text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* @file measurement_systen_node.cpp
* @author Izabella Thais Oliveira Gomes
* @date 23/09/2016
*
* @attention Copyright (C) 2014 UnBall Robot Soccer Team
*
* @brief Rotate robot position datas acording to camera position in the vision and simulator and publishes that.
*
*/
#include <vector>
#include <cmath>
#include <ros/ros.h>
#include <unball/VisionMessage.h>
#include <unball/SimulatorMessage.h>
#include <unball/MeasurementSystemMessage.h>
#include <opencv2/opencv.hpp>
const float field_x_length = 1.50;
const float field_y_length = 1.30;
const float camera_x_length = 640;
const float camera_y_length = 480;
void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_s);
void rotateAxis();
void convertPixelsToMeters();
void receiveSimulatorMessage(const unball::SimulatorMessage::ConstPtr &msg_v);
void publishMeasurementSystemMessage(ros::Publisher &publisher);
void filter();
unball::MeasurementSystemMessage message;
ros::Publisher publisher;
int main(int argc, char **argv)
{
ros::init(argc, argv, "measurement_system_node");
ros::NodeHandle n;
ros::Rate loop_rate(10); // Hz
ros::Subscriber sub = n.subscribe("vision_topic", 1, receiveVisionMessage);
publisher = n.advertise<unball::MeasurementSystemMessage>("measurement_system_topic", 1);
while (ros::ok())
{
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_v)
{
std::vector<float> x(6), y(6), th(6);
std::vector<float> ball_location(2);
ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Receiving vision message");
for (int robot_index = 0; robot_index < 6; robot_index++)
{
ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, msg_v->x[robot_index], msg_v->y[robot_index],
msg_v->th[robot_index]);
if (not (msg_v->x[robot_index] == -1 and msg_v->y[robot_index] == -1))
{
message.x[robot_index] = msg_v->x[robot_index];
message.y[robot_index] = msg_v->y[robot_index];
if (not std::isnan(msg_v->th[robot_index])){
message.th[robot_index] = msg_v->th[robot_index] * -1;
}
}
//if(message.th[robot_index]!=0){
// message.th[robot_index] = msg_v->th[robot_index] * -1;
//}
}
message.ball_x = msg_v->ball_x;
message.ball_y = msg_v->ball_y;
convertPixelsToMeters();
filter();
ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Sending measurement system message");
for (int robot_index = 0; robot_index < 6; robot_index++)
{
ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, message.x[robot_index], message.y[robot_index],
message.th[robot_index]);
}
ROS_INFO("Ball: x: %f, y: %f", message.ball_x, message.ball_y);
publisher.publish(message);
}
void convertPixelsToMeters(){
auto x_conversion = field_x_length / camera_x_length;
auto y_conversion = (field_y_length / camera_y_length) * -1;
for (int i = 0; i < 6; ++i)
{
message.x[i] -= camera_x_length / 2;
message.y[i] -= camera_y_length / 2;
message.x[i] *= x_conversion;
message.y[i] *= y_conversion;
}
message.ball_x -= camera_x_length / 2;
message.ball_y -= camera_y_length / 2;
message.ball_x *= x_conversion;
message.ball_y *= y_conversion;
}
float mean_array_x[6]={0,0,0,0,0,0};
float mean_array_y[6]={0,0,0,0,0,0};
float mean_ball_x=0;
float mean_ball_y=0;
float mean_array_th[6]={0,0,0,0,0,0};
float N_mean=4;
void filter(){
for (int i = 0; i < 6; ++i)
{
mean_array_x[i] += (message.x[i] - mean_array_x[i])/N_mean;
message.x[i] = mean_array_x[i];
mean_array_y[i] += (message.y[i] - mean_array_y[i])/N_mean;
message.y[i] = mean_array_y[i];
if (not std::isnan(mean_array_th[i] + (message.th[i] - mean_array_th[i])/N_mean)) {
if(abs(message.th[i]-mean_array_th[i])>M_PI/2){
mean_array_th[i]=message.th[i];
}else{
mean_array_th[i] += (message.th[i] - mean_array_th[i])/N_mean;
}
message.th[i] = mean_array_th[i];
}
}
mean_ball_x += (message.ball_x - mean_ball_x)/N_mean;
message.ball_x = mean_ball_x;
mean_ball_y += (message.ball_y - mean_ball_y)/N_mean;
message.ball_y = mean_ball_y;
}<commit_msg>final ajusts<commit_after>/**
* @file measurement_systen_node.cpp
* @author Izabella Thais Oliveira Gomes
* @date 23/09/2016
*
* @attention Copyright (C) 2014 UnBall Robot Soccer Team
*
* @brief Rotate robot position datas acording to camera position in the vision and simulator and publishes that.
*
*/
#include <vector>
#include <cmath>
#include <ros/ros.h>
#include <unball/VisionMessage.h>
#include <unball/SimulatorMessage.h>
#include <unball/MeasurementSystemMessage.h>
#include <opencv2/opencv.hpp>
//const float field_x_length = 1.50;
//const float field_y_length = 1.30;
const float field_x_length = 1.60;
const float field_y_length = 1.30;
const float camera_x_length = 640;
const float camera_y_length = 480;
void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_s);
void rotateAxis();
void convertPixelsToMeters();
void receiveSimulatorMessage(const unball::SimulatorMessage::ConstPtr &msg_v);
void publishMeasurementSystemMessage(ros::Publisher &publisher);
void filter();
unball::MeasurementSystemMessage message;
ros::Publisher publisher;
int main(int argc, char **argv)
{
ros::init(argc, argv, "measurement_system_node");
ros::NodeHandle n;
ros::Rate loop_rate(10); // Hz
ros::Subscriber sub = n.subscribe("vision_topic", 1, receiveVisionMessage);
publisher = n.advertise<unball::MeasurementSystemMessage>("measurement_system_topic", 1);
while (ros::ok())
{
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_v)
{
std::vector<float> x(6), y(6), th(6);
std::vector<float> ball_location(2);
ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Receiving vision message");
for (int robot_index = 0; robot_index < 6; robot_index++)
{
ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, msg_v->x[robot_index], msg_v->y[robot_index],
msg_v->th[robot_index]);
if (not (msg_v->x[robot_index] == -1 and msg_v->y[robot_index] == -1))
{
message.x[robot_index] = msg_v->x[robot_index];
message.y[robot_index] = msg_v->y[robot_index];
if (not std::isnan(msg_v->th[robot_index])){
message.th[robot_index] = msg_v->th[robot_index];
}
}
}
message.ball_x = msg_v->ball_x;
message.ball_y = msg_v->ball_y;
convertPixelsToMeters();
//filter();
ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Sending measurement system message");
for (int robot_index = 0; robot_index < 6; robot_index++)
{
ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, message.x[robot_index], message.y[robot_index],
message.th[robot_index]);
}
ROS_INFO("Ball: x: %f, y: %f", message.ball_x, message.ball_y);
publisher.publish(message);
}
void convertPixelsToMeters(){
auto x_conversion = field_x_length / camera_x_length;
auto y_conversion = (field_y_length / camera_y_length) * -1;
for (int i = 0; i < 6; ++i)
{
message.x[i] -= camera_x_length / 2;
message.y[i] -= camera_y_length / 2;
message.x[i] *= x_conversion;
message.y[i] *= y_conversion;
}
message.ball_x -= camera_x_length / 2;
message.ball_y -= camera_y_length / 2;
message.ball_x *= x_conversion;
message.ball_y *= y_conversion;
}
float mean_array_x[6]={0,0,0,0,0,0};
float mean_array_y[6]={0,0,0,0,0,0};
float mean_ball_x=0;
float mean_ball_y=0;
float mean_array_th[6]={0,0,0,0,0,0};
float N_mean=10;
void filter(){
for (int i = 0; i < 6; ++i)
{
mean_array_x[i] += (message.x[i] - mean_array_x[i])/N_mean;
message.x[i] = mean_array_x[i];
mean_array_y[i] += (message.y[i] - mean_array_y[i])/N_mean;
message.y[i] = mean_array_y[i];
if (not std::isnan(mean_array_th[i] + (message.th[i] - mean_array_th[i])/N_mean)) {
if(abs(message.th[i]-mean_array_th[i])>M_PI/2){
mean_array_th[i]=message.th[i];
}else{
mean_array_th[i] += (message.th[i] - mean_array_th[i])/N_mean;
}
message.th[i] = mean_array_th[i];
}
}
mean_ball_x += (message.ball_x - mean_ball_x)/N_mean;
message.ball_x = mean_ball_x;
mean_ball_y += (message.ball_y - mean_ball_y)/N_mean;
message.ball_y = mean_ball_y;
}<|endoftext|> |
<commit_before>#include "dll/dbn.hpp"
template<typename DBN>
void test_dbn(){
DBN dbn;
dbn.display();
std::vector<vector<double>> images;
std::vector<vector<double>> labels;
dbn.pretrain(images, 10);
dbn.fine_tune(images, labels, 10, 10);
}
template <typename RBM>
using pcd2_trainer_t = dll::persistent_cd_trainer<2, RBM>;
int main(){
//Basic example
typedef dll::dbn<
dll::layer<28 * 28, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>, dll::init_weights, dll::weight_decay<dll::decay_type::L2>, dll::sparsity>,
dll::layer<100, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>>,
dll::layer<110, 200, dll::in_dbn, dll::batch_size<50>, dll::momentum, dll::weight_decay<dll::decay_type::L2_FULL>>
> dbn_1;
//Test them all
test_dbn<dbn_1>();
return 0;
}<commit_msg>Fix test<commit_after>#include "dll/dbn.hpp"
template<typename DBN>
void test_dbn(){
DBN dbn;
dbn.display();
std::vector<vector<double>> images;
std::vector<uint8_t> labels;
dbn.pretrain(images, 10);
dbn.fine_tune(images, labels, 10, 10);
}
template <typename RBM>
using pcd2_trainer_t = dll::persistent_cd_trainer<2, RBM>;
int main(){
//Basic example
typedef dll::dbn<
dll::layer<28 * 28, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>, dll::init_weights, dll::weight_decay<dll::decay_type::L2>, dll::sparsity>,
dll::layer<100, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>>,
dll::layer<110, 200, dll::in_dbn, dll::batch_size<50>, dll::momentum, dll::weight_decay<dll::decay_type::L2_FULL>>
> dbn_1;
//Test them all
test_dbn<dbn_1>();
return 0;
}<|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 "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "base/hash_tables.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
namespace chromeos {
// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryImpl() {
if (CrosLibrary::Get()->EnsureLoaded())
Init();
}
virtual ~CryptohomeLibraryImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str());
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()),
d,
"Couldn't initiate async check of user's key.");
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return chromeos::CryptohomeMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str());
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str()),
d,
"Couldn't initiate aync migration of user's key");
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return chromeos::CryptohomeMountAllowFail(user_email.c_str(),
passhash.c_str(),
error_code);
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
const bool create_if_missing,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMount(user_email.c_str(),
passhash.c_str(),
create_if_missing,
"",
std::vector<std::string>()),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool MountForBwsi(int* error_code) {
return chromeos::CryptohomeMountGuest(error_code);
}
bool AsyncMountForBwsi(Delegate* d) {
return CacheCallback(chromeos::CryptohomeAsyncMountGuest(),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool Remove(const std::string& user_email) {
return chromeos::CryptohomeRemove(user_email.c_str());
}
bool AsyncRemove(const std::string& user_email, Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncRemove(user_email.c_str()),
d,
"Couldn't initiate async removal of cryptohome.");
}
bool IsMounted() {
return chromeos::CryptohomeIsMounted();
}
CryptohomeBlob GetSystemSalt() {
return chromeos::CryptohomeGetSystemSalt();
}
private:
static void Handler(const chromeos::CryptohomeAsyncCallStatus& event,
void* cryptohome_library) {
CryptohomeLibraryImpl* library =
reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library);
library->Dispatch(event);
}
void Init() {
cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this);
}
void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) {
callback_map_[event.async_id]->OnComplete(event.return_status,
event.return_code);
callback_map_[event.async_id] = NULL;
}
bool CacheCallback(int async_id,
Delegate* d,
const char* error) {
if (async_id == 0) {
LOG(ERROR) << error;
return false;
}
callback_map_[async_id] = d;
return true;
}
typedef base::hash_map<int, Delegate*> CallbackMap;
mutable CallbackMap callback_map_;
void* cryptohome_connection_;
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};
class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryStubImpl() {}
virtual ~CryptohomeLibraryStubImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return true;
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return true;
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Remove(const std::string& user_email) {
return true;
}
bool AsyncRemove(const std::string& user_email, Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return true;
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
const bool create_if_missing,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MountForBwsi(int* error_code) {
return true;
}
bool AsyncMountForBwsi(Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool IsMounted() {
return true;
}
CryptohomeBlob GetSystemSalt() {
CryptohomeBlob salt = CryptohomeBlob();
salt.push_back(0);
salt.push_back(0);
return salt;
}
private:
static void DoStubCallback(Delegate* callback) {
callback->OnComplete(true, kCryptohomeMountErrorNone);
}
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};
// static
CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) {
if (stub)
return new CryptohomeLibraryStubImpl();
else
return new CryptohomeLibraryImpl();
}
} // namespace chromeos
<commit_msg>[Chrome OS] Log and handle cryptohomed callbacks for calls we didn't initiate<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 "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "base/hash_tables.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
namespace chromeos {
// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryImpl() {
if (CrosLibrary::Get()->EnsureLoaded())
Init();
}
virtual ~CryptohomeLibraryImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str());
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()),
d,
"Couldn't initiate async check of user's key.");
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return chromeos::CryptohomeMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str());
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str()),
d,
"Couldn't initiate aync migration of user's key");
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return chromeos::CryptohomeMountAllowFail(user_email.c_str(),
passhash.c_str(),
error_code);
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
const bool create_if_missing,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMount(user_email.c_str(),
passhash.c_str(),
create_if_missing,
"",
std::vector<std::string>()),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool MountForBwsi(int* error_code) {
return chromeos::CryptohomeMountGuest(error_code);
}
bool AsyncMountForBwsi(Delegate* d) {
return CacheCallback(chromeos::CryptohomeAsyncMountGuest(),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool Remove(const std::string& user_email) {
return chromeos::CryptohomeRemove(user_email.c_str());
}
bool AsyncRemove(const std::string& user_email, Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncRemove(user_email.c_str()),
d,
"Couldn't initiate async removal of cryptohome.");
}
bool IsMounted() {
return chromeos::CryptohomeIsMounted();
}
CryptohomeBlob GetSystemSalt() {
return chromeos::CryptohomeGetSystemSalt();
}
private:
static void Handler(const chromeos::CryptohomeAsyncCallStatus& event,
void* cryptohome_library) {
CryptohomeLibraryImpl* library =
reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library);
library->Dispatch(event);
}
void Init() {
cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this);
}
void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) {
if (!callback_map_[event.async_id]) {
LOG(ERROR) << "Received signal for unknown async_id " << event.async_id;
return;
}
callback_map_[event.async_id]->OnComplete(event.return_status,
event.return_code);
callback_map_[event.async_id] = NULL;
}
bool CacheCallback(int async_id, Delegate* d, const char* error) {
if (async_id == 0) {
LOG(ERROR) << error;
return false;
}
LOG(INFO) << "Adding handler for " << async_id;
callback_map_[async_id] = d;
return true;
}
typedef base::hash_map<int, Delegate*> CallbackMap;
mutable CallbackMap callback_map_;
void* cryptohome_connection_;
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};
class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryStubImpl() {}
virtual ~CryptohomeLibraryStubImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return true;
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return true;
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Remove(const std::string& user_email) {
return true;
}
bool AsyncRemove(const std::string& user_email, Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return true;
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
const bool create_if_missing,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MountForBwsi(int* error_code) {
return true;
}
bool AsyncMountForBwsi(Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool IsMounted() {
return true;
}
CryptohomeBlob GetSystemSalt() {
CryptohomeBlob salt = CryptohomeBlob();
salt.push_back(0);
salt.push_back(0);
return salt;
}
private:
static void DoStubCallback(Delegate* callback) {
callback->OnComplete(true, kCryptohomeMountErrorNone);
}
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};
// static
CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) {
if (stub)
return new CryptohomeLibraryStubImpl();
else
return new CryptohomeLibraryImpl();
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtk/gtk.h>
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/gtk/bookmark_editor_gtk.h"
#include "chrome/browser/gtk/bookmark_tree_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using bookmark_utils::GetTitleFromTreeIter;
// Base class for bookmark editor tests. This class is a copy from
// bookmark_editor_view_unittest.cc, and all the tests in this file are
// GTK-ifications of the corresponding views tests. Testing here is really
// important because on Linux, we make round trip copies from chrome's
// BookmarkModel class to GTK's native GtkTreeStore.
class BookmarkEditorGtkTest : public testing::Test {
public:
BookmarkEditorGtkTest() : model_(NULL) {
}
virtual void SetUp() {
profile_.reset(new TestingProfile());
profile_->set_has_history_service(true);
profile_->CreateBookmarkModel(true);
model_ = profile_->GetBookmarkModel();
AddTestData();
}
virtual void TearDown() {
}
protected:
MessageLoopForUI message_loop_;
BookmarkModel* model_;
scoped_ptr<TestingProfile> profile_;
std::string base_path() const { return "file:///c:/tmp/"; }
BookmarkNode* GetNode(const std::string& name) {
return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name));
}
private:
// Creates the following structure:
// bookmark bar node
// a
// F1
// f1a
// F11
// f11a
// F2
// other node
// oa
// OF1
// of1a
void AddTestData() {
std::string test_base = base_path();
model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a",
GURL(test_base + "a"));
BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1");
model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a"));
BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11");
model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a"));
model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2");
// Children of the other node.
model_->AddURL(model_->other_node(), 0, L"oa",
GURL(test_base + "oa"));
BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1");
model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a"));
}
};
// Makes sure the tree model matches that of the bookmark bar model.
TEST_F(BookmarkEditorGtkTest, ModelsMatch) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
// The root should have two children, one for the bookmark bar node,
// the other for the 'other bookmarks' folder.
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter toplevel;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel));
GtkTreeIter bookmark_bar_node = toplevel;
ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel));
GtkTreeIter other_node = toplevel;
ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f1_iter;
GtkTreeIter child;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node));
f1_iter = child;
ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &child));
ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// F1 should have one child, F11
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter));
ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// Other node should have one child (OF1).
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node));
ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
}
// Changes the title and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle());
// The URL shouldn't have changed.
ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL());
}
// Changes the url and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle());
// The URL should have changed.
ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL());
ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added());
}
// Moves 'a' to be a child of the other node.
TEST_F(BookmarkEditorGtkTest, ChangeParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL());
}
// Moves 'a' to be a child of the other node.
// Moves 'a' to be a child of the other node and changes its url to new_a.
TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL());
ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added());
}
// Creates a new folder and moves a node to it.
TEST_F(BookmarkEditorGtkTest, MoveToNewParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f2_iter;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter,
&bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter));
// Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21".
GtkTreeIter f21_iter;
editor.AddNewGroup(&f2_iter, &f21_iter);
gtk_tree_store_set(editor.tree_store_, &f21_iter,
bookmark_utils::FOLDER_NAME, "F21", -1);
GtkTreeIter f211_iter;
editor.AddNewGroup(&f21_iter, &f211_iter);
gtk_tree_store_set(editor.tree_store_, &f211_iter,
bookmark_utils::FOLDER_NAME, "F211", -1);
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter));
editor.ApplyEdits(&f2_iter);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
BookmarkNode* mf2 = bb_node->GetChild(1);
// F2 in the model should have two children now: F21 and the node edited.
ASSERT_EQ(2, mf2->GetChildCount());
// F21 should be first.
ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle());
// Then a.
ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle());
// F21 should have one child, F211.
BookmarkNode* mf21 = mf2->GetChild(0);
ASSERT_EQ(1, mf21->GetChildCount());
ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle());
}
// Brings up the editor, creating a new URL on the bookmark bar.
TEST_F(BookmarkEditorGtkTest, NewURL) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(4, bb_node->GetChildCount());
BookmarkNode* new_node = bb_node->GetChild(3);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies the url.
TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits(NULL);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies only the title.
TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits();
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
}
<commit_msg>Disable a failing test on linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtk/gtk.h>
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/gtk/bookmark_editor_gtk.h"
#include "chrome/browser/gtk/bookmark_tree_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using bookmark_utils::GetTitleFromTreeIter;
// Base class for bookmark editor tests. This class is a copy from
// bookmark_editor_view_unittest.cc, and all the tests in this file are
// GTK-ifications of the corresponding views tests. Testing here is really
// important because on Linux, we make round trip copies from chrome's
// BookmarkModel class to GTK's native GtkTreeStore.
class BookmarkEditorGtkTest : public testing::Test {
public:
BookmarkEditorGtkTest() : model_(NULL) {
}
virtual void SetUp() {
profile_.reset(new TestingProfile());
profile_->set_has_history_service(true);
profile_->CreateBookmarkModel(true);
model_ = profile_->GetBookmarkModel();
AddTestData();
}
virtual void TearDown() {
}
protected:
MessageLoopForUI message_loop_;
BookmarkModel* model_;
scoped_ptr<TestingProfile> profile_;
std::string base_path() const { return "file:///c:/tmp/"; }
BookmarkNode* GetNode(const std::string& name) {
return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name));
}
private:
// Creates the following structure:
// bookmark bar node
// a
// F1
// f1a
// F11
// f11a
// F2
// other node
// oa
// OF1
// of1a
void AddTestData() {
std::string test_base = base_path();
model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a",
GURL(test_base + "a"));
BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1");
model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a"));
BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11");
model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a"));
model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2");
// Children of the other node.
model_->AddURL(model_->other_node(), 0, L"oa",
GURL(test_base + "oa"));
BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1");
model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a"));
}
};
// Makes sure the tree model matches that of the bookmark bar model.
TEST_F(BookmarkEditorGtkTest, ModelsMatch) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
// The root should have two children, one for the bookmark bar node,
// the other for the 'other bookmarks' folder.
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter toplevel;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel));
GtkTreeIter bookmark_bar_node = toplevel;
ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel));
GtkTreeIter other_node = toplevel;
ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f1_iter;
GtkTreeIter child;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node));
f1_iter = child;
ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &child));
ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// F1 should have one child, F11
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter));
ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// Other node should have one child (OF1).
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node));
ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
}
// Changes the title and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle());
// The URL shouldn't have changed.
ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL());
}
// Changes the url and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle());
// The URL should have changed.
ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL());
ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added());
}
// Moves 'a' to be a child of the other node.
TEST_F(BookmarkEditorGtkTest, ChangeParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL());
}
// Moves 'a' to be a child of the other node.
// Moves 'a' to be a child of the other node and changes its url to new_a.
TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL());
ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added());
}
// TODO(tc): Test failing. Can't use DISABLED_ because of FRIEND_TEST.
#if 0
// Creates a new folder and moves a node to it.
TEST_F(BookmarkEditorGtkTest, MoveToNewParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f2_iter;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter,
&bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter));
// Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21".
GtkTreeIter f21_iter;
editor.AddNewGroup(&f2_iter, &f21_iter);
gtk_tree_store_set(editor.tree_store_, &f21_iter,
bookmark_utils::FOLDER_NAME, "F21", -1);
GtkTreeIter f211_iter;
editor.AddNewGroup(&f21_iter, &f211_iter);
gtk_tree_store_set(editor.tree_store_, &f211_iter,
bookmark_utils::FOLDER_NAME, "F211", -1);
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter));
editor.ApplyEdits(&f2_iter);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
BookmarkNode* mf2 = bb_node->GetChild(1);
// F2 in the model should have two children now: F21 and the node edited.
ASSERT_EQ(2, mf2->GetChildCount());
// F21 should be first.
ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle());
// Then a.
ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle());
// F21 should have one child, F211.
BookmarkNode* mf21 = mf2->GetChild(0);
ASSERT_EQ(1, mf21->GetChildCount());
ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle());
}
#endif
// Brings up the editor, creating a new URL on the bookmark bar.
TEST_F(BookmarkEditorGtkTest, NewURL) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(4, bb_node->GetChildCount());
BookmarkNode* new_node = bb_node->GetChild(3);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies the url.
TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits(NULL);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies only the title.
TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits();
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <memory>
#include <algorithm>
#include <vector>
#include "platform_tizen.h"
#include "platform_gl.h"
#include "urlWorker.h"
#include "log.h"
#include <libgen.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <fontconfig.h>
#include <dlog.h>
#define NUM_WORKERS 4
static bool s_isContinuousRendering = false;
static std::function<void()> s_renderCallbackFunction = nullptr;
static std::vector<std::string> s_fallbackFonts;
static FcConfig* s_fcConfig = nullptr;
static UrlWorker s_workers;
bool startUrlRequest(const std::string& _url, UrlCallback _callback) {
s_workers.enqueue(std::make_unique<UrlTask>(_url, _callback));
return true;
}
void cancelUrlRequest(const std::string& _url) {
s_workers.cancel(_url);
}
void initUrlRequests(const char* proxyAddress) {
s_workers.start(4, proxyAddress);
}
void stopUrlRequests() {
s_workers.stop();
}
static bool s_update = false;
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "Tangram"
void logMsg(const char* fmt, ...) {
va_list vl;
va_start(vl, fmt);
dlog_vprint(DLOG_WARN, LOG_TAG, fmt, vl);
va_end(vl);
}
void setRenderCallbackFunction(std::function<void()> callback) {
s_renderCallbackFunction = callback;
}
void setEvasGlAPI(Evas_GL_API *glApi) {
__evas_gl_glapi = glApi;
}
void requestRender() {
s_update = true;
if (s_renderCallbackFunction) {
s_renderCallbackFunction();
}
}
bool shouldRender() {
bool update = s_update;
s_update = false;
return update;
}
void setContinuousRendering(bool _isContinuous) {
s_isContinuousRendering = _isContinuous;
}
bool isContinuousRendering() {
return s_isContinuousRendering;
}
void initPlatformFontSetup() {
static bool s_platformFontsInit = false;
if (s_platformFontsInit) { return; }
s_fcConfig = FcInitLoadConfigAndFonts();
std::string style = "Regular";
FcStrSet* fcLangs = FcGetLangs();
FcStrList* fcLangList = FcStrListCreate(fcLangs);
FcChar8* fcLang;
while ((fcLang = FcStrListNext(fcLangList))) {
FcValue fcStyleValue, fcLangValue;
fcStyleValue.type = fcLangValue.type = FcType::FcTypeString;
fcStyleValue.u.s = reinterpret_cast<const FcChar8*>(style.c_str());
fcLangValue.u.s = fcLang;
// create a pattern with style and family font properties
FcPattern* pat = FcPatternCreate();
FcPatternAdd(pat, FC_STYLE, fcStyleValue, true);
FcPatternAdd(pat, FC_LANG, fcLangValue, true);
//FcPatternPrint(pat);
FcConfigSubstitute(s_fcConfig, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
FcResult res;
FcPattern* font = FcFontMatch(s_fcConfig, pat, &res);
if (font) {
FcChar8* file = nullptr;
if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch) {
// Make sure this font file is not previously added.
if (std::find(s_fallbackFonts.begin(), s_fallbackFonts.end(),
reinterpret_cast<char*>(file)) == s_fallbackFonts.end()) {
s_fallbackFonts.emplace_back(reinterpret_cast<char*>(file));
}
}
FcPatternDestroy(font);
}
FcPatternDestroy(pat);
}
FcStrListDone(fcLangList);
s_platformFontsInit = true;
}
std::vector<FontSourceHandle> systemFontFallbacksHandle() {
initPlatformFontSetup();
std::vector<FontSourceHandle> handles;
for (auto& path : s_fallbackFonts) {
FontSourceHandle fontSourceHandle = [&](size_t* _size) -> unsigned char* {
LOG("Loading font %s", path.c_str());
auto cdata = bytesFromFile(path.c_str(), *_size);
return cdata;
};
handles.push_back(fontSourceHandle);
}
return handles;
}
std::string fontPath(const std::string& _name, const std::string& _weight,
const std::string& _face) {
initPlatformFontSetup();
if (!s_fcConfig) {
return "";
}
std::string fontFile = "";
FcValue fcFamily, fcFace, fcWeight;
fcFamily.type = fcFace.type = fcWeight.type = FcType::FcTypeString;
fcFamily.u.s = reinterpret_cast<const FcChar8*>(_name.c_str());
fcWeight.u.s = reinterpret_cast<const FcChar8*>(_weight.c_str());
fcFace.u.s = reinterpret_cast<const FcChar8*>(_face.c_str());
// Create a pattern with family, style and weight font properties
FcPattern* pattern = FcPatternCreate();
FcPatternAdd(pattern, FC_FAMILY, fcFamily, true);
FcPatternAdd(pattern, FC_STYLE, fcFace, true);
FcPatternAdd(pattern, FC_WEIGHT, fcWeight, true);
//FcPatternPrint(pattern);
FcConfigSubstitute(s_fcConfig, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
FcResult res;
FcPattern* font = FcFontMatch(s_fcConfig, pattern, &res);
if (font) {
FcChar8* file = nullptr;
FcChar8* fontFamily = nullptr;
if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch &&
FcPatternGetString(font, FC_FAMILY, 0, &fontFamily) == FcResultMatch) {
// We do not want the "best" match, but an "exact" or at least the same "family" match
// We have fallbacks to cover rest here.
if (strcmp(reinterpret_cast<const char*>(fontFamily), _name.c_str()) == 0) {
fontFile = reinterpret_cast<const char*>(file);
}
}
FcPatternDestroy(font);
}
FcPatternDestroy(pattern);
return fontFile;
}
unsigned char* systemFont(const std::string& _name, const std::string& _weight, const std::string& _face, size_t* _size) {
std::string path = fontPath(_name, _weight, _face);
if (path.empty()) { return nullptr; }
return bytesFromFile(path.c_str(), *_size);
}
unsigned char* bytesFromFile(const char* _path, size_t& _size) {
if (!_path || strlen(_path) == 0) { return nullptr; }
std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);
if(!resource.is_open()) {
logMsg("Failed to read file at path: %s\n", _path);
_size = 0;
return nullptr;
}
_size = resource.tellg();
resource.seekg(std::ifstream::beg);
char* cdata = (char*) malloc(sizeof(char) * (_size));
resource.read(cdata, _size);
resource.close();
return reinterpret_cast<unsigned char *>(cdata);
}
std::string stringFromFile(const char* _path) {
std::string out;
if (!_path || strlen(_path) == 0) { return out; }
std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);
if(!resource.is_open()) {
logMsg("Failed to read file at path: %s\n", _path);
return out;
}
resource.seekg(0, std::ios::end);
out.resize(resource.tellg());
resource.seekg(0, std::ios::beg);
resource.read(&out[0], out.size());
resource.close();
return out;
}
void setCurrentThreadPriority(int priority){
int tid = syscall(SYS_gettid);
//int p1 = getpriority(PRIO_PROCESS, tid);
setpriority(PRIO_PROCESS, tid, priority);
//int p2 = getpriority(PRIO_PROCESS, tid);
//logMsg("set niceness: %d -> %d\n", p1, p2);
}
void initGLExtensions() {
// glBindVertexArrayOESEXT = (PFNGLBINDVERTEXARRAYPROC)glfwGetProcAddress("glBindVertexArray");
// glDeleteVertexArraysOESEXT = (PFNGLDELETEVERTEXARRAYSPROC)glfwGetProcAddress("glDeleteVertexArrays");
// glGenVertexArraysOESEXT = (PFNGLGENVERTEXARRAYSPROC)glfwGetProcAddress("glGenVertexArrays");
}
<commit_msg>Fix tizen fontfallback loading<commit_after>#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <memory>
#include <algorithm>
#include <vector>
#include "platform_tizen.h"
#include "platform_gl.h"
#include "urlWorker.h"
#include "log.h"
#include <libgen.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <fontconfig.h>
#include <dlog.h>
#define NUM_WORKERS 4
static bool s_isContinuousRendering = false;
static std::function<void()> s_renderCallbackFunction = nullptr;
static std::vector<std::string> s_fallbackFonts;
static FcConfig* s_fcConfig = nullptr;
static UrlWorker s_workers;
bool startUrlRequest(const std::string& _url, UrlCallback _callback) {
s_workers.enqueue(std::make_unique<UrlTask>(_url, _callback));
return true;
}
void cancelUrlRequest(const std::string& _url) {
s_workers.cancel(_url);
}
void initUrlRequests(const char* proxyAddress) {
s_workers.start(4, proxyAddress);
}
void stopUrlRequests() {
s_workers.stop();
}
static bool s_update = false;
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "Tangram"
void logMsg(const char* fmt, ...) {
va_list vl;
va_start(vl, fmt);
dlog_vprint(DLOG_WARN, LOG_TAG, fmt, vl);
va_end(vl);
}
void setRenderCallbackFunction(std::function<void()> callback) {
s_renderCallbackFunction = callback;
}
void setEvasGlAPI(Evas_GL_API *glApi) {
__evas_gl_glapi = glApi;
}
void requestRender() {
s_update = true;
if (s_renderCallbackFunction) {
s_renderCallbackFunction();
}
}
bool shouldRender() {
bool update = s_update;
s_update = false;
return update;
}
void setContinuousRendering(bool _isContinuous) {
s_isContinuousRendering = _isContinuous;
}
bool isContinuousRendering() {
return s_isContinuousRendering;
}
void initPlatformFontSetup() {
static bool s_platformFontsInit = false;
if (s_platformFontsInit) { return; }
s_fcConfig = FcInitLoadConfigAndFonts();
std::string style = "Regular";
FcStrSet* fcLangs = FcGetLangs();
FcStrList* fcLangList = FcStrListCreate(fcLangs);
FcChar8* fcLang;
while ((fcLang = FcStrListNext(fcLangList))) {
FcValue fcStyleValue, fcLangValue;
fcStyleValue.type = fcLangValue.type = FcType::FcTypeString;
fcStyleValue.u.s = reinterpret_cast<const FcChar8*>(style.c_str());
fcLangValue.u.s = fcLang;
// create a pattern with style and family font properties
FcPattern* pat = FcPatternCreate();
FcPatternAdd(pat, FC_STYLE, fcStyleValue, true);
FcPatternAdd(pat, FC_LANG, fcLangValue, true);
//FcPatternPrint(pat);
FcConfigSubstitute(s_fcConfig, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
FcResult res;
FcPattern* font = FcFontMatch(s_fcConfig, pat, &res);
if (font) {
FcChar8* file = nullptr;
if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch) {
// Make sure this font file is not previously added.
if (std::find(s_fallbackFonts.begin(), s_fallbackFonts.end(),
reinterpret_cast<char*>(file)) == s_fallbackFonts.end()) {
s_fallbackFonts.emplace_back(reinterpret_cast<char*>(file));
}
}
FcPatternDestroy(font);
}
FcPatternDestroy(pat);
}
FcStrListDone(fcLangList);
s_platformFontsInit = true;
}
std::vector<FontSourceHandle> systemFontFallbacksHandle() {
initPlatformFontSetup();
std::vector<FontSourceHandle> handles;
for (auto& path : s_fallbackFonts) {
handles.emplace_back(path);
}
return handles;
}
std::string fontPath(const std::string& _name, const std::string& _weight,
const std::string& _face) {
initPlatformFontSetup();
if (!s_fcConfig) {
return "";
}
std::string fontFile = "";
FcValue fcFamily, fcFace, fcWeight;
fcFamily.type = fcFace.type = fcWeight.type = FcType::FcTypeString;
fcFamily.u.s = reinterpret_cast<const FcChar8*>(_name.c_str());
fcWeight.u.s = reinterpret_cast<const FcChar8*>(_weight.c_str());
fcFace.u.s = reinterpret_cast<const FcChar8*>(_face.c_str());
// Create a pattern with family, style and weight font properties
FcPattern* pattern = FcPatternCreate();
FcPatternAdd(pattern, FC_FAMILY, fcFamily, true);
FcPatternAdd(pattern, FC_STYLE, fcFace, true);
FcPatternAdd(pattern, FC_WEIGHT, fcWeight, true);
//FcPatternPrint(pattern);
FcConfigSubstitute(s_fcConfig, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
FcResult res;
FcPattern* font = FcFontMatch(s_fcConfig, pattern, &res);
if (font) {
FcChar8* file = nullptr;
FcChar8* fontFamily = nullptr;
if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch &&
FcPatternGetString(font, FC_FAMILY, 0, &fontFamily) == FcResultMatch) {
// We do not want the "best" match, but an "exact" or at least the same "family" match
// We have fallbacks to cover rest here.
if (strcmp(reinterpret_cast<const char*>(fontFamily), _name.c_str()) == 0) {
fontFile = reinterpret_cast<const char*>(file);
}
}
FcPatternDestroy(font);
}
FcPatternDestroy(pattern);
return fontFile;
}
unsigned char* systemFont(const std::string& _name, const std::string& _weight, const std::string& _face, size_t* _size) {
std::string path = fontPath(_name, _weight, _face);
if (path.empty()) { return nullptr; }
return bytesFromFile(path.c_str(), *_size);
}
unsigned char* bytesFromFile(const char* _path, size_t& _size) {
if (!_path || strlen(_path) == 0) { return nullptr; }
std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);
if(!resource.is_open()) {
logMsg("Failed to read file at path: %s\n", _path);
_size = 0;
return nullptr;
}
_size = resource.tellg();
resource.seekg(std::ifstream::beg);
char* cdata = (char*) malloc(sizeof(char) * (_size));
resource.read(cdata, _size);
resource.close();
return reinterpret_cast<unsigned char *>(cdata);
}
std::string stringFromFile(const char* _path) {
std::string out;
if (!_path || strlen(_path) == 0) { return out; }
std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);
if(!resource.is_open()) {
logMsg("Failed to read file at path: %s\n", _path);
return out;
}
resource.seekg(0, std::ios::end);
out.resize(resource.tellg());
resource.seekg(0, std::ios::beg);
resource.read(&out[0], out.size());
resource.close();
return out;
}
void setCurrentThreadPriority(int priority){
int tid = syscall(SYS_gettid);
//int p1 = getpriority(PRIO_PROCESS, tid);
setpriority(PRIO_PROCESS, tid, priority);
//int p2 = getpriority(PRIO_PROCESS, tid);
//logMsg("set niceness: %d -> %d\n", p1, p2);
}
void initGLExtensions() {
// glBindVertexArrayOESEXT = (PFNGLBINDVERTEXARRAYPROC)glfwGetProcAddress("glBindVertexArray");
// glDeleteVertexArraysOESEXT = (PFNGLDELETEVERTEXARRAYSPROC)glfwGetProcAddress("glDeleteVertexArrays");
// glGenVertexArraysOESEXT = (PFNGLGENVERTEXARRAYSPROC)glfwGetProcAddress("glGenVertexArrays");
}
<|endoftext|> |
<commit_before>// @(#)root/roostats:$Id$
// Author: Kyle Cranmer 28/07/2008
/*************************************************************************
* Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//_________________________________________________
/*
BEGIN_HTML
<p>
ProfileLikelihoodCalculator is a concrete implementation of CombinedCalculator
(the interface class for a tools which can produce both RooStats HypoTestResults and ConfIntervals).
The tool uses the profile likelihood ratio as a test statistic, and assumes that Wilks' theorem is valid.
Wilks' theorem states that -2* log (profile likelihood ratio) is asymptotically distributed as a chi^2 distribution
with N-dof, where N is the number of degrees of freedom. Thus, p-values can be constructed and the profile likelihood ratio
can be used to construct a LikelihoodInterval.
(In the future, this class could be extended to use toy Monte Carlo to calibrate the distribution of the test statistic).
</p>
<p> Usage: It uses the interface of the CombinedCalculator, so that it can be configured by specifying:
<ul>
<li>a model common model (eg. a family of specific models which includes both the null and alternate),</li>
<li>a data set, </li>
<li>a set of parameters of interest. The nuisance parameters will be all other parameters of the model </li>
<li>a set of parameters of which specify the null hypothesis (including values and const/non-const status) </li>
</ul>
The interface allows one to pass the model, data, and parameters either directly or via a ModelConfig class.
The alternate hypothesis leaves the parameter free to take any value other than those specified by the null hypotesis. There is therefore no need to
specify the alternate parameters.
</p>
<p>
After configuring the calculator, one only needs to ask GetHypoTest() (which will return a HypoTestResult pointer) or GetInterval() (which will return an ConfInterval pointer).
</p>
<p>
The concrete implementations of this interface should deal with the details of how the nuisance parameters are
dealt with (eg. integration vs. profiling) and which test-statistic is used (perhaps this should be added to the interface).
</p>
<p>
The motivation for this interface is that we hope to be able to specify the problem in a common way for several concrete calculators.
</p>
END_HTML
*/
//
#ifndef RooStats_ProfileLikelihoodCalculator
#include "RooStats/ProfileLikelihoodCalculator.h"
#endif
#ifndef RooStats_RooStatsUtils
#include "RooStats/RooStatsUtils.h"
#endif
#include "RooStats/LikelihoodInterval.h"
#include "RooStats/HypoTestResult.h"
#include "RooFitResult.h"
#include "RooRealVar.h"
#include "RooProfileLL.h"
#include "RooNLLVar.h"
#include "RooGlobalFunc.h"
#include "RooMsgService.h"
#include "Math/MinimizerOptions.h"
//#include "RooProdPdf.h"
using namespace std;
ClassImp(RooStats::ProfileLikelihoodCalculator) ;
using namespace RooFit;
using namespace RooStats;
//_______________________________________________________
ProfileLikelihoodCalculator::ProfileLikelihoodCalculator() :
CombinedCalculator(), fFitResult(0)
{
// default constructor
}
ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, RooAbsPdf& pdf, const RooArgSet& paramsOfInterest,
Double_t size, const RooArgSet* nullParams ) :
CombinedCalculator(data,pdf, paramsOfInterest, size, nullParams ),
fFitResult(0)
{
// constructor from pdf and parameters
// the pdf must contain eventually the nuisance parameters
}
ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, ModelConfig& model, Double_t size) :
CombinedCalculator(data, model, size),
fFitResult(0)
{
// construct from a ModelConfig. Assume data model.GetPdf() will provide full description of model including
// constraint term on the nuisances parameters
assert(model.GetPdf() );
}
//_______________________________________________________
ProfileLikelihoodCalculator::~ProfileLikelihoodCalculator(){
// destructor
// cannot delete prod pdf because it will delete all the composing pdf's
// if (fOwnPdf) delete fPdf;
// fPdf = 0;
if (fFitResult) delete fFitResult;
}
void ProfileLikelihoodCalculator::DoReset() const {
// reset and clear fit result
// to be called when a new model or data are set in the calculator
if (fFitResult) delete fFitResult;
fFitResult = 0;
}
void ProfileLikelihoodCalculator::DoGlobalFit() const {
// perform a global fit of the likelihood letting with all parameter of interest and
// nuisance parameters
// keep the list of fitted parameters
DoReset();
RooAbsPdf * pdf = GetPdf();
RooAbsData* data = GetData();
if (!data || !pdf ) return;
// get all non-const parameters
RooArgSet* constrainedParams = pdf->getParameters(*data);
if (!constrainedParams) return ;
RemoveConstantParameters(constrainedParams);
// calculate MLE
const char * minimType = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
const char * minimAlgo = ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str();
int strategy = ROOT::Math::MinimizerOptions::DefaultStrategy();
int level = ROOT::Math::MinimizerOptions::DefaultPrintLevel() -1;// RooFit level starts from -1
oocoutP((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::DoGlobalFit - using " << minimType << " / " << minimAlgo << " with strategy " << strategy << std::endl;
// do global fit and store fit result for further use
fFitResult = pdf->fitTo(*data, Constrain(*constrainedParams),ConditionalObservables(fConditionalObs),
Strategy(strategy),PrintLevel(level),
Hesse(kFALSE),Save(kTRUE),Minimizer(minimType,minimAlgo));
// print fit result
if (fFitResult)
fFitResult->printStream( oocoutI((TObject*)0,Minimization), fFitResult->defaultPrintContents(0), fFitResult->defaultPrintStyle(0) );
if (fFitResult->status() != 0)
oocoutW((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::DoGlobalFit - Global fit failed - status = " << fFitResult->status() << std::endl;
delete constrainedParams;
}
//_______________________________________________________
LikelihoodInterval* ProfileLikelihoodCalculator::GetInterval() const {
// Main interface to get a RooStats::ConfInterval.
// It constructs a profile likelihood ratio and uses that to construct a RooStats::LikelihoodInterval.
// RooAbsPdf* pdf = fWS->pdf(fPdfName);
// RooAbsData* data = fWS->data(fDataName);
RooAbsPdf * pdf = GetPdf();
RooAbsData* data = GetData();
if (!data || !pdf || fPOI.getSize() == 0) return 0;
RooArgSet* constrainedParams = pdf->getParameters(*data);
RemoveConstantParameters(constrainedParams);
/*
RooNLLVar* nll = new RooNLLVar("nll","",*pdf,*data, Extended(),Constrain(*constrainedParams));
RooProfileLL* profile = new RooProfileLL("pll","",*nll, *fPOI);
profile->addOwnedComponents(*nll) ; // to avoid memory leak
*/
RooAbsReal * nll = pdf->createNLL(*data, CloneData(kTRUE), Constrain(*constrainedParams),ConditionalObservables(fConditionalObs));
RooAbsReal* profile = nll->createProfile(fPOI);
profile->addOwnedComponents(*nll) ; // to avoid memory leak
//RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ;
// perform a Best Fit
if (!fFitResult) DoGlobalFit();
// if fit fails return
if (!fFitResult) return 0;
// t.b.f. " RooProfileLL should keep and provide possibility to query on global minimum
// set POI to fit value (this will speed up profileLL calculation of global minimum)
const RooArgList & fitParams = fFitResult->floatParsFinal();
for (int i = 0; i < fitParams.getSize(); ++i) {
RooRealVar & fitPar = (RooRealVar &) fitParams[i];
RooRealVar * par = (RooRealVar*) fPOI.find( fitPar.GetName() );
if (par) {
par->setVal( fitPar.getVal() );
par->setError( fitPar.getError() );
}
}
// do this so profile will cache inside the absolute minimum and
// minimum values of nuisance parameters
// (no need to this here)
// profile->getVal();
//RooMsgService::instance().setGlobalKillBelow(RooFit::DEBUG) ;
// profile->Print();
TString name = TString("LikelihoodInterval_");// + TString(GetName() );
// make a list of fPOI with fit result values and pass to LikelihoodInterval class
// bestPOI is a cloned list of POI only with their best fit values
TIter iter = fPOI.createIterator();
RooArgSet fitParSet(fitParams);
RooArgSet * bestPOI = new RooArgSet();
while (RooAbsArg * arg = (RooAbsArg*) iter.Next() ) {
RooAbsArg * p = fitParSet.find( arg->GetName() );
if (p) bestPOI->addClone(*p);
else bestPOI->addClone(*arg);
}
// fPOI contains the paramter of interest of the PL object
// and bestPOI contains a snapshot with the best fit values
LikelihoodInterval* interval = new LikelihoodInterval(name, profile, &fPOI, bestPOI);
interval->SetConfidenceLevel(1.-fSize);
delete constrainedParams;
return interval;
}
//_______________________________________________________
HypoTestResult* ProfileLikelihoodCalculator::GetHypoTest() const {
// Main interface to get a HypoTestResult.
// It does two fits:
// the first lets the null parameters float, so it's a maximum likelihood estimate
// the second is to the null (fixing null parameters to their specified values): eg. a conditional maximum likelihood
// the ratio of the likelihood at the conditional MLE to the MLE is the profile likelihood ratio.
// Wilks' theorem is used to get p-values
// RooAbsPdf* pdf = fWS->pdf(fPdfName);
// RooAbsData* data = fWS->data(fDataName);
RooAbsPdf * pdf = GetPdf();
RooAbsData* data = GetData();
if (!data || !pdf) return 0;
if (fNullParams.getSize() == 0) return 0;
// make a clone and ordered list since a vector will be associated to keep parameter values
// clone the list since first fit will changes the fNullParams values
RooArgList poiList;
poiList.addClone(fNullParams); // make a clone list
// do a global fit
if (!fFitResult) DoGlobalFit();
if (!fFitResult) return 0;
RooArgSet* constrainedParams = pdf->getParameters(*data);
RemoveConstantParameters(constrainedParams);
// perform a global fit if it is not done before
if (!fFitResult) DoGlobalFit();
Double_t NLLatMLE= fFitResult->minNll();
// set POI to given values, set constant, calculate conditional MLE
std::vector<double> oldValues(poiList.getSize() );
for (unsigned int i = 0; i < oldValues.size(); ++i) {
RooRealVar * mytarget = (RooRealVar*) constrainedParams->find(poiList[i].GetName());
if (mytarget) {
oldValues[i] = mytarget->getVal();
mytarget->setVal( ( (RooRealVar&) poiList[i] ).getVal() );
mytarget->setConstant(kTRUE);
}
}
// perform the fit only if nuisance parameters are available
// get nuisance parameters
// nuisance parameters are the non const parameters from the likelihood parameters
RooArgSet nuisParams(*constrainedParams);
// need to remove the parameter of interest
RemoveConstantParameters(&nuisParams);
// check there are variable parameter in order to do a fit
bool existVarParams = false;
TIter it = nuisParams.createIterator();
RooRealVar * myarg = 0;
while ((myarg = (RooRealVar *)it.Next())) {
if ( !myarg->isConstant() ) {
existVarParams = true;
break;
}
}
Double_t NLLatCondMLE = NLLatMLE;
if (existVarParams) {
const char * minimType = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
const char * minimAlgo = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
int level = ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1; // RooFit levels starts from -1
oocoutP((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::GetHypoTest - do conditional fit " << std::endl;
RooFitResult* fit2 = pdf->fitTo(*data,Constrain(*constrainedParams),ConditionalObservables(fConditionalObs),
Hesse(kFALSE),Strategy(0), Minos(kFALSE),
Minimizer(minimType,minimAlgo), Save(kTRUE),PrintLevel(level));
// print fit result
if (fit2) {
NLLatCondMLE = fit2->minNll();
fit2->printStream( oocoutI((TObject*)0,Minimization), fit2->defaultPrintContents(0), fit2->defaultPrintStyle(0) );
if (fit2->status() != 0)
oocoutW((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::GetHypotest - Conditional fit failed - status = " << fit2->status() << std::endl;
}
}
else {
// get just the likelihood value (no need to do a fit since the likelihood is a constant function)
RooAbsReal* nll = pdf->createNLL(*data, CloneData(kTRUE), Constrain(*constrainedParams),ConditionalObservables(fConditionalObs));
NLLatCondMLE = nll->getVal();
delete nll;
}
// Use Wilks' theorem to translate -2 log lambda into a signifcance/p-value
Double_t deltaNLL = std::max( NLLatCondMLE-NLLatMLE, 0.);
// get number of free parameter of interest
RemoveConstantParameters(poiList);
int ndf = poiList.getSize();
Double_t pvalue = ROOT::Math::chisquared_cdf_c( 2* deltaNLL, ndf);
TString name = TString("ProfileLRHypoTestResult_");// + TString(GetName() );
HypoTestResult* htr = new HypoTestResult(name, pvalue, 0 );
// restore previous value of poi
for (unsigned int i = 0; i < oldValues.size(); ++i) {
RooRealVar * mytarget = (RooRealVar*) constrainedParams->find(poiList[i].GetName());
if (mytarget) {
mytarget->setVal(oldValues[i] );
mytarget->setConstant(false);
}
}
delete constrainedParams;
return htr;
}
<commit_msg>Re-revert r46690<commit_after>// @(#)root/roostats:$Id$
// Author: Kyle Cranmer 28/07/2008
/*************************************************************************
* Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//_________________________________________________
/*
BEGIN_HTML
<p>
ProfileLikelihoodCalculator is a concrete implementation of CombinedCalculator
(the interface class for a tools which can produce both RooStats HypoTestResults and ConfIntervals).
The tool uses the profile likelihood ratio as a test statistic, and assumes that Wilks' theorem is valid.
Wilks' theorem states that -2* log (profile likelihood ratio) is asymptotically distributed as a chi^2 distribution
with N-dof, where N is the number of degrees of freedom. Thus, p-values can be constructed and the profile likelihood ratio
can be used to construct a LikelihoodInterval.
(In the future, this class could be extended to use toy Monte Carlo to calibrate the distribution of the test statistic).
</p>
<p> Usage: It uses the interface of the CombinedCalculator, so that it can be configured by specifying:
<ul>
<li>a model common model (eg. a family of specific models which includes both the null and alternate),</li>
<li>a data set, </li>
<li>a set of parameters of interest. The nuisance parameters will be all other parameters of the model </li>
<li>a set of parameters of which specify the null hypothesis (including values and const/non-const status) </li>
</ul>
The interface allows one to pass the model, data, and parameters either directly or via a ModelConfig class.
The alternate hypothesis leaves the parameter free to take any value other than those specified by the null hypotesis. There is therefore no need to
specify the alternate parameters.
</p>
<p>
After configuring the calculator, one only needs to ask GetHypoTest() (which will return a HypoTestResult pointer) or GetInterval() (which will return an ConfInterval pointer).
</p>
<p>
The concrete implementations of this interface should deal with the details of how the nuisance parameters are
dealt with (eg. integration vs. profiling) and which test-statistic is used (perhaps this should be added to the interface).
</p>
<p>
The motivation for this interface is that we hope to be able to specify the problem in a common way for several concrete calculators.
</p>
END_HTML
*/
//
#ifndef RooStats_ProfileLikelihoodCalculator
#include "RooStats/ProfileLikelihoodCalculator.h"
#endif
#ifndef RooStats_RooStatsUtils
#include "RooStats/RooStatsUtils.h"
#endif
#include "RooStats/LikelihoodInterval.h"
#include "RooStats/HypoTestResult.h"
#include "RooFitResult.h"
#include "RooRealVar.h"
#include "RooProfileLL.h"
#include "RooNLLVar.h"
#include "RooGlobalFunc.h"
#include "RooMsgService.h"
#include "Math/MinimizerOptions.h"
//#include "RooProdPdf.h"
using namespace std;
ClassImp(RooStats::ProfileLikelihoodCalculator) ;
using namespace RooFit;
using namespace RooStats;
//_______________________________________________________
ProfileLikelihoodCalculator::ProfileLikelihoodCalculator() :
CombinedCalculator(), fFitResult(0)
{
// default constructor
}
ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, RooAbsPdf& pdf, const RooArgSet& paramsOfInterest,
Double_t size, const RooArgSet* nullParams ) :
CombinedCalculator(data,pdf, paramsOfInterest, size, nullParams ),
fFitResult(0)
{
// constructor from pdf and parameters
// the pdf must contain eventually the nuisance parameters
}
ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, ModelConfig& model, Double_t size) :
CombinedCalculator(data, model, size),
fFitResult(0)
{
// construct from a ModelConfig. Assume data model.GetPdf() will provide full description of model including
// constraint term on the nuisances parameters
assert(model.GetPdf() );
}
//_______________________________________________________
ProfileLikelihoodCalculator::~ProfileLikelihoodCalculator(){
// destructor
// cannot delete prod pdf because it will delete all the composing pdf's
// if (fOwnPdf) delete fPdf;
// fPdf = 0;
if (fFitResult) delete fFitResult;
}
void ProfileLikelihoodCalculator::DoReset() const {
// reset and clear fit result
// to be called when a new model or data are set in the calculator
if (fFitResult) delete fFitResult;
fFitResult = 0;
}
void ProfileLikelihoodCalculator::DoGlobalFit() const {
// perform a global fit of the likelihood letting with all parameter of interest and
// nuisance parameters
// keep the list of fitted parameters
DoReset();
RooAbsPdf * pdf = GetPdf();
RooAbsData* data = GetData();
if (!data || !pdf ) return;
// get all non-const parameters
RooArgSet* constrainedParams = pdf->getParameters(*data);
if (!constrainedParams) return ;
RemoveConstantParameters(constrainedParams);
// calculate MLE
const char * minimType = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
const char * minimAlgo = ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str();
int strategy = ROOT::Math::MinimizerOptions::DefaultStrategy();
int level = ROOT::Math::MinimizerOptions::DefaultPrintLevel() -1;// RooFit level starts from -1
oocoutP((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::DoGlobalFit - using " << minimType << " / " << minimAlgo << " with strategy " << strategy << std::endl;
// do global fit and store fit result for further use
fFitResult = pdf->fitTo(*data, Constrain(*constrainedParams),ConditionalObservables(fConditionalObs),
Strategy(strategy),PrintLevel(level),
Hesse(kFALSE),Save(kTRUE),Minimizer(minimType,minimAlgo));
// print fit result
if (fFitResult)
fFitResult->printStream( oocoutI((TObject*)0,Minimization), fFitResult->defaultPrintContents(0), fFitResult->defaultPrintStyle(0) );
if (fFitResult->status() != 0)
oocoutW((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::DoGlobalFit - Global fit failed - status = " << fFitResult->status() << std::endl;
delete constrainedParams;
}
//_______________________________________________________
LikelihoodInterval* ProfileLikelihoodCalculator::GetInterval() const {
// Main interface to get a RooStats::ConfInterval.
// It constructs a profile likelihood ratio and uses that to construct a RooStats::LikelihoodInterval.
// RooAbsPdf* pdf = fWS->pdf(fPdfName);
// RooAbsData* data = fWS->data(fDataName);
RooAbsPdf * pdf = GetPdf();
RooAbsData* data = GetData();
if (!data || !pdf || fPOI.getSize() == 0) return 0;
RooArgSet* constrainedParams = pdf->getParameters(*data);
RemoveConstantParameters(constrainedParams);
/*
RooNLLVar* nll = new RooNLLVar("nll","",*pdf,*data, Extended(),Constrain(*constrainedParams));
RooProfileLL* profile = new RooProfileLL("pll","",*nll, *fPOI);
profile->addOwnedComponents(*nll) ; // to avoid memory leak
*/
RooAbsReal * nll = pdf->createNLL(*data, CloneData(kTRUE), Constrain(*constrainedParams),ConditionalObservables(fConditionalObs));
RooAbsReal* profile = nll->createProfile(fPOI);
profile->addOwnedComponents(*nll) ; // to avoid memory leak
//RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ;
// perform a Best Fit
if (!fFitResult) DoGlobalFit();
// if fit fails return
if (!fFitResult) return 0;
// t.b.f. " RooProfileLL should keep and provide possibility to query on global minimum
// set POI to fit value (this will speed up profileLL calculation of global minimum)
const RooArgList & fitParams = fFitResult->floatParsFinal();
for (int i = 0; i < fitParams.getSize(); ++i) {
RooRealVar & fitPar = (RooRealVar &) fitParams[i];
RooRealVar * par = (RooRealVar*) fPOI.find( fitPar.GetName() );
if (par) {
par->setVal( fitPar.getVal() );
par->setError( fitPar.getError() );
}
}
// do this so profile will cache inside the absolute minimum and
// minimum values of nuisance parameters
// (no need to this here)
// profile->getVal();
//RooMsgService::instance().setGlobalKillBelow(RooFit::DEBUG) ;
// profile->Print();
TString name = TString("LikelihoodInterval_");// + TString(GetName() );
// make a list of fPOI with fit result values and pass to LikelihoodInterval class
// bestPOI is a cloned list of POI only with their best fit values
TIter iter = fPOI.createIterator();
RooArgSet fitParSet(fitParams);
RooArgSet * bestPOI = new RooArgSet();
while (RooAbsArg * arg = (RooAbsArg*) iter.Next() ) {
RooAbsArg * p = fitParSet.find( arg->GetName() );
if (p) bestPOI->addClone(*p);
else bestPOI->addClone(*arg);
}
// fPOI contains the paramter of interest of the PL object
// and bestPOI contains a snapshot with the best fit values
LikelihoodInterval* interval = new LikelihoodInterval(name, profile, &fPOI, bestPOI);
interval->SetConfidenceLevel(1.-fSize);
delete constrainedParams;
return interval;
}
//_______________________________________________________
HypoTestResult* ProfileLikelihoodCalculator::GetHypoTest() const {
// Main interface to get a HypoTestResult.
// It does two fits:
// the first lets the null parameters float, so it's a maximum likelihood estimate
// the second is to the null (fixing null parameters to their specified values): eg. a conditional maximum likelihood
// the ratio of the likelihood at the conditional MLE to the MLE is the profile likelihood ratio.
// Wilks' theorem is used to get p-values
// RooAbsPdf* pdf = fWS->pdf(fPdfName);
// RooAbsData* data = fWS->data(fDataName);
RooAbsPdf * pdf = GetPdf();
RooAbsData* data = GetData();
if (!data || !pdf) return 0;
if (fNullParams.getSize() == 0) return 0;
// make a clone and ordered list since a vector will be associated to keep parameter values
// clone the list since first fit will changes the fNullParams values
RooArgList poiList;
poiList.addClone(fNullParams); // make a clone list
// do a global fit
if (!fFitResult) DoGlobalFit();
if (!fFitResult) return 0;
RooArgSet* constrainedParams = pdf->getParameters(*data);
RemoveConstantParameters(constrainedParams);
// perform a global fit if it is not done before
if (!fFitResult) DoGlobalFit();
Double_t NLLatMLE= fFitResult->minNll();
// set POI to given values, set constant, calculate conditional MLE
std::vector<double> oldValues(poiList.getSize() );
for (unsigned int i = 0; i < oldValues.size(); ++i) {
RooRealVar * mytarget = (RooRealVar*) constrainedParams->find(poiList[i].GetName());
if (mytarget) {
oldValues[i] = mytarget->getVal();
mytarget->setVal( ( (RooRealVar&) poiList[i] ).getVal() );
mytarget->setConstant(kTRUE);
}
}
// perform the fit only if nuisance parameters are available
// get nuisance parameters
// nuisance parameters are the non const parameters from the likelihood parameters
RooArgSet nuisParams(*constrainedParams);
// need to remove the parameter of interest
RemoveConstantParameters(&nuisParams);
// check there are variable parameter in order to do a fit
bool existVarParams = false;
TIter it = nuisParams.createIterator();
RooRealVar * myarg = 0;
while ((myarg = (RooRealVar *)it.Next())) {
if ( !myarg->isConstant() ) {
existVarParams = true;
break;
}
}
Double_t NLLatCondMLE = NLLatMLE;
if (existVarParams) {
const char * minimType = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
const char * minimAlgo = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
int level = ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1; // RooFit levels starts from -1
oocoutP((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::GetHypoTest - do conditional fit " << std::endl;
RooFitResult* fit2 = pdf->fitTo(*data,Constrain(*constrainedParams),ConditionalObservables(fConditionalObs),
Hesse(kFALSE),Strategy(0), Minos(kFALSE),
Minimizer(minimType,minimAlgo), Save(kTRUE),PrintLevel(level));
// print fit result
if (fit2) {
NLLatCondMLE = fit2->minNll();
fit2->printStream( oocoutI((TObject*)0,Minimization), fit2->defaultPrintContents(0), fit2->defaultPrintStyle(0) );
if (fit2->status() != 0)
oocoutW((TObject*)0,Minimization) << "ProfileLikelihoodCalcultor::GetHypotest - Conditional fit failed - status = " << fit2->status() << std::endl;
}
}
else {
// get just the likelihood value (no need to do a fit since the likelihood is a constant function)
RooAbsReal* nll = pdf->createNLL(*data, CloneData(kTRUE), Constrain(*constrainedParams),ConditionalObservables(fConditionalObs));
NLLatCondMLE = nll->getVal();
delete nll;
}
// Use Wilks' theorem to translate -2 log lambda into a signifcance/p-value
Double_t deltaNLL = std::max( NLLatCondMLE-NLLatMLE, 0.);
// get number of free parameter of interest
RemoveConstantParameters(poiList);
int ndf = poiList.getSize();
Double_t pvalue = ROOT::Math::chisquared_cdf_c( 2* deltaNLL, ndf);
// in case of one dimenension (1 poi) do the one-sided p-value (need to divide by 2)
if (ndf == 1) pvalue = 0.5 * pvalue;
TString name = TString("ProfileLRHypoTestResult_");// + TString(GetName() );
HypoTestResult* htr = new HypoTestResult(name, pvalue, 0 );
// restore previous value of poi
for (unsigned int i = 0; i < oldValues.size(); ++i) {
RooRealVar * mytarget = (RooRealVar*) constrainedParams->find(poiList[i].GetName());
if (mytarget) {
mytarget->setVal(oldValues[i] );
mytarget->setConstant(false);
}
}
delete constrainedParams;
return htr;
}
<|endoftext|> |
<commit_before>#include "LolaAdaptor.h"
using namespace naoth;
LolaAdaptor::LolaAdaptor()
{
// open semaphore to synchronize with NaoController
if((sem = sem_open("motion_trigger", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED)
{
perror("[LolaAdaptor] sem_open");
::exit(-1);
}
openSharedMemory(naoSensorData, "/nao_sensor_data");
openSharedMemory(naoCommandMotorJointData, "/nao_command.MotorJointData");
openSharedMemory(naoCommandUltraSoundSendData, "/nao_command.UltraSoundSendData");
openSharedMemory(naoCommandLEDData, "/nao_command.LEDData");
}
LolaAdaptor::~LolaAdaptor()
{
// stop the thread before anything else
stop();
// close semaphore
if(sem != SEM_FAILED)
{
sem_close(sem);
sem = SEM_FAILED;
}
}
template<typename T>
void LolaAdaptor::openSharedMemory(SharedMemory<T> &sm, const std::string &path)
{
std::cout<< "[LolaAdaptor] Opening Shared Memory: "<<path<<std::endl;
sm.open(path);
}
void LolaAdaptor::writeNaoInfo(const std::string& theBodyID, const std::string& /*theHeadID*/) const
{
// save the body ID
std::cout << "[LolaAdaptor] bodyID: " << theBodyID << std::endl;
// save the nick name
std::string theBodyNickName = "error";
if(theBodyID.length() >= 4) {
theBodyNickName = "Nao" + theBodyID.substr( theBodyID.length() - 4 ); //theDCMHandler.getBodyNickName();
}
std::cout << "[LolaAdaptor] nickName: "<< theBodyNickName << std::endl;
// save the value to file
// FIXME: fixed path "Config/nao.info"
{
std::string staticMemberPath("Config/nao.info");
std::ofstream os(staticMemberPath.c_str());
ASSERT(os.good());
os << theBodyID << "\n" << theBodyNickName << std::endl;
os.close();
}
}//end writeNaoInfo()
void LolaAdaptor::start()
{
exiting = false;
lolaThread = std::thread(&LolaAdaptor::run, this);
//ThreadUtil::setPriority(lolaThread, ThreadUtil::Priority::highest);
ThreadUtil::setName(lolaThread, "LOLA");
// NOTE: SCHED_FIFO is a real time sheduler
// max priority for a FIFO thread is 99
sched_param param;
param.sched_priority = 50;
if(pthread_setschedparam(lolaThread.native_handle(), SCHED_FIFO, ¶m)) {
std::cerr << "[LolaAdaptor] error setting thread priority" << std::endl;
assert(false);
}
// int tryCount = 0;
while(waitingForLola && ! exiting)
{
fprintf(stderr, "[LolaAdaptor] Waiting for LoLA socket.\n");
std::this_thread::sleep_for(std::chrono::milliseconds(125));
// if(tryCount > 40 )
// {
// fprintf(stderr, "[LolaAdaptor] Waiting for LoLA socket failed after %d ms.\n", tryCount * 125);
// waitingForLola = false;
// assert(false);
// }
// tryCount++;
}
fprintf(stderr, "[LolaAdaptor] LoLA socket connection established.\n");
//HACK: pulseaudio is not initialized correctly, but after playing a sound as no it works?!?
}//end start()
void LolaAdaptor::stop()
{
std::cout << "[LolaAdaptor] stop wait" << std::endl;
// request the thread to stop
exiting = true;
if(lolaThread.joinable()) {
lolaThread.join();
}
std::cout << "[LolaAdaptor] stop done" << std::endl;
}
bool LolaAdaptor::isRunning() const
{
return running;
}
void LolaAdaptor::run()
{
waitForLolaSocket();
Lola lola;
lola.connectSocket();
if(lola.hasError())
{
fprintf(stderr, "[LolaAdaptor] Error while attemting to connect to LoLa socket.\n");
assert(false);
}
waitingForLola = false;
running = true;
SensorData sensors;
ActuatorData actuators;
bool firstRun = true;
while(!exiting)
{
lola.readSensors(sensors);
if(firstRun) {
writeNaoInfo(sensors.RobotConfig.Body.BodyId, sensors.RobotConfig.Head.FullHeadId);
firstRun = false;
}
// like old DCM motionCallbackPre
if(!runEmergencyMotion(actuators))
{
setMotorJoints(actuators);
}
lola.writeActuators(actuators);
// like old DCM motionCallbackPost
DCMSensorData* sensorData = naoSensorData.writing();
// current system time (System time, not nao time (!))
sensorData->timeStamp = NaoTime::getSystemTimeInMilliSeconds();
// copy sensor data to shared memory
LolaDataConverter::readSensorData(sensors, *sensorData);
// check if chest button was pressed as a request to shutdown
// each cycle needs 12ms so if the button was pressed for 3 seconds
// these are 250 frames
sensorData->get(theButtonData);
if(!shutdown_requested && theButtonData.numOfFramesPressed[ButtonData::Chest] > 250)
{
shutdown_requested = true;
//exit(-1);
// break;
shutdownCallbackThread = std::thread(&LolaAdaptor::shutdownCallback, this);
}
// save the data for the emergency case
if(state == DISCONNECTED) {
std::cout << "get inertial sensor data" << std::endl;
sensorData->get(theInertialSensorData);
sensor_data_available = true;
} else {
sensor_data_available = false;
}
// push the data to shared memory
naoSensorData.swapWriting();
// notify cognition
notify();
}
running = false;
}//end run()
void LolaAdaptor::waitForLolaSocket()
{
int tryCount = 0;
// end the thread if the lola (unix) socket doesn't exists (after 5s)!
while(!fileExists("/tmp/robocup"))
{
std::this_thread::sleep_for(std::chrono::milliseconds(250));
if(tryCount > 20 )
{
fprintf(stderr, "[LolaAdaptor] Waiting for LoLa %d ms.\n", tryCount * 250);
assert(false);
}
tryCount++;
}
std::this_thread::sleep_for(std::chrono::milliseconds(900));
}//end waitForLolaSocket()
bool LolaAdaptor::fileExists(const std::string& filename)
{
struct stat buffer;
return (stat (filename.c_str(), &buffer) == 0);
}
void LolaAdaptor::setMotorJoints(ActuatorData &actuators)
{
// get the MotorJointData from the shared memory and put them to the DCM
if ( naoCommandMotorJointData.swapReading() )
{
const Accessor<MotorJointData>* motorData = naoCommandMotorJointData.reading();
// write MotorJointData to LolaActuatorData
LolaDataConverter::set(actuators, motorData->get());
// TODO: why do we need this? It is never resetted ...
//drop_count = 0;
command_data_available = true;
}
if(naoCommandLEDData.swapReading())
{
const Accessor<LEDData>* commandData = naoCommandLEDData.reading();
LolaDataConverter::set(actuators, commandData->get());
}
}//end setMotorJoints()
void LolaAdaptor::setWarningLED(ActuatorData& actuators, bool red)
{
static naoth::LEDData theLEDData;
static int count = 0;
int begin = ((++count)/10)%10;
theLEDData.theMonoLED[LEDData::EarRight0 + begin] = 0;
theLEDData.theMonoLED[LEDData::EarLeft0 + begin] = 0;
int end = (begin+2)%10;
theLEDData.theMonoLED[LEDData::EarRight0 + end] = 1;
theLEDData.theMonoLED[LEDData::EarLeft0 + end] = 1;
for(int i=0; i<LEDData::numOfMultiLED; i++)
{
theLEDData.theMultiLED[i][LEDData::RED] = red ? 1 : 0;
theLEDData.theMultiLED[i][LEDData::GREEN] = 0;
theLEDData.theMultiLED[i][LEDData::BLUE] = red ? 0 : 1;
}
LolaDataConverter::set(actuators, theLEDData);
}//end setWarningLED
bool LolaAdaptor::runEmergencyMotion(ActuatorData& actuators)
{
if(state == DISCONNECTED)
{
if(initialMotion == NULL && command_data_available && sensor_data_available)
{
std::cout << "emerg: start init motion" << std::endl;
// take the last command data
const Accessor<MotorJointData>* commandData = naoCommandMotorJointData.reading();
initialMotion = new BasicMotion(theMotorJointData, commandData->get(), theInertialSensorData);
}
setWarningLED(actuators, state == DISCONNECTED);
}//end if
// after reconnect: wait until the init motion is finished
if(initialMotion != NULL)
{
if(state == CONNECTED && initialMotion->isFinish())
{
std::cout << "emerg: stop init motion" << std::endl;
delete initialMotion;
initialMotion = NULL;
}
else
{
// execute the emergency motion
// (the resulting joint commands are written to theMotorJointData)
initialMotion->execute();
// write MotorJointData to LolaActuatorData
LolaDataConverter::set(actuators, theMotorJointData);
}
}//end if
return initialMotion != NULL;
}//end runEmergencyMotion
void LolaAdaptor::notify()
{
static int drop_count = 10;
// raise the semaphore: triggers core
if(sem != SEM_FAILED)
{
int sval;
if(sem_getvalue(sem, &sval) == 0)
{
if(sval < 1)
{
sem_post(sem);
// until now we were disconnected, but now we're alive and connected ...
if(state == DISCONNECTED) {
fprintf(stderr, "[LolaAdaptor] I think the core is alive.\n");
}
drop_count = 0;
state = CONNECTED;
}
else
{
if(drop_count == 0) {
fprintf(stderr, "[LolaAdaptor] dropped sensor data.\n");
} else if(drop_count == 10) {
fprintf(stderr, "[LolaAdaptor] I think the core is dead.\n");
state = DISCONNECTED;
}
// don't count more than 11
drop_count += (drop_count < 11);
}//end if
}
else
{
fprintf(stderr, "[LolaAdaptor] I couldn't get value by sem_getvalue.\n");
}
}//end if SEM_FAILED
}//end notify()
void LolaAdaptor::shutdownCallback()
{
// play a sound that the user knows we recognized his shutdown request
system("paplay /opt/aldebaran/share/naoqi/wav/bip_power_off.wav");
// stop the user program
std::cout << "[LolaAdaptor] stopping naoth" << std::endl;
// stop naoth to trigger emergency motion
system("killall naoth");
// in NaoSMAL it's like this
//system("naoth stop");
sleep(5);
// we are the child process, do a blocking call to shutdown
std::cout << "[LolaAdaptor] System shutdown requested" << std::endl;
system("/sbin/shutdown -h now");
// await termination
while(true) {
sleep(100);
}
}//end shutdownCallback
<commit_msg>fix: use full path for writing in nao info. This helps for running it locally. We can use full path here because we will only run it on the nao anyways<commit_after>#include "LolaAdaptor.h"
using namespace naoth;
LolaAdaptor::LolaAdaptor()
{
// open semaphore to synchronize with NaoController
if((sem = sem_open("motion_trigger", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED)
{
perror("[LolaAdaptor] sem_open");
::exit(-1);
}
openSharedMemory(naoSensorData, "/nao_sensor_data");
openSharedMemory(naoCommandMotorJointData, "/nao_command.MotorJointData");
openSharedMemory(naoCommandUltraSoundSendData, "/nao_command.UltraSoundSendData");
openSharedMemory(naoCommandLEDData, "/nao_command.LEDData");
}
LolaAdaptor::~LolaAdaptor()
{
// stop the thread before anything else
stop();
// close semaphore
if(sem != SEM_FAILED)
{
sem_close(sem);
sem = SEM_FAILED;
}
}
template<typename T>
void LolaAdaptor::openSharedMemory(SharedMemory<T> &sm, const std::string &path)
{
std::cout<< "[LolaAdaptor] Opening Shared Memory: "<<path<<std::endl;
sm.open(path);
}
void LolaAdaptor::writeNaoInfo(const std::string& theBodyID, const std::string& /*theHeadID*/) const
{
// save the body ID
std::cout << "[LolaAdaptor] bodyID: " << theBodyID << std::endl;
// save the nick name
std::string theBodyNickName = "error";
if(theBodyID.length() >= 4) {
theBodyNickName = "Nao" + theBodyID.substr( theBodyID.length() - 4 ); //theDCMHandler.getBodyNickName();
}
std::cout << "[LolaAdaptor] nickName: "<< theBodyNickName << std::endl;
// save the value to file
// FIXME: fixed path "Config/nao.info"
{
std::string staticMemberPath("/home/nao/Config/nao.info");
std::ofstream os(staticMemberPath.c_str());
ASSERT(os.good());
os << theBodyID << "\n" << theBodyNickName << std::endl;
os.close();
}
}//end writeNaoInfo()
void LolaAdaptor::start()
{
exiting = false;
lolaThread = std::thread(&LolaAdaptor::run, this);
//ThreadUtil::setPriority(lolaThread, ThreadUtil::Priority::highest);
ThreadUtil::setName(lolaThread, "LOLA");
// NOTE: SCHED_FIFO is a real time sheduler
// max priority for a FIFO thread is 99
sched_param param;
param.sched_priority = 50;
if(pthread_setschedparam(lolaThread.native_handle(), SCHED_FIFO, ¶m)) {
std::cerr << "[LolaAdaptor] error setting thread priority" << std::endl;
assert(false);
}
// int tryCount = 0;
while(waitingForLola && ! exiting)
{
fprintf(stderr, "[LolaAdaptor] Waiting for LoLA socket.\n");
std::this_thread::sleep_for(std::chrono::milliseconds(125));
// if(tryCount > 40 )
// {
// fprintf(stderr, "[LolaAdaptor] Waiting for LoLA socket failed after %d ms.\n", tryCount * 125);
// waitingForLola = false;
// assert(false);
// }
// tryCount++;
}
fprintf(stderr, "[LolaAdaptor] LoLA socket connection established.\n");
//HACK: pulseaudio is not initialized correctly, but after playing a sound as no it works?!?
}//end start()
void LolaAdaptor::stop()
{
std::cout << "[LolaAdaptor] stop wait" << std::endl;
// request the thread to stop
exiting = true;
if(lolaThread.joinable()) {
lolaThread.join();
}
std::cout << "[LolaAdaptor] stop done" << std::endl;
}
bool LolaAdaptor::isRunning() const
{
return running;
}
void LolaAdaptor::run()
{
waitForLolaSocket();
Lola lola;
lola.connectSocket();
if(lola.hasError())
{
fprintf(stderr, "[LolaAdaptor] Error while attemting to connect to LoLa socket.\n");
assert(false);
}
waitingForLola = false;
running = true;
SensorData sensors;
ActuatorData actuators;
bool firstRun = true;
while(!exiting)
{
lola.readSensors(sensors);
if(firstRun) {
writeNaoInfo(sensors.RobotConfig.Body.BodyId, sensors.RobotConfig.Head.FullHeadId);
firstRun = false;
}
// like old DCM motionCallbackPre
if(!runEmergencyMotion(actuators))
{
setMotorJoints(actuators);
}
lola.writeActuators(actuators);
// like old DCM motionCallbackPost
DCMSensorData* sensorData = naoSensorData.writing();
// current system time (System time, not nao time (!))
sensorData->timeStamp = NaoTime::getSystemTimeInMilliSeconds();
// copy sensor data to shared memory
LolaDataConverter::readSensorData(sensors, *sensorData);
// check if chest button was pressed as a request to shutdown
// each cycle needs 12ms so if the button was pressed for 3 seconds
// these are 250 frames
sensorData->get(theButtonData);
if(!shutdown_requested && theButtonData.numOfFramesPressed[ButtonData::Chest] > 250)
{
shutdown_requested = true;
//exit(-1);
// break;
shutdownCallbackThread = std::thread(&LolaAdaptor::shutdownCallback, this);
}
// save the data for the emergency case
if(state == DISCONNECTED) {
std::cout << "get inertial sensor data" << std::endl;
sensorData->get(theInertialSensorData);
sensor_data_available = true;
} else {
sensor_data_available = false;
}
// push the data to shared memory
naoSensorData.swapWriting();
// notify cognition
notify();
}
running = false;
}//end run()
void LolaAdaptor::waitForLolaSocket()
{
int tryCount = 0;
// end the thread if the lola (unix) socket doesn't exists (after 5s)!
while(!fileExists("/tmp/robocup"))
{
std::this_thread::sleep_for(std::chrono::milliseconds(250));
if(tryCount > 20 )
{
fprintf(stderr, "[LolaAdaptor] Waiting for LoLa %d ms.\n", tryCount * 250);
assert(false);
}
tryCount++;
}
std::this_thread::sleep_for(std::chrono::milliseconds(900));
}//end waitForLolaSocket()
bool LolaAdaptor::fileExists(const std::string& filename)
{
struct stat buffer;
return (stat (filename.c_str(), &buffer) == 0);
}
void LolaAdaptor::setMotorJoints(ActuatorData &actuators)
{
// get the MotorJointData from the shared memory and put them to the DCM
if ( naoCommandMotorJointData.swapReading() )
{
const Accessor<MotorJointData>* motorData = naoCommandMotorJointData.reading();
// write MotorJointData to LolaActuatorData
LolaDataConverter::set(actuators, motorData->get());
// TODO: why do we need this? It is never resetted ...
//drop_count = 0;
command_data_available = true;
}
if(naoCommandLEDData.swapReading())
{
const Accessor<LEDData>* commandData = naoCommandLEDData.reading();
LolaDataConverter::set(actuators, commandData->get());
}
}//end setMotorJoints()
void LolaAdaptor::setWarningLED(ActuatorData& actuators, bool red)
{
static naoth::LEDData theLEDData;
static int count = 0;
int begin = ((++count)/10)%10;
theLEDData.theMonoLED[LEDData::EarRight0 + begin] = 0;
theLEDData.theMonoLED[LEDData::EarLeft0 + begin] = 0;
int end = (begin+2)%10;
theLEDData.theMonoLED[LEDData::EarRight0 + end] = 1;
theLEDData.theMonoLED[LEDData::EarLeft0 + end] = 1;
for(int i=0; i<LEDData::numOfMultiLED; i++)
{
theLEDData.theMultiLED[i][LEDData::RED] = red ? 1 : 0;
theLEDData.theMultiLED[i][LEDData::GREEN] = 0;
theLEDData.theMultiLED[i][LEDData::BLUE] = red ? 0 : 1;
}
LolaDataConverter::set(actuators, theLEDData);
}//end setWarningLED
bool LolaAdaptor::runEmergencyMotion(ActuatorData& actuators)
{
if(state == DISCONNECTED)
{
if(initialMotion == NULL && command_data_available && sensor_data_available)
{
std::cout << "emerg: start init motion" << std::endl;
// take the last command data
const Accessor<MotorJointData>* commandData = naoCommandMotorJointData.reading();
initialMotion = new BasicMotion(theMotorJointData, commandData->get(), theInertialSensorData);
}
setWarningLED(actuators, state == DISCONNECTED);
}//end if
// after reconnect: wait until the init motion is finished
if(initialMotion != NULL)
{
if(state == CONNECTED && initialMotion->isFinish())
{
std::cout << "emerg: stop init motion" << std::endl;
delete initialMotion;
initialMotion = NULL;
}
else
{
// execute the emergency motion
// (the resulting joint commands are written to theMotorJointData)
initialMotion->execute();
// write MotorJointData to LolaActuatorData
LolaDataConverter::set(actuators, theMotorJointData);
}
}//end if
return initialMotion != NULL;
}//end runEmergencyMotion
void LolaAdaptor::notify()
{
static int drop_count = 10;
// raise the semaphore: triggers core
if(sem != SEM_FAILED)
{
int sval;
if(sem_getvalue(sem, &sval) == 0)
{
if(sval < 1)
{
sem_post(sem);
// until now we were disconnected, but now we're alive and connected ...
if(state == DISCONNECTED) {
fprintf(stderr, "[LolaAdaptor] I think the core is alive.\n");
}
drop_count = 0;
state = CONNECTED;
}
else
{
if(drop_count == 0) {
fprintf(stderr, "[LolaAdaptor] dropped sensor data.\n");
} else if(drop_count == 10) {
fprintf(stderr, "[LolaAdaptor] I think the core is dead.\n");
state = DISCONNECTED;
}
// don't count more than 11
drop_count += (drop_count < 11);
}//end if
}
else
{
fprintf(stderr, "[LolaAdaptor] I couldn't get value by sem_getvalue.\n");
}
}//end if SEM_FAILED
}//end notify()
void LolaAdaptor::shutdownCallback()
{
// play a sound that the user knows we recognized his shutdown request
system("paplay /opt/aldebaran/share/naoqi/wav/bip_power_off.wav");
// stop the user program
std::cout << "[LolaAdaptor] stopping naoth" << std::endl;
// stop naoth to trigger emergency motion
system("killall naoth");
// in NaoSMAL it's like this
//system("naoth stop");
sleep(5);
// we are the child process, do a blocking call to shutdown
std::cout << "[LolaAdaptor] System shutdown requested" << std::endl;
system("/sbin/shutdown -h now");
// await termination
while(true) {
sleep(100);
}
}//end shutdownCallback
<|endoftext|> |
<commit_before>/*****************************************************************************
* recents.cpp : Recents MRL (menu)
*****************************************************************************
* Copyright © 2008-2014 VideoLAN and VLC authors
* $Id$
*
* Authors: Ludovic Fauvet <[email protected]>
* Jean-baptiste Kempf <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* ( at your option ) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "qt4.hpp"
#include "recents.hpp"
#include "dialogs_provider.hpp"
#include "menus.hpp"
#include "util/qt_dirs.hpp"
#include <QStringList>
#include <QRegExp>
#include <QSignalMapper>
#ifdef _WIN32
#include <shlobj.h>
/* typedef enum {
SHARD_PIDL = 0x00000001,
SHARD_PATHA = 0x00000002,
SHARD_PATHW = 0x00000003,
SHARD_APPIDINFO = 0x00000004,
SHARD_APPIDINFOIDLIST = 0x00000005,
SHARD_LINK = 0x00000006,
SHARD_APPIDINFOLINK = 0x00000007,
SHARD_SHELLITEM = 0x00000008
} SHARD; */
#define SHARD_PATHW 0x00000003
#include <vlc_charset.h>
#endif
RecentsMRL::RecentsMRL( intf_thread_t *_p_intf ) : p_intf( _p_intf )
{
stack = new QStringList;
signalMapper = new QSignalMapper( this );
CONNECT( signalMapper,
mapped(const QString & ),
this,
playMRL( const QString & ) );
/* Load the filter psz */
char* psz_tmp = var_InheritString( p_intf, "qt-recentplay-filter" );
if( psz_tmp && *psz_tmp )
filter = new QRegExp( psz_tmp, Qt::CaseInsensitive );
else
filter = NULL;
free( psz_tmp );
load();
isActive = var_InheritBool( p_intf, "qt-recentplay" );
if( !isActive ) clear();
}
RecentsMRL::~RecentsMRL()
{
delete filter;
delete stack;
}
void RecentsMRL::addRecent( const QString &mrl )
{
if ( !isActive || ( filter && filter->indexIn( mrl ) >= 0 ) )
return;
#ifdef _WIN32
/* Add to the Windows 7 default list in taskbar */
char* path = make_path( qtu( mrl ) );
if( path )
{
wchar_t *wmrl = ToWide( path );
SHAddToRecentDocs( SHARD_PATHW, wmrl );
free( wmrl );
free( path );
}
#endif
int i_index = stack->indexOf( mrl );
if( 0 <= i_index )
{
/* move to the front */
stack->move( i_index, 0 );
}
else
{
stack->prepend( mrl );
if( stack->count() > RECENTS_LIST_SIZE )
stack->takeLast();
}
VLCMenuBar::updateRecents( p_intf );
save();
}
void RecentsMRL::clear()
{
if ( stack->isEmpty() )
return;
stack->clear();
if( isActive ) VLCMenuBar::updateRecents( p_intf );
save();
}
QStringList RecentsMRL::recents()
{
return *stack;
}
void RecentsMRL::load()
{
/* Load from the settings */
QStringList list = getSettings()->value( "RecentsMRL/list" ).toStringList();
/* And filter the regexp on the list */
for( int i = 0; i < list.count(); ++i )
{
if ( !filter || filter->indexIn( list.at(i) ) == -1 )
stack->append( list.at(i) );
}
}
void RecentsMRL::save()
{
getSettings()->setValue( "RecentsMRL/list", *stack );
}
playlist_item_t *RecentsMRL::toPlaylist(int length)
{
playlist_item_t *p_node_recent = playlist_NodeCreate(THEPL, _("Recently Played"), THEPL->p_root, PLAYLIST_END, PLAYLIST_RO_FLAG, NULL);
if ( p_node_recent == NULL ) return NULL;
if (length == 0 || stack->count() < length)
length = stack->count();
for (int i = 0; i < length; i++)
{
input_item_t *p_input = input_item_New(qtu(stack->at(i)), NULL);
playlist_NodeAddInput(THEPL, p_input, p_node_recent, PLAYLIST_APPEND, PLAYLIST_END, false);
}
return p_node_recent;
}
void RecentsMRL::playMRL( const QString &mrl )
{
Open::openMRL( p_intf, mrl );
}
int Open::openMRL( intf_thread_t *p_intf,
const QString &mrl,
bool b_start,
bool b_playlist)
{
return openMRLwithOptions( p_intf, mrl, NULL, b_start, b_playlist );
}
int Open::openMRLwithOptions( intf_thread_t* p_intf,
const QString &mrl,
QStringList *options,
bool b_start,
bool b_playlist,
const char *title)
{
/* Options */
const char **ppsz_options = NULL;
int i_options = 0;
if( options != NULL && options->count() > 0 )
{
ppsz_options = (const char **)malloc( options->count() );
if( ppsz_options ) {
for( int j = 0; j < options->count(); j++ ) {
QString option = colon_unescape( options->at(j) );
if( !option.isEmpty() ) {
ppsz_options[j] = qtu(option);
i_options++;
}
}
}
}
/* Add to playlist */
int i_ret = playlist_AddExt( THEPL,
qtu(mrl), title,
PLAYLIST_APPEND | (b_start ? PLAYLIST_GO : PLAYLIST_PREPARSE),
PLAYLIST_END,
-1,
i_options, ppsz_options, VLC_INPUT_OPTION_TRUSTED,
b_playlist,
pl_Unlocked );
/* Add to recent items, only if played */
if( i_ret == VLC_SUCCESS && b_start && b_playlist )
RecentsMRL::getInstance( p_intf )->addRecent( mrl );
return i_ret;
}
<commit_msg>Qt: save recents on quit()<commit_after>/*****************************************************************************
* recents.cpp : Recents MRL (menu)
*****************************************************************************
* Copyright © 2008-2014 VideoLAN and VLC authors
* $Id$
*
* Authors: Ludovic Fauvet <[email protected]>
* Jean-baptiste Kempf <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* ( at your option ) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "qt4.hpp"
#include "recents.hpp"
#include "dialogs_provider.hpp"
#include "menus.hpp"
#include "util/qt_dirs.hpp"
#include <QStringList>
#include <QRegExp>
#include <QSignalMapper>
#ifdef _WIN32
#include <shlobj.h>
/* typedef enum {
SHARD_PIDL = 0x00000001,
SHARD_PATHA = 0x00000002,
SHARD_PATHW = 0x00000003,
SHARD_APPIDINFO = 0x00000004,
SHARD_APPIDINFOIDLIST = 0x00000005,
SHARD_LINK = 0x00000006,
SHARD_APPIDINFOLINK = 0x00000007,
SHARD_SHELLITEM = 0x00000008
} SHARD; */
#define SHARD_PATHW 0x00000003
#include <vlc_charset.h>
#endif
RecentsMRL::RecentsMRL( intf_thread_t *_p_intf ) : p_intf( _p_intf )
{
stack = new QStringList;
signalMapper = new QSignalMapper( this );
CONNECT( signalMapper,
mapped(const QString & ),
this,
playMRL( const QString & ) );
/* Load the filter psz */
char* psz_tmp = var_InheritString( p_intf, "qt-recentplay-filter" );
if( psz_tmp && *psz_tmp )
filter = new QRegExp( psz_tmp, Qt::CaseInsensitive );
else
filter = NULL;
free( psz_tmp );
load();
isActive = var_InheritBool( p_intf, "qt-recentplay" );
if( !isActive ) clear();
}
RecentsMRL::~RecentsMRL()
{
save();
delete filter;
delete stack;
}
void RecentsMRL::addRecent( const QString &mrl )
{
if ( !isActive || ( filter && filter->indexIn( mrl ) >= 0 ) )
return;
#ifdef _WIN32
/* Add to the Windows 7 default list in taskbar */
char* path = make_path( qtu( mrl ) );
if( path )
{
wchar_t *wmrl = ToWide( path );
SHAddToRecentDocs( SHARD_PATHW, wmrl );
free( wmrl );
free( path );
}
#endif
int i_index = stack->indexOf( mrl );
if( 0 <= i_index )
{
/* move to the front */
stack->move( i_index, 0 );
}
else
{
stack->prepend( mrl );
if( stack->count() > RECENTS_LIST_SIZE )
stack->takeLast();
}
VLCMenuBar::updateRecents( p_intf );
save();
}
void RecentsMRL::clear()
{
if ( stack->isEmpty() )
return;
stack->clear();
if( isActive ) VLCMenuBar::updateRecents( p_intf );
save();
}
QStringList RecentsMRL::recents()
{
return *stack;
}
void RecentsMRL::load()
{
/* Load from the settings */
QStringList list = getSettings()->value( "RecentsMRL/list" ).toStringList();
/* And filter the regexp on the list */
for( int i = 0; i < list.count(); ++i )
{
if ( !filter || filter->indexIn( list.at(i) ) == -1 )
stack->append( list.at(i) );
}
}
void RecentsMRL::save()
{
getSettings()->setValue( "RecentsMRL/list", *stack );
}
playlist_item_t *RecentsMRL::toPlaylist(int length)
{
playlist_item_t *p_node_recent = playlist_NodeCreate(THEPL, _("Recently Played"), THEPL->p_root, PLAYLIST_END, PLAYLIST_RO_FLAG, NULL);
if ( p_node_recent == NULL ) return NULL;
if (length == 0 || stack->count() < length)
length = stack->count();
for (int i = 0; i < length; i++)
{
input_item_t *p_input = input_item_New(qtu(stack->at(i)), NULL);
playlist_NodeAddInput(THEPL, p_input, p_node_recent, PLAYLIST_APPEND, PLAYLIST_END, false);
}
return p_node_recent;
}
void RecentsMRL::playMRL( const QString &mrl )
{
Open::openMRL( p_intf, mrl );
}
int Open::openMRL( intf_thread_t *p_intf,
const QString &mrl,
bool b_start,
bool b_playlist)
{
return openMRLwithOptions( p_intf, mrl, NULL, b_start, b_playlist );
}
int Open::openMRLwithOptions( intf_thread_t* p_intf,
const QString &mrl,
QStringList *options,
bool b_start,
bool b_playlist,
const char *title)
{
/* Options */
const char **ppsz_options = NULL;
int i_options = 0;
if( options != NULL && options->count() > 0 )
{
ppsz_options = (const char **)malloc( options->count() );
if( ppsz_options ) {
for( int j = 0; j < options->count(); j++ ) {
QString option = colon_unescape( options->at(j) );
if( !option.isEmpty() ) {
ppsz_options[j] = qtu(option);
i_options++;
}
}
}
}
/* Add to playlist */
int i_ret = playlist_AddExt( THEPL,
qtu(mrl), title,
PLAYLIST_APPEND | (b_start ? PLAYLIST_GO : PLAYLIST_PREPARSE),
PLAYLIST_END,
-1,
i_options, ppsz_options, VLC_INPUT_OPTION_TRUSTED,
b_playlist,
pl_Unlocked );
/* Add to recent items, only if played */
if( i_ret == VLC_SUCCESS && b_start && b_playlist )
RecentsMRL::getInstance( p_intf )->addRecent( mrl );
return i_ret;
}
<|endoftext|> |
<commit_before>// $Id: elem_refinement.C,v 1.2 2003-05-29 15:54:06 benkirk Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm>
#include <iterator>
#include <set>
// Local includes
#include "elem.h"
#include "mesh_base.h"
//--------------------------------------------------------------------
// Elem methods
/**
* The following functions only apply when
* AMR is enabled and thus are not present
* otherwise.
*/
#ifdef ENABLE_AMR
void Elem::refine (MeshBase& mesh)
{
assert (this->refinement_flag() == Elem::REFINE);
assert (this->active());
assert (_children == NULL);
// Two big prime numbers less than
// sqrt(max_unsigned_int) for key creation.
const unsigned int bp1 = 65449;
const unsigned int bp2 = 48661;
// Create my children
{
_children = new Elem*[this->n_children()];
for (unsigned int c=0; c<this->n_children(); c++)
{
_children[c] = Elem::build(this->type(), this);
_children[c]->set_refinement_flag(Elem::JUST_REFINED);
}
}
// Compute new nodal locations
// and asssign nodes to children
{
// Make these static. It is unlikely the
// sizes will change from call to call, so having these
// static should save on reallocations
std::vector<std::vector<Point> > p (this->n_children());
std::vector<std::vector<unsigned int> > keys (this->n_children());
std::vector<std::vector<Node*> > nodes(this->n_children());
// compute new nodal locations
for (unsigned int c=0; c<this->n_children(); c++)
{
p[c].resize (this->child(c)->n_nodes());
keys[c].resize (this->child(c)->n_nodes());
nodes[c].resize(this->child(c)->n_nodes());
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
// zero entries
p[c][nc].zero();
keys[c][nc] = 0;
nodes[c][nc] = NULL;
for (unsigned int n=0; n<this->n_nodes(); n++)
{
// The value from the embedding matrix
const float em_val = this->embedding_matrix(c,nc,n);
if (em_val != 0.)
{
p[c][nc].add_scaled (this->point(n), em_val);
// We may have found the node, in which case we
// won't need to look it up later.
if (em_val == 1.)
nodes[c][nc] = this->get_node(n);
// Otherwise build the key to look for the node
else
{
// An unsigned int associated with the
// address of the node n. We can't use the
// node number since they can change.
const unsigned int n_id =
#if SIZEOF_INT == SIZEOF_VOID_P
// 32-bit machines
reinterpret_cast<unsigned int>(this->get_node(n));
#elif SIZEOF_LONG_LONG_INT == SIZEOF_VOID_P
// 64-bit machines
// Another big prime number less than max_unsigned_int
// for key creation on 64-bit machines
const unsigned int bp3 = 4294967291;
static_cast<long long unsigned int>(this->get_node(n))%
bp3;
#else
// Huh?
0; error();
#endif
// Compute the key for this new node nc. This will
// be used to locate the node if it already exists
// in the mesh.
keys[c][nc] +=
(((static_cast<unsigned int>(em_val*100000.)%bp1) *
(n_id%bp1))%bp1)*bp2;
}
}
}
}
// assign nodes to children & add them to the mesh
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
if (nodes[c][nc] != NULL)
{
this->child(c)->set_node(nc) = nodes[c][nc];
}
else
{
this->child(c)->set_node(nc) =
mesh.mesh_refinement.add_point(p[c][nc],
keys[c][nc]);
}
}
mesh.add_elem(this->child(c),
mesh.mesh_refinement.new_element_number());
}
}
// Possibly add boundary information
for (unsigned int s=0; s<this->n_neighbors(); s++)
if (this->neighbor(s) == NULL)
{
const short int id = mesh.boundary_info.boundary_id(this, s);
if (id != mesh.boundary_info.invalid_id)
for (unsigned int sc=0; sc<this->n_children_per_side(s); sc++)
mesh.boundary_info.add_side(this->child(this->side_children_matrix(s,sc)),
s,
id);
}
// Un-set my refinement flag now
this->set_refinement_flag(Elem::DO_NOTHING);
assert (!this->active());
}
void Elem::coarsen()
{
assert (this->refinement_flag() == Elem::COARSEN);
assert (!this->active());
// Delete the storage for my children
delete [] _children;
_children = NULL;
this->set_refinement_flag(Elem::DO_NOTHING);
assert (this->active());
}
#endif // #ifdef ENABLE_AMR
<commit_msg>64-bit fix for SGI<commit_after>// $Id: elem_refinement.C,v 1.3 2003-05-29 16:58:49 benkirk Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm>
#include <iterator>
#include <set>
// Local includes
#include "elem.h"
#include "mesh_base.h"
//--------------------------------------------------------------------
// Elem methods
/**
* The following functions only apply when
* AMR is enabled and thus are not present
* otherwise.
*/
#ifdef ENABLE_AMR
void Elem::refine (MeshBase& mesh)
{
assert (this->refinement_flag() == Elem::REFINE);
assert (this->active());
assert (_children == NULL);
// Two big prime numbers less than
// sqrt(max_unsigned_int) for key creation.
const unsigned int bp1 = 65449;
const unsigned int bp2 = 48661;
// Create my children
{
_children = new Elem*[this->n_children()];
for (unsigned int c=0; c<this->n_children(); c++)
{
_children[c] = Elem::build(this->type(), this);
_children[c]->set_refinement_flag(Elem::JUST_REFINED);
}
}
// Compute new nodal locations
// and asssign nodes to children
{
// Make these static. It is unlikely the
// sizes will change from call to call, so having these
// static should save on reallocations
std::vector<std::vector<Point> > p (this->n_children());
std::vector<std::vector<unsigned int> > keys (this->n_children());
std::vector<std::vector<Node*> > nodes(this->n_children());
// compute new nodal locations
for (unsigned int c=0; c<this->n_children(); c++)
{
p[c].resize (this->child(c)->n_nodes());
keys[c].resize (this->child(c)->n_nodes());
nodes[c].resize(this->child(c)->n_nodes());
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
// zero entries
p[c][nc].zero();
keys[c][nc] = 0;
nodes[c][nc] = NULL;
for (unsigned int n=0; n<this->n_nodes(); n++)
{
// The value from the embedding matrix
const float em_val = this->embedding_matrix(c,nc,n);
if (em_val != 0.)
{
p[c][nc].add_scaled (this->point(n), em_val);
// We may have found the node, in which case we
// won't need to look it up later.
if (em_val == 1.)
nodes[c][nc] = this->get_node(n);
// Otherwise build the key to look for the node
else
{
// An unsigned int associated with the
// address of the node n. We can't use the
// node number since they can change.
#if SIZEOF_INT == SIZEOF_VOID_P
// 32-bit machines
const unsigned int n_id =
reinterpret_cast<unsigned int>(this->get_node(n));
#elif SIZEOF_LONG_LONG_INT == SIZEOF_VOID_P
// 64-bit machines
// Another big prime number less than max_unsigned_int
// for key creation on 64-bit machines
const unsigned int bp3 = 4294967291;
const unsigned int n_id =
reinterpret_cast<long long unsigned int>(this->get_node(n))%bp3;
#else
// Huh?
DIE HERE... CANNOT COMPILE
#endif
// Compute the key for this new node nc. This will
// be used to locate the node if it already exists
// in the mesh.
keys[c][nc] +=
(((static_cast<unsigned int>(em_val*100000.)%bp1) *
(n_id%bp1))%bp1)*bp2;
}
}
}
}
// assign nodes to children & add them to the mesh
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
if (nodes[c][nc] != NULL)
{
this->child(c)->set_node(nc) = nodes[c][nc];
}
else
{
this->child(c)->set_node(nc) =
mesh.mesh_refinement.add_point(p[c][nc],
keys[c][nc]);
}
}
mesh.add_elem(this->child(c),
mesh.mesh_refinement.new_element_number());
}
}
// Possibly add boundary information
for (unsigned int s=0; s<this->n_neighbors(); s++)
if (this->neighbor(s) == NULL)
{
const short int id = mesh.boundary_info.boundary_id(this, s);
if (id != mesh.boundary_info.invalid_id)
for (unsigned int sc=0; sc<this->n_children_per_side(s); sc++)
mesh.boundary_info.add_side(this->child(this->side_children_matrix(s,sc)),
s,
id);
}
// Un-set my refinement flag now
this->set_refinement_flag(Elem::DO_NOTHING);
assert (!this->active());
}
void Elem::coarsen()
{
assert (this->refinement_flag() == Elem::COARSEN);
assert (!this->active());
// Delete the storage for my children
delete [] _children;
_children = NULL;
this->set_refinement_flag(Elem::DO_NOTHING);
assert (this->active());
}
#endif // #ifdef ENABLE_AMR
<|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh_config.h"
// Currently, the EigenSystem should only be available
// if SLEPc support is enabled.
#if defined(LIBMESH_HAVE_SLEPC)
// C++ includes
// Local includes
#include "eigen_system.h"
#include "equation_systems.h"
#include "sparse_matrix.h"
#include "eigen_solver.h"
#include "dof_map.h"
#include "mesh.h"
#include "qoi_set.h"
// ------------------------------------------------------------
// EigenSystem implementation
EigenSystem::EigenSystem (EquationSystems& es,
const std::string& name,
const unsigned int number
) :
Parent (es, name, number),
matrix_A (NULL),
matrix_B (NULL),
eigen_solver (EigenSolver<Number>::build()),
_n_converged_eigenpairs (0),
_n_iterations (0),
_is_generalized_eigenproblem (false),
_eigen_problem_type (NHEP)
{
}
EigenSystem::~EigenSystem ()
{
// clear data
this->clear();
}
void EigenSystem::clear ()
{
// Clear the parent data
Parent::clear();
// delete the matricies
delete matrix_A;
delete matrix_B;
// NULL-out the matricies.
matrix_A = NULL;
matrix_B = NULL;
// clear the solver
eigen_solver->clear();
}
void EigenSystem::set_eigenproblem_type (EigenProblemType ept)
{
_eigen_problem_type = ept;
eigen_solver->set_eigenproblem_type(ept);
// std::cout<< "The Problem type is set to be: "<<std::endl;
switch (_eigen_problem_type)
{
case HEP: // std::cout<<"Hermitian"<<std::endl;
break;
case NHEP: // std::cout<<"Non-Hermitian"<<std::endl;
break;
case GHEP: // std::cout<<"Gerneralized Hermitian"<<std::endl;
break;
case GNHEP: // std::cout<<"Generalized Non-Hermitian"<<std::endl;
break;
default: // std::cout<<"not properly specified"<<std::endl;
libmesh_error();
break;
}
}
void EigenSystem::init_data ()
{
// initialize parent data
Parent::init_data();
// define the type of eigenproblem
if (_eigen_problem_type == GNHEP || _eigen_problem_type == GHEP)
_is_generalized_eigenproblem = true;
// build the system matrix
matrix_A = SparseMatrix<Number>::build().release();
// add matrix to the _dof_map
// and compute the sparsity
DofMap& dof_map = this->get_dof_map();
dof_map.attach_matrix(*matrix_A);
// build matrix_B only in case of a
// generalized problem
if (_is_generalized_eigenproblem)
{
matrix_B = SparseMatrix<Number>::build().release();
dof_map.attach_matrix(*matrix_B);
}
dof_map.compute_sparsity(this->get_mesh());
// initialize and zero system matrix
matrix_A->init();
matrix_A->zero();
// eventually initialize and zero system matrix_B
if (_is_generalized_eigenproblem)
{
matrix_B->init();
matrix_B->zero();
}
}
void EigenSystem::reinit ()
{
// initialize parent data
Parent::reinit();
}
void EigenSystem::solve ()
{
// A reference to the EquationSystems
EquationSystems& es = this->get_equation_systems();
// check that necessary parameters have been set
libmesh_assert (es.parameters.have_parameter<unsigned int>("eigenpairs"));
libmesh_assert (es.parameters.have_parameter<unsigned int>("basis vectors"));
if (this->assemble_before_solve)
// Assemble the linear system
this->assemble ();
// Get the tolerance for the solver and the maximum
// number of iterations. Here, we simply adopt the linear solver
// specific parameters.
const Real tol =
es.parameters.get<Real>("linear solver tolerance");
const unsigned int maxits =
es.parameters.get<unsigned int>("linear solver maximum iterations");
const unsigned int nev =
es.parameters.get<unsigned int>("eigenpairs");
const unsigned int ncv =
es.parameters.get<unsigned int>("basis vectors");
std::pair<unsigned int, unsigned int> solve_data;
// call the solver depending on the type of eigenproblem
if (_is_generalized_eigenproblem)
{
//in case of a generalized eigenproblem
solve_data = eigen_solver->solve_generalized (*matrix_A,*matrix_B, nev, ncv, tol, maxits);
}
else
{
libmesh_assert (matrix_B == NULL);
//in case of a standard eigenproblem
solve_data = eigen_solver->solve_standard (*matrix_A, nev, ncv, tol, maxits);
}
this->_n_converged_eigenpairs = solve_data.first;
this->_n_iterations = solve_data.second;
}
void EigenSystem::sensitivity_solve (const ParameterVector&)
{
libmesh_not_implemented();
}
void EigenSystem::adjoint_solve (const QoiSet&)
{
libmesh_not_implemented();
}
void EigenSystem::adjoint_qoi_parameter_sensitivity
(const QoISet&,
const ParameterVector&,
SensitivityData&)
{
libmesh_not_implemented();
}
void EigenSystem::forward_qoi_parameter_sensitivity
(const QoISet&,
const ParameterVector&,
SensitivityData&)
{
libmesh_not_implemented();
}
void EigenSystem::assemble ()
{
// Assemble the linear system
Parent::assemble ();
}
std::pair<Real, Real> EigenSystem::get_eigenpair (unsigned int i)
{
// call the eigen_solver get_eigenpair method
return eigen_solver->get_eigenpair (i, *solution);
}
#endif // LIBMESH_HAVE_SLEPC
<commit_msg>Another small fix for --enable_slepc<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh_config.h"
// Currently, the EigenSystem should only be available
// if SLEPc support is enabled.
#if defined(LIBMESH_HAVE_SLEPC)
// C++ includes
// Local includes
#include "eigen_system.h"
#include "equation_systems.h"
#include "sparse_matrix.h"
#include "eigen_solver.h"
#include "dof_map.h"
#include "mesh.h"
#include "qoi_set.h"
// ------------------------------------------------------------
// EigenSystem implementation
EigenSystem::EigenSystem (EquationSystems& es,
const std::string& name,
const unsigned int number
) :
Parent (es, name, number),
matrix_A (NULL),
matrix_B (NULL),
eigen_solver (EigenSolver<Number>::build()),
_n_converged_eigenpairs (0),
_n_iterations (0),
_is_generalized_eigenproblem (false),
_eigen_problem_type (NHEP)
{
}
EigenSystem::~EigenSystem ()
{
// clear data
this->clear();
}
void EigenSystem::clear ()
{
// Clear the parent data
Parent::clear();
// delete the matricies
delete matrix_A;
delete matrix_B;
// NULL-out the matricies.
matrix_A = NULL;
matrix_B = NULL;
// clear the solver
eigen_solver->clear();
}
void EigenSystem::set_eigenproblem_type (EigenProblemType ept)
{
_eigen_problem_type = ept;
eigen_solver->set_eigenproblem_type(ept);
// std::cout<< "The Problem type is set to be: "<<std::endl;
switch (_eigen_problem_type)
{
case HEP: // std::cout<<"Hermitian"<<std::endl;
break;
case NHEP: // std::cout<<"Non-Hermitian"<<std::endl;
break;
case GHEP: // std::cout<<"Gerneralized Hermitian"<<std::endl;
break;
case GNHEP: // std::cout<<"Generalized Non-Hermitian"<<std::endl;
break;
default: // std::cout<<"not properly specified"<<std::endl;
libmesh_error();
break;
}
}
void EigenSystem::init_data ()
{
// initialize parent data
Parent::init_data();
// define the type of eigenproblem
if (_eigen_problem_type == GNHEP || _eigen_problem_type == GHEP)
_is_generalized_eigenproblem = true;
// build the system matrix
matrix_A = SparseMatrix<Number>::build().release();
// add matrix to the _dof_map
// and compute the sparsity
DofMap& dof_map = this->get_dof_map();
dof_map.attach_matrix(*matrix_A);
// build matrix_B only in case of a
// generalized problem
if (_is_generalized_eigenproblem)
{
matrix_B = SparseMatrix<Number>::build().release();
dof_map.attach_matrix(*matrix_B);
}
dof_map.compute_sparsity(this->get_mesh());
// initialize and zero system matrix
matrix_A->init();
matrix_A->zero();
// eventually initialize and zero system matrix_B
if (_is_generalized_eigenproblem)
{
matrix_B->init();
matrix_B->zero();
}
}
void EigenSystem::reinit ()
{
// initialize parent data
Parent::reinit();
}
void EigenSystem::solve ()
{
// A reference to the EquationSystems
EquationSystems& es = this->get_equation_systems();
// check that necessary parameters have been set
libmesh_assert (es.parameters.have_parameter<unsigned int>("eigenpairs"));
libmesh_assert (es.parameters.have_parameter<unsigned int>("basis vectors"));
if (this->assemble_before_solve)
// Assemble the linear system
this->assemble ();
// Get the tolerance for the solver and the maximum
// number of iterations. Here, we simply adopt the linear solver
// specific parameters.
const Real tol =
es.parameters.get<Real>("linear solver tolerance");
const unsigned int maxits =
es.parameters.get<unsigned int>("linear solver maximum iterations");
const unsigned int nev =
es.parameters.get<unsigned int>("eigenpairs");
const unsigned int ncv =
es.parameters.get<unsigned int>("basis vectors");
std::pair<unsigned int, unsigned int> solve_data;
// call the solver depending on the type of eigenproblem
if (_is_generalized_eigenproblem)
{
//in case of a generalized eigenproblem
solve_data = eigen_solver->solve_generalized (*matrix_A,*matrix_B, nev, ncv, tol, maxits);
}
else
{
libmesh_assert (matrix_B == NULL);
//in case of a standard eigenproblem
solve_data = eigen_solver->solve_standard (*matrix_A, nev, ncv, tol, maxits);
}
this->_n_converged_eigenpairs = solve_data.first;
this->_n_iterations = solve_data.second;
}
void EigenSystem::assemble_residual_derivatives (const ParameterVector&)
{
libmesh_not_implemented();
}
void EigenSystem::sensitivity_solve (const ParameterVector&)
{
libmesh_not_implemented();
}
void EigenSystem::adjoint_solve (const QoISet&)
{
libmesh_not_implemented();
}
void EigenSystem::adjoint_qoi_parameter_sensitivity
(const QoISet&,
const ParameterVector&,
SensitivityData&)
{
libmesh_not_implemented();
}
void EigenSystem::forward_qoi_parameter_sensitivity
(const QoISet&,
const ParameterVector&,
SensitivityData&)
{
libmesh_not_implemented();
}
void EigenSystem::assemble ()
{
// Assemble the linear system
Parent::assemble ();
}
std::pair<Real, Real> EigenSystem::get_eigenpair (unsigned int i)
{
// call the eigen_solver get_eigenpair method
return eigen_solver->get_eigenpair (i, *solution);
}
#endif // LIBMESH_HAVE_SLEPC
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: parsersvc.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2003-04-17 13:35:35 $
*
* 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: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "parsersvc.hxx"
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_XML_SCHEMAPARSER_HXX
#include "schemaparser.hxx"
#endif
#ifndef CONFIGMGR_XML_LAYERPARSER_HXX
#include "layerparser.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_
#include <com/sun/star/configuration/backend/XSchema.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_
#include <com/sun/star/configuration/backend/XLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_MALFORMEDDATAEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/MalformedDataException.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace xml
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace io = ::com::sun::star::io;
namespace sax = ::com::sun::star::xml::sax;
namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
template <class BackendInterface>
struct ParserServiceTraits;
// -----------------------------------------------------------------------------
static inline void clear(OUString & _rs) { _rs = OUString(); }
// -----------------------------------------------------------------------------
template <class BackendInterface>
ParserService<BackendInterface>::ParserService(CreationArg _xContext)
: m_xServiceFactory(_xContext->getServiceManager(), uno::UNO_QUERY)
, m_aInputSource()
{
if (!m_xServiceFactory.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Context has no service factory"));
throw uno::RuntimeException(sMessage,NULL);
}
}
// -----------------------------------------------------------------------------
// XInitialization
template <class BackendInterface>
void SAL_CALL
ParserService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
switch(aArguments.getLength())
{
case 0:
break;
case 1:
if (aArguments[0] >>= m_aInputSource)
break;
if (aArguments[0] >>= m_aInputSource.aInputStream)
break;
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration Parser"
"- InputSource or XInputStream expected"));
throw lang::IllegalArgumentException(sMessage,*this,1);
}
default:
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser"));
throw lang::IllegalArgumentException(sMessage,*this,0);
}
}
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
inline
ServiceInfoHelper ParserService<BackendInterface>::getServiceInfo()
{
return ParserServiceTraits<BackendInterface>::getServiceInfo();
}
// -----------------------------------------------------------------------------
// XServiceInfo
template <class BackendInterface>
::rtl::OUString SAL_CALL
ParserService<BackendInterface>::getImplementationName( )
throw (uno::RuntimeException)
{
return getServiceInfo().getImplementationName();
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
sal_Bool SAL_CALL
ParserService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException)
{
return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Sequence< ::rtl::OUString > SAL_CALL
ParserService<BackendInterface>::getSupportedServiceNames( )
throw (uno::RuntimeException)
{
return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
void SAL_CALL
ParserService<BackendInterface>::setInputStream( const uno::Reference< io::XInputStream >& aStream )
throw (uno::RuntimeException)
{
clear( m_aInputSource.sEncoding );
clear( m_aInputSource.sSystemId );
// clear( m_aInputSource.sPublicId );
m_aInputSource.aInputStream = aStream;
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< io::XInputStream > SAL_CALL
ParserService<BackendInterface>::getInputStream( )
throw (uno::RuntimeException)
{
return m_aInputSource.aInputStream;
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
void ParserService<BackendInterface>::parse(uno::Reference< sax::XDocumentHandler > const & _xHandler)
// throw (backenduno::MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
OSL_PRECOND( _xHandler.is(), "ParserService: No SAX handler to parse to");
typedef uno::Reference< sax::XParser > SaxParser;
rtl::OUString const k_sSaxParserService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"));
SaxParser xParser = SaxParser::query( m_xServiceFactory->createInstance(k_sSaxParserService) );
if (!xParser.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Cannot create SAX Parser"));
throw uno::RuntimeException(sMessage,*this);
}
try
{
xParser->setDocumentHandler(_xHandler);
xParser->parseStream( m_aInputSource );
}
catch (sax::SAXException & e)
{
uno::Any aWrapped = e.WrappedException.hasValue() ? e.WrappedException : uno::makeAny( e );
OUString sSAXMessage = e.Message;
// Expatwrap SAX service doubly wraps its errors ??
sax::SAXException eInner;
if (aWrapped >>= eInner)
{
if (eInner.WrappedException.hasValue()) aWrapped = eInner.WrappedException;
rtl::OUStringBuffer sMsgBuf(eInner.Message);
sMsgBuf.appendAscii("- {Parser Error: ").append(sSAXMessage).appendAscii(" }.");
sSAXMessage = sMsgBuf.makeStringAndClear();
}
static backenduno::MalformedDataException const * const forDataError = 0;
static lang::WrappedTargetException const * const forWrappedError = 0;
if (aWrapped.isExtractableTo(getCppuType(forDataError)) ||
aWrapped.isExtractableTo(getCppuType(forWrappedError)))
{
cppu::throwException(aWrapped);
OSL_ASSERT(!"not reached");
}
rtl::OUStringBuffer sMessageBuf;
sMessageBuf.appendAscii("Configuration Parser: a ").append( aWrapped.getValueTypeName() );
sMessageBuf.appendAscii(" occurred while parsing: ");
sMessageBuf.append(sSAXMessage);
throw lang::WrappedTargetException(sMessageBuf.makeStringAndClear(),*this,aWrapped);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
AsciiServiceName const aSchemaParserServices[] =
{
"com.sun.star.configuration.backend.xml.SchemaParser",
0
};
const ServiceImplementationInfo aSchemaParserSI =
{
"com.sun.star.comp.configuration.backend.xml.SchemaParser",
aSchemaParserServices,
0
};
// -----------------------------------------------------------------------------
AsciiServiceName const aLayerParserServices[] =
{
"com.sun.star.configuration.backend.xml.LayerParser",
0
};
const ServiceImplementationInfo aLayerParserSI =
{
"com.sun.star.comp.configuration.backend.xml.LayerParser",
aLayerParserServices,
0
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XSchema >
{
typedef backenduno::XSchemaHandler Handler;
static ServiceImplementationInfo const * getServiceInfo()
{ return & aSchemaParserSI; }
};
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XLayer >
{
typedef backenduno::XLayerHandler Handler;
static ServiceImplementationInfo const * getServiceInfo()
{ return & aLayerParserSI; }
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
typedef ParserService< backenduno::XSchema > SchemaParserService_Base;
class SchemaParserService : public SchemaParserService_Base
{
public:
typedef SchemaParser::HandlerRef HandlerArg;
SchemaParserService(CreationArg _xContext)
: SchemaParserService_Base(_xContext)
{
}
virtual void SAL_CALL readSchema( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
virtual void SAL_CALL readComponent( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
virtual void SAL_CALL readTemplates( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
};
// -----------------------------------------------------------------------------
typedef ParserService< backenduno::XLayer > LayerParserService_Base;
class LayerParserService : public LayerParserService_Base
{
public:
typedef LayerParser::HandlerRef HandlerArg;
LayerParserService(CreationArg _xContext)
: LayerParserService_Base(_xContext)
{
}
virtual void SAL_CALL readData( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL instantiateSchemaParser( CreationContext const& xContext )
{
return * new SchemaParserService(xContext);
}
uno::Reference< uno::XInterface > SAL_CALL instantiateLayerParser( CreationContext const& xContext )
{
return * new LayerParserService(xContext);
}
// -----------------------------------------------------------------------------
const ServiceRegistrationInfo* getSchemaParserServiceInfo()
{ return getRegistrationInfo(& aSchemaParserSI); }
const ServiceRegistrationInfo* getLayerParserServiceInfo()
{ return getRegistrationInfo(& aLayerParserSI); }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
static OUString nullHandlerMessage(char const * where)
{
OSL_ASSERT(where);
OUString msg = OUString::createFromAscii(where);
return msg.concat(OUString::createFromAscii(": Error - NULL handler passed."));
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readSchema( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readSchema"),*this);
SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectAll);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readComponent( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readComponent"),*this);
SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectComponent);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readTemplates( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readTemplates"),*this);
SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectTemplates);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL LayerParserService::readData( uno::Reference< backenduno::XLayerHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("LayerParserService::readData"),*this);
SaxHandler xHandler = new LayerParser(this->getServiceFactory(),aHandler);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<commit_msg>INTEGRATION: CWS cfgapi (1.6.94); FILE MERGED 2004/05/07 10:47:02 ssmith 1.6.94.1: #112671# clearing inputStream after initial parsing<commit_after>/*************************************************************************
*
* $RCSfile: parsersvc.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2004-06-18 15:52:22 $
*
* 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: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "parsersvc.hxx"
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_XML_SCHEMAPARSER_HXX
#include "schemaparser.hxx"
#endif
#ifndef CONFIGMGR_XML_LAYERPARSER_HXX
#include "layerparser.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_
#include <com/sun/star/configuration/backend/XSchema.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_
#include <com/sun/star/configuration/backend/XLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_MALFORMEDDATAEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/MalformedDataException.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace xml
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace io = ::com::sun::star::io;
namespace sax = ::com::sun::star::xml::sax;
namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
template <class BackendInterface>
struct ParserServiceTraits;
// -----------------------------------------------------------------------------
static inline void clear(OUString & _rs) { _rs = OUString(); }
// -----------------------------------------------------------------------------
template <class BackendInterface>
ParserService<BackendInterface>::ParserService(CreationArg _xContext)
: m_xServiceFactory(_xContext->getServiceManager(), uno::UNO_QUERY)
, m_aInputSource()
{
if (!m_xServiceFactory.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Context has no service factory"));
throw uno::RuntimeException(sMessage,NULL);
}
}
// -----------------------------------------------------------------------------
// XInitialization
template <class BackendInterface>
void SAL_CALL
ParserService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
switch(aArguments.getLength())
{
case 0:
break;
case 1:
if (aArguments[0] >>= m_aInputSource)
break;
if (aArguments[0] >>= m_aInputSource.aInputStream)
break;
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration Parser"
"- InputSource or XInputStream expected"));
throw lang::IllegalArgumentException(sMessage,*this,1);
}
default:
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser"));
throw lang::IllegalArgumentException(sMessage,*this,0);
}
}
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
inline
ServiceInfoHelper ParserService<BackendInterface>::getServiceInfo()
{
return ParserServiceTraits<BackendInterface>::getServiceInfo();
}
// -----------------------------------------------------------------------------
// XServiceInfo
template <class BackendInterface>
::rtl::OUString SAL_CALL
ParserService<BackendInterface>::getImplementationName( )
throw (uno::RuntimeException)
{
return getServiceInfo().getImplementationName();
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
sal_Bool SAL_CALL
ParserService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException)
{
return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Sequence< ::rtl::OUString > SAL_CALL
ParserService<BackendInterface>::getSupportedServiceNames( )
throw (uno::RuntimeException)
{
return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
void SAL_CALL
ParserService<BackendInterface>::setInputStream( const uno::Reference< io::XInputStream >& aStream )
throw (uno::RuntimeException)
{
clear( m_aInputSource.sEncoding );
clear( m_aInputSource.sSystemId );
// clear( m_aInputSource.sPublicId );
m_aInputSource.aInputStream = aStream;
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< io::XInputStream > SAL_CALL
ParserService<BackendInterface>::getInputStream( )
throw (uno::RuntimeException)
{
return m_aInputSource.aInputStream;
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
void ParserService<BackendInterface>::parse(uno::Reference< sax::XDocumentHandler > const & _xHandler)
// throw (backenduno::MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
OSL_PRECOND( _xHandler.is(), "ParserService: No SAX handler to parse to");
typedef uno::Reference< sax::XParser > SaxParser;
rtl::OUString const k_sSaxParserService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"));
SaxParser xParser = SaxParser::query( m_xServiceFactory->createInstance(k_sSaxParserService) );
if (!xParser.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Cannot create SAX Parser"));
throw uno::RuntimeException(sMessage,*this);
}
try
{
xParser->setDocumentHandler(_xHandler);
sax::InputSource aInputSourceCopy = m_aInputSource;
//Set the sax input stream to null, an input stream can only be parsed once
m_aInputSource.aInputStream = NULL;
xParser->parseStream( aInputSourceCopy );
}
catch (sax::SAXException & e)
{
uno::Any aWrapped = e.WrappedException.hasValue() ? e.WrappedException : uno::makeAny( e );
OUString sSAXMessage = e.Message;
// Expatwrap SAX service doubly wraps its errors ??
sax::SAXException eInner;
if (aWrapped >>= eInner)
{
if (eInner.WrappedException.hasValue()) aWrapped = eInner.WrappedException;
rtl::OUStringBuffer sMsgBuf(eInner.Message);
sMsgBuf.appendAscii("- {Parser Error: ").append(sSAXMessage).appendAscii(" }.");
sSAXMessage = sMsgBuf.makeStringAndClear();
}
static backenduno::MalformedDataException const * const forDataError = 0;
static lang::WrappedTargetException const * const forWrappedError = 0;
if (aWrapped.isExtractableTo(getCppuType(forDataError)) ||
aWrapped.isExtractableTo(getCppuType(forWrappedError)))
{
cppu::throwException(aWrapped);
OSL_ASSERT(!"not reached");
}
rtl::OUStringBuffer sMessageBuf;
sMessageBuf.appendAscii("Configuration Parser: a ").append( aWrapped.getValueTypeName() );
sMessageBuf.appendAscii(" occurred while parsing: ");
sMessageBuf.append(sSAXMessage);
throw lang::WrappedTargetException(sMessageBuf.makeStringAndClear(),*this,aWrapped);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
AsciiServiceName const aSchemaParserServices[] =
{
"com.sun.star.configuration.backend.xml.SchemaParser",
0
};
const ServiceImplementationInfo aSchemaParserSI =
{
"com.sun.star.comp.configuration.backend.xml.SchemaParser",
aSchemaParserServices,
0
};
// -----------------------------------------------------------------------------
AsciiServiceName const aLayerParserServices[] =
{
"com.sun.star.configuration.backend.xml.LayerParser",
0
};
const ServiceImplementationInfo aLayerParserSI =
{
"com.sun.star.comp.configuration.backend.xml.LayerParser",
aLayerParserServices,
0
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XSchema >
{
typedef backenduno::XSchemaHandler Handler;
static ServiceImplementationInfo const * getServiceInfo()
{ return & aSchemaParserSI; }
};
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XLayer >
{
typedef backenduno::XLayerHandler Handler;
static ServiceImplementationInfo const * getServiceInfo()
{ return & aLayerParserSI; }
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
typedef ParserService< backenduno::XSchema > SchemaParserService_Base;
class SchemaParserService : public SchemaParserService_Base
{
public:
typedef SchemaParser::HandlerRef HandlerArg;
SchemaParserService(CreationArg _xContext)
: SchemaParserService_Base(_xContext)
{
}
virtual void SAL_CALL readSchema( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
virtual void SAL_CALL readComponent( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
virtual void SAL_CALL readTemplates( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
};
// -----------------------------------------------------------------------------
typedef ParserService< backenduno::XLayer > LayerParserService_Base;
class LayerParserService : public LayerParserService_Base
{
public:
typedef LayerParser::HandlerRef HandlerArg;
LayerParserService(CreationArg _xContext)
: LayerParserService_Base(_xContext)
{
}
virtual void SAL_CALL readData( HandlerArg const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException);
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL instantiateSchemaParser( CreationContext const& xContext )
{
return * new SchemaParserService(xContext);
}
uno::Reference< uno::XInterface > SAL_CALL instantiateLayerParser( CreationContext const& xContext )
{
return * new LayerParserService(xContext);
}
// -----------------------------------------------------------------------------
const ServiceRegistrationInfo* getSchemaParserServiceInfo()
{ return getRegistrationInfo(& aSchemaParserSI); }
const ServiceRegistrationInfo* getLayerParserServiceInfo()
{ return getRegistrationInfo(& aLayerParserSI); }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
static OUString nullHandlerMessage(char const * where)
{
OSL_ASSERT(where);
OUString msg = OUString::createFromAscii(where);
return msg.concat(OUString::createFromAscii(": Error - NULL handler passed."));
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readSchema( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readSchema"),*this);
SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectAll);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readComponent( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readComponent"),*this);
SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectComponent);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readTemplates( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readTemplates"),*this);
SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectTemplates);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL LayerParserService::readData( uno::Reference< backenduno::XLayerHandler > const & aHandler )
throw (backenduno::MalformedDataException, lang::WrappedTargetException,
lang::NullPointerException, uno::RuntimeException)
{
if (!aHandler.is())
throw lang::NullPointerException(nullHandlerMessage("LayerParserService::readData"),*this);
SaxHandler xHandler = new LayerParser(this->getServiceFactory(),aHandler);
this->parse( xHandler );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<|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 "base/auto_reset.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_writer.h"
#include "base/path_service.h"
#include "base/safe_numerics.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/media_galleries/media_file_system_registry.h"
#include "chrome/browser/media_galleries/media_galleries_preferences.h"
#include "chrome/browser/media_galleries/media_galleries_test_util.h"
#include "chrome/browser/storage_monitor/storage_info.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/test/test_utils.h"
#if defined(OS_WIN) || defined(OS_MACOSX)
#include "chrome/browser/media_galleries/fileapi/picasa_finder.h"
#include "chrome/common/media_galleries/picasa_test_util.h"
#include "chrome/common/media_galleries/picasa_types.h"
#include "chrome/common/media_galleries/pmp_test_util.h"
#endif
using extensions::PlatformAppBrowserTest;
namespace {
// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
#if defined(FILE_PATH_USES_DRIVE_LETTERS)
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux");
#else
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
#endif
// This function is to ensure at least one (fake) media gallery exists for
// testing platforms with no default media galleries, such as CHROMEOS.
void MakeFakeMediaGalleryForTest(Profile* profile, const base::FilePath& path) {
MediaGalleriesPreferences* preferences =
g_browser_process->media_file_system_registry()->GetPreferences(profile);
base::RunLoop runloop;
preferences->EnsureInitialized(runloop.QuitClosure());
runloop.Run();
MediaGalleryPrefInfo gallery_info;
ASSERT_FALSE(preferences->LookUpGalleryByPath(path, &gallery_info));
preferences->AddGallery(gallery_info.device_id,
gallery_info.path,
false /* user_added */,
gallery_info.volume_label,
gallery_info.vendor_name,
gallery_info.model_name,
gallery_info.total_size_in_bytes,
gallery_info.last_attach_time);
content::RunAllPendingInMessageLoop();
}
} // namespace
class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest {
protected:
MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {}
virtual ~MediaGalleriesPlatformAppBrowserTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
PlatformAppBrowserTest::SetUpOnMainThread();
ensure_media_directories_exists_.reset(new EnsureMediaDirectoriesExists);
PopulatePicturesDirectoryTestData();
}
virtual void TearDownOnMainThread() OVERRIDE {
ensure_media_directories_exists_.reset();
PlatformAppBrowserTest::TearDownOnMainThread();
}
bool RunMediaGalleriesTest(const std::string& extension_name) {
base::ListValue empty_list_value;
return RunMediaGalleriesTestWithArg(extension_name, empty_list_value);
}
bool RunMediaGalleriesTestWithArg(const std::string& extension_name,
const base::ListValue& custom_arg_value) {
// Copy the test data for this test into a temporary directory. Then add
// a common_injected.js to the temporary copy and run it.
const char kTestDir[] = "api_test/media_galleries/";
base::FilePath from_dir =
test_data_dir_.AppendASCII(kTestDir + extension_name);
from_dir = from_dir.NormalizePathSeparators();
base::ScopedTempDir temp_dir;
if (!temp_dir.CreateUniqueTempDir())
return false;
if (!base::CopyDirectory(from_dir, temp_dir.path(), true))
return false;
base::FilePath common_js_path(
GetCommonDataDir().AppendASCII("common_injected.js"));
base::FilePath inject_js_path(
temp_dir.path().AppendASCII(extension_name)
.AppendASCII("common_injected.js"));
if (!base::CopyFile(common_js_path, inject_js_path))
return false;
const char* custom_arg = NULL;
std::string json_string;
if (!custom_arg_value.empty()) {
base::JSONWriter::Write(&custom_arg_value, &json_string);
custom_arg = json_string.c_str();
}
base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.path());
return RunPlatformAppTestWithArg(extension_name, custom_arg);
}
void AttachFakeDevice() {
device_id_ = StorageInfo::MakeDeviceId(
StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);
StorageMonitor::GetInstance()->receiver()->ProcessAttach(
StorageInfo(device_id_, base::string16(), kDevicePath,
ASCIIToUTF16(kDeviceName), base::string16(),
base::string16(), 0));
content::RunAllPendingInMessageLoop();
}
void DetachFakeDevice() {
StorageMonitor::GetInstance()->receiver()->ProcessDetach(device_id_);
content::RunAllPendingInMessageLoop();
}
void PopulatePicturesDirectoryTestData() {
if (ensure_media_directories_exists_->num_galleries() == 0)
return;
base::FilePath test_data_path(GetCommonDataDir());
base::FilePath write_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_USER_PICTURES, &write_path));
// Valid file, should show up in JS as a FileEntry.
ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.jpg"),
write_path.AppendASCII("test.jpg")));
// Invalid file, should not show up as a FileEntry in JS at all.
ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.txt"),
write_path.AppendASCII("test.txt")));
int64 file_size;
ASSERT_TRUE(file_util::GetFileSize(test_data_path.AppendASCII("test.jpg"),
&file_size));
test_jpg_size_ = base::checked_numeric_cast<int>(file_size);
}
#if defined(OS_WIN) || defined(OS_MACOSX)
void PopulatePicasaTestData(const base::FilePath& picasa_app_data_root) {
base::FilePath picasa_database_path =
picasa::MakePicasaDatabasePath(picasa_app_data_root);
base::FilePath picasa_temp_dir_path =
picasa_database_path.DirName().AppendASCII(picasa::kPicasaTempDirName);
ASSERT_TRUE(file_util::CreateDirectory(picasa_database_path));
ASSERT_TRUE(file_util::CreateDirectory(picasa_temp_dir_path));
// Create fake folder directories.
base::FilePath folders_root =
ensure_media_directories_exists_->GetFakePicasaFoldersRootPath();
base::FilePath fake_folder_1 = folders_root.AppendASCII("folder1");
base::FilePath fake_folder_2 = folders_root.AppendASCII("folder2");
ASSERT_TRUE(file_util::CreateDirectory(fake_folder_1));
ASSERT_TRUE(file_util::CreateDirectory(fake_folder_2));
// Write folder and album contents.
picasa::WriteTestAlbumTable(
picasa_database_path, fake_folder_1, fake_folder_2);
picasa::WriteTestAlbumsImagesIndex(fake_folder_1, fake_folder_2);
base::FilePath test_jpg_path = GetCommonDataDir().AppendASCII("test.jpg");
ASSERT_TRUE(base::CopyFile(
test_jpg_path, fake_folder_1.AppendASCII("InBoth.jpg")));
ASSERT_TRUE(base::CopyFile(
test_jpg_path, fake_folder_1.AppendASCII("InSecondAlbumOnly.jpg")));
ASSERT_TRUE(base::CopyFile(
test_jpg_path, fake_folder_2.AppendASCII("InFirstAlbumOnly.jpg")));
}
#endif
base::FilePath GetCommonDataDir() const {
return test_data_dir_.AppendASCII("api_test")
.AppendASCII("media_galleries")
.AppendASCII("common");
}
int num_galleries() const {
return ensure_media_directories_exists_->num_galleries();
}
int test_jpg_size() const { return test_jpg_size_; }
EnsureMediaDirectoriesExists* ensure_media_directories_exists() const {
return ensure_media_directories_exists_.get();
}
private:
std::string device_id_;
int test_jpg_size_;
scoped_ptr<EnsureMediaDirectoriesExists> ensure_media_directories_exists_;
};
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesNoAccess) {
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());
base::ListValue custom_args;
custom_args.AppendInteger(num_galleries() + 1);
ASSERT_TRUE(RunMediaGalleriesTestWithArg("no_access", custom_args))
<< message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, NoGalleriesRead) {
ASSERT_TRUE(RunMediaGalleriesTest("no_galleries")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
NoGalleriesCopyTo) {
ASSERT_TRUE(RunMediaGalleriesTest("no_galleries_copy_to")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesRead) {
base::ListValue custom_args;
custom_args.AppendInteger(num_galleries());
custom_args.AppendInteger(test_jpg_size());
ASSERT_TRUE(RunMediaGalleriesTestWithArg("read_access", custom_args))
<< message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesCopyTo) {
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());
ASSERT_TRUE(RunMediaGalleriesTest("copy_to_access")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesAccessAttached) {
AttachFakeDevice();
base::ListValue custom_args;
custom_args.AppendInteger(num_galleries() + 1);
custom_args.AppendString(kDeviceName);
ASSERT_TRUE(RunMediaGalleriesTestWithArg("access_attached", custom_args))
<< message_;
DetachFakeDevice();
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
GetFilesystemMetadata) {
ASSERT_TRUE(RunMediaGalleriesTest("metadata")) << message_;
}
#if defined(OS_WIN)|| defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
PicasaDefaultLocation) {
#if defined(OS_WIN)
PopulatePicasaTestData(
ensure_media_directories_exists()->GetFakeLocalAppDataPath());
#elif defined(OS_MACOSX)
PopulatePicasaTestData(
ensure_media_directories_exists()->GetFakeAppDataPath());
#endif
ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
PicasaCustomLocation) {
base::ScopedTempDir custom_picasa_app_data_root;
ASSERT_TRUE(custom_picasa_app_data_root.CreateUniqueTempDir());
ensure_media_directories_exists()->SetCustomPicasaAppDataPath(
custom_picasa_app_data_root.path());
PopulatePicasaTestData(custom_picasa_app_data_root.path());
ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}
#endif // defined(OS_WIN) || defined(OS_MACOSX)
<commit_msg>Disable MediaGalleriesPlatformAppBrowserTest.MediaGalleriesCopyTo for being flaky.<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 "base/auto_reset.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_writer.h"
#include "base/path_service.h"
#include "base/safe_numerics.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/media_galleries/media_file_system_registry.h"
#include "chrome/browser/media_galleries/media_galleries_preferences.h"
#include "chrome/browser/media_galleries/media_galleries_test_util.h"
#include "chrome/browser/storage_monitor/storage_info.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/test/test_utils.h"
#if defined(OS_WIN) || defined(OS_MACOSX)
#include "chrome/browser/media_galleries/fileapi/picasa_finder.h"
#include "chrome/common/media_galleries/picasa_test_util.h"
#include "chrome/common/media_galleries/picasa_types.h"
#include "chrome/common/media_galleries/pmp_test_util.h"
#endif
using extensions::PlatformAppBrowserTest;
namespace {
// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
#if defined(FILE_PATH_USES_DRIVE_LETTERS)
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux");
#else
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
#endif
// This function is to ensure at least one (fake) media gallery exists for
// testing platforms with no default media galleries, such as CHROMEOS.
void MakeFakeMediaGalleryForTest(Profile* profile, const base::FilePath& path) {
MediaGalleriesPreferences* preferences =
g_browser_process->media_file_system_registry()->GetPreferences(profile);
base::RunLoop runloop;
preferences->EnsureInitialized(runloop.QuitClosure());
runloop.Run();
MediaGalleryPrefInfo gallery_info;
ASSERT_FALSE(preferences->LookUpGalleryByPath(path, &gallery_info));
preferences->AddGallery(gallery_info.device_id,
gallery_info.path,
false /* user_added */,
gallery_info.volume_label,
gallery_info.vendor_name,
gallery_info.model_name,
gallery_info.total_size_in_bytes,
gallery_info.last_attach_time);
content::RunAllPendingInMessageLoop();
}
} // namespace
class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest {
protected:
MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {}
virtual ~MediaGalleriesPlatformAppBrowserTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
PlatformAppBrowserTest::SetUpOnMainThread();
ensure_media_directories_exists_.reset(new EnsureMediaDirectoriesExists);
PopulatePicturesDirectoryTestData();
}
virtual void TearDownOnMainThread() OVERRIDE {
ensure_media_directories_exists_.reset();
PlatformAppBrowserTest::TearDownOnMainThread();
}
bool RunMediaGalleriesTest(const std::string& extension_name) {
base::ListValue empty_list_value;
return RunMediaGalleriesTestWithArg(extension_name, empty_list_value);
}
bool RunMediaGalleriesTestWithArg(const std::string& extension_name,
const base::ListValue& custom_arg_value) {
// Copy the test data for this test into a temporary directory. Then add
// a common_injected.js to the temporary copy and run it.
const char kTestDir[] = "api_test/media_galleries/";
base::FilePath from_dir =
test_data_dir_.AppendASCII(kTestDir + extension_name);
from_dir = from_dir.NormalizePathSeparators();
base::ScopedTempDir temp_dir;
if (!temp_dir.CreateUniqueTempDir())
return false;
if (!base::CopyDirectory(from_dir, temp_dir.path(), true))
return false;
base::FilePath common_js_path(
GetCommonDataDir().AppendASCII("common_injected.js"));
base::FilePath inject_js_path(
temp_dir.path().AppendASCII(extension_name)
.AppendASCII("common_injected.js"));
if (!base::CopyFile(common_js_path, inject_js_path))
return false;
const char* custom_arg = NULL;
std::string json_string;
if (!custom_arg_value.empty()) {
base::JSONWriter::Write(&custom_arg_value, &json_string);
custom_arg = json_string.c_str();
}
base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.path());
return RunPlatformAppTestWithArg(extension_name, custom_arg);
}
void AttachFakeDevice() {
device_id_ = StorageInfo::MakeDeviceId(
StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);
StorageMonitor::GetInstance()->receiver()->ProcessAttach(
StorageInfo(device_id_, base::string16(), kDevicePath,
ASCIIToUTF16(kDeviceName), base::string16(),
base::string16(), 0));
content::RunAllPendingInMessageLoop();
}
void DetachFakeDevice() {
StorageMonitor::GetInstance()->receiver()->ProcessDetach(device_id_);
content::RunAllPendingInMessageLoop();
}
void PopulatePicturesDirectoryTestData() {
if (ensure_media_directories_exists_->num_galleries() == 0)
return;
base::FilePath test_data_path(GetCommonDataDir());
base::FilePath write_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_USER_PICTURES, &write_path));
// Valid file, should show up in JS as a FileEntry.
ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.jpg"),
write_path.AppendASCII("test.jpg")));
// Invalid file, should not show up as a FileEntry in JS at all.
ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.txt"),
write_path.AppendASCII("test.txt")));
int64 file_size;
ASSERT_TRUE(file_util::GetFileSize(test_data_path.AppendASCII("test.jpg"),
&file_size));
test_jpg_size_ = base::checked_numeric_cast<int>(file_size);
}
#if defined(OS_WIN) || defined(OS_MACOSX)
void PopulatePicasaTestData(const base::FilePath& picasa_app_data_root) {
base::FilePath picasa_database_path =
picasa::MakePicasaDatabasePath(picasa_app_data_root);
base::FilePath picasa_temp_dir_path =
picasa_database_path.DirName().AppendASCII(picasa::kPicasaTempDirName);
ASSERT_TRUE(file_util::CreateDirectory(picasa_database_path));
ASSERT_TRUE(file_util::CreateDirectory(picasa_temp_dir_path));
// Create fake folder directories.
base::FilePath folders_root =
ensure_media_directories_exists_->GetFakePicasaFoldersRootPath();
base::FilePath fake_folder_1 = folders_root.AppendASCII("folder1");
base::FilePath fake_folder_2 = folders_root.AppendASCII("folder2");
ASSERT_TRUE(file_util::CreateDirectory(fake_folder_1));
ASSERT_TRUE(file_util::CreateDirectory(fake_folder_2));
// Write folder and album contents.
picasa::WriteTestAlbumTable(
picasa_database_path, fake_folder_1, fake_folder_2);
picasa::WriteTestAlbumsImagesIndex(fake_folder_1, fake_folder_2);
base::FilePath test_jpg_path = GetCommonDataDir().AppendASCII("test.jpg");
ASSERT_TRUE(base::CopyFile(
test_jpg_path, fake_folder_1.AppendASCII("InBoth.jpg")));
ASSERT_TRUE(base::CopyFile(
test_jpg_path, fake_folder_1.AppendASCII("InSecondAlbumOnly.jpg")));
ASSERT_TRUE(base::CopyFile(
test_jpg_path, fake_folder_2.AppendASCII("InFirstAlbumOnly.jpg")));
}
#endif
base::FilePath GetCommonDataDir() const {
return test_data_dir_.AppendASCII("api_test")
.AppendASCII("media_galleries")
.AppendASCII("common");
}
int num_galleries() const {
return ensure_media_directories_exists_->num_galleries();
}
int test_jpg_size() const { return test_jpg_size_; }
EnsureMediaDirectoriesExists* ensure_media_directories_exists() const {
return ensure_media_directories_exists_.get();
}
private:
std::string device_id_;
int test_jpg_size_;
scoped_ptr<EnsureMediaDirectoriesExists> ensure_media_directories_exists_;
};
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesNoAccess) {
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());
base::ListValue custom_args;
custom_args.AppendInteger(num_galleries() + 1);
ASSERT_TRUE(RunMediaGalleriesTestWithArg("no_access", custom_args))
<< message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, NoGalleriesRead) {
ASSERT_TRUE(RunMediaGalleriesTest("no_galleries")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
NoGalleriesCopyTo) {
ASSERT_TRUE(RunMediaGalleriesTest("no_galleries_copy_to")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesRead) {
base::ListValue custom_args;
custom_args.AppendInteger(num_galleries());
custom_args.AppendInteger(test_jpg_size());
ASSERT_TRUE(RunMediaGalleriesTestWithArg("read_access", custom_args))
<< message_;
}
// Flaky: crbug.com/314576
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
DISABLED_MediaGalleriesCopyTo) {
#else
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesCopyTo) {
#endif
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());
ASSERT_TRUE(RunMediaGalleriesTest("copy_to_access")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
MediaGalleriesAccessAttached) {
AttachFakeDevice();
base::ListValue custom_args;
custom_args.AppendInteger(num_galleries() + 1);
custom_args.AppendString(kDeviceName);
ASSERT_TRUE(RunMediaGalleriesTestWithArg("access_attached", custom_args))
<< message_;
DetachFakeDevice();
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
GetFilesystemMetadata) {
ASSERT_TRUE(RunMediaGalleriesTest("metadata")) << message_;
}
#if defined(OS_WIN)|| defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
PicasaDefaultLocation) {
#if defined(OS_WIN)
PopulatePicasaTestData(
ensure_media_directories_exists()->GetFakeLocalAppDataPath());
#elif defined(OS_MACOSX)
PopulatePicasaTestData(
ensure_media_directories_exists()->GetFakeAppDataPath());
#endif
ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
PicasaCustomLocation) {
base::ScopedTempDir custom_picasa_app_data_root;
ASSERT_TRUE(custom_picasa_app_data_root.CreateUniqueTempDir());
ensure_media_directories_exists()->SetCustomPicasaAppDataPath(
custom_picasa_app_data_root.path());
PopulatePicasaTestData(custom_picasa_app_data_root.path());
ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}
#endif // defined(OS_WIN) || defined(OS_MACOSX)
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------//
// █ █ //
// ████████ //
// ██ ██ //
// ███ █ █ ███ CCBNode_Loader_PropertySetters.cpp //
// █ █ █ █ MonsterFramework //
// ████████████ //
// █ █ Copyright (c) 2015 AmazingCow //
// █ █ █ █ www.AmazingCow.com //
// █ █ █ █ //
// █ █ N2OMatt - [email protected] //
// ████████████ www.amazingcow.com/n2omatt //
// //
// //
// This software is licensed as BSD-3 //
// CHECK THE COPYING FILE TO MORE DETAILS //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 0. You **CANNOT** change the type of the license. //
// 1. The origin of this software must not be misrepresented; //
// you must not claim that you wrote the original software. //
// 2. If you use this software in a product, an acknowledgment in the //
// product IS HIGHLY APPRECIATED, both in source and binary forms. //
// (See opensource.AmazingCow.com/acknowledgment.html for details). //
// If you will not acknowledge, just send us a email. We'll be //
// *VERY* happy to see our work being used by other people. :) //
// The email is: [email protected] //
// 3. Altered source versions must be plainly marked as such, //
// and must notbe misrepresented as being the original software. //
// 4. This notice may not be removed or altered from any source //
// distribution. //
// 5. Most important, you must have fun. ;) //
// //
// Visit opensource.amazingcow.com for more open-source projects. //
// //
// Enjoy :) //
//----------------------------------------------------------------------------//
#include "CCBNodeLoader_PropertySetters.h"
#include "CCBNodeLoader_Decoders.h"
#include <typeinfo>
USING_NS_STD_CC_CD_MF
// Anchor Point //
void mf::_set_anchorPoint(cc::Node *obj, const cc::Value &value)
{
obj->setAnchorPoint(_decodeAsPoint(value));
}
void mf::_set_ignoreAnchorPointForPosition(cc::Node *obj, const cc::Value &value)
{
obj->ignoreAnchorPointForPosition(_decodeAsCheck(value));
}
// Transforms //
void mf::_set_position(cc::Node *obj, const cc::Value &value)
{
obj->setPosition(_decodeAsPosition(value, obj->getParent()));
}
void mf::_set_scale(cc::Node *obj, const cc::Value &value)
{
//EMSG: We're decided treat scale as a stand alone
//property. So it's not depends of anything else.
auto point = _decodeAsPoint(value);
obj->setScale(point.x, point.y);
}
void mf::_set_rotation(cc::Node *obj, const cc::Value &value)
{
obj->setRotation(_decodeAsDegrees(value));
}
// ???
void mf::_set_isEnabled(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::MenuItem *>(obj)->setEnabled(_decodeAsCheck(value));
}
void mf::_set_contentSize(cc::Node *obj, const cc::Value &value)
{
obj->setContentSize(_decodeAsSize(value));
}
// Color / Opacity //
void mf::_set_color(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::LayerColor *>(obj)->setColor(_decodeAsColor3(value));
}
void mf::_set_opacity(cc::Node *obj, const cc::Value &value)
{
obj->setOpacity(_decodeAsByte(value));
}
// Input //
void mf::_set_isTouchEnabled(cc::Node *obj, const cc::Value &value)
{
//COWTODO:: Ignoring by now, but must check what this method will do.
}
void mf::_set_isAccelerometerEnabled(cc::Node *obj, const cc::Value &value)
{
//COWTODO:: Ignoring by now, but must check what this method will do.
}
// Frame //
void mf::_set_displayFrame(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Sprite *>(obj)->setSpriteFrame(_decodeAsSpriteFrame(value));
}
// Button //
void mf::_set_normalSpriteFrame(cc::Node *obj, const cc::Value &value)
{
//COWTODO: Refactor and comment.
if(typeid(*obj) == typeid(cc::MenuItemToggle))
{
auto toggle = static_cast<cc::MenuItemToggle *>(obj);
cc::Sprite *sprite1 = cc::Sprite::create();
cc::Sprite *sprite2 = cc::Sprite::create();
mf::_set_displayFrame(sprite1, value);
mf::_set_displayFrame(sprite2, value);
auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);
toggle->addSubItem(menuItem);
toggle->setSelectedIndex(0);
}
else
{
cc::Sprite *sprite = cc::Sprite::create();
mf::_set_displayFrame(sprite, value);
static_cast<cc::MenuItemSprite *>(obj)->setNormalImage(sprite);
}
}
void mf::_set_selectedSpriteFrame(cc::Node *obj, const cc::Value &value)
{
//COWTODO: Refactor and comment.
if(typeid(*obj) == typeid(cc::MenuItemToggle))
{
auto toggle = static_cast<cc::MenuItemToggle *>(obj);
cc::Sprite *sprite1 = cc::Sprite::create();
cc::Sprite *sprite2 = cc::Sprite::create();
mf::_set_displayFrame(sprite1, value);
mf::_set_displayFrame(sprite2, value);
auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);
toggle->addSubItem(menuItem);
}
else
{
cc::Sprite *sprite = cc::Sprite::create();
mf::_set_displayFrame(sprite, value);
static_cast<cc::MenuItemSprite *>(obj)->setSelectedImage(sprite);
}
}
void mf::_set_disabledSpriteFrame(cc::Node *obj, const cc::Value &value)
{
//Implement MFToggle support.
//There's no information to set the sprite, this is due
//the CocosBuild set the disabledSpriteFrame in plist even
//if the user doesn't set any of them...
if(_decodeAsSpriteFrame(value) == "")
return;
cc::Sprite *sprite = cc::Sprite::create();
mf::_set_displayFrame(sprite, value);
static_cast<cc::MenuItemSprite *>(obj)->setDisabledImage(sprite);
}
void mf::_set_block(cc::Node *obj, const cc::Value &value,
ILoadResolver *pResolver)
{
pResolver->resolveMenuSelector(_decodeAsBlock(value),
static_cast<cc::MenuItem *>(obj));
}
// Font //
void mf::_set_fontName(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Label *>(obj)->setSystemFontName(value.asString());
}
void mf::_set_fontSize(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Label *>(obj)->setSystemFontSize(_decodeAsFontScale(value));
}
void mf::_set_string(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Label *>(obj)->setString(_decodeAsString(value));
}
<commit_msg>Add some COWTODOs.<commit_after>//----------------------------------------------------------------------------//
// █ █ //
// ████████ //
// ██ ██ //
// ███ █ █ ███ CCBNode_Loader_PropertySetters.cpp //
// █ █ █ █ MonsterFramework //
// ████████████ //
// █ █ Copyright (c) 2015 AmazingCow //
// █ █ █ █ www.AmazingCow.com //
// █ █ █ █ //
// █ █ N2OMatt - [email protected] //
// ████████████ www.amazingcow.com/n2omatt //
// //
// //
// This software is licensed as BSD-3 //
// CHECK THE COPYING FILE TO MORE DETAILS //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 0. You **CANNOT** change the type of the license. //
// 1. The origin of this software must not be misrepresented; //
// you must not claim that you wrote the original software. //
// 2. If you use this software in a product, an acknowledgment in the //
// product IS HIGHLY APPRECIATED, both in source and binary forms. //
// (See opensource.AmazingCow.com/acknowledgment.html for details). //
// If you will not acknowledge, just send us a email. We'll be //
// *VERY* happy to see our work being used by other people. :) //
// The email is: [email protected] //
// 3. Altered source versions must be plainly marked as such, //
// and must notbe misrepresented as being the original software. //
// 4. This notice may not be removed or altered from any source //
// distribution. //
// 5. Most important, you must have fun. ;) //
// //
// Visit opensource.amazingcow.com for more open-source projects. //
// //
// Enjoy :) //
//----------------------------------------------------------------------------//
#include "CCBNodeLoader_PropertySetters.h"
#include "CCBNodeLoader_Decoders.h"
#include <typeinfo>
USING_NS_STD_CC_CD_MF
// Anchor Point //
void mf::_set_anchorPoint(cc::Node *obj, const cc::Value &value)
{
obj->setAnchorPoint(_decodeAsPoint(value));
}
void mf::_set_ignoreAnchorPointForPosition(cc::Node *obj, const cc::Value &value)
{
obj->ignoreAnchorPointForPosition(_decodeAsCheck(value));
}
// Transforms //
void mf::_set_position(cc::Node *obj, const cc::Value &value)
{
obj->setPosition(_decodeAsPosition(value, obj->getParent()));
}
void mf::_set_scale(cc::Node *obj, const cc::Value &value)
{
//EMSG: We're decided treat scale as a stand alone
//property. So it's not depends of anything else.
auto point = _decodeAsPoint(value);
obj->setScale(point.x, point.y);
}
void mf::_set_rotation(cc::Node *obj, const cc::Value &value)
{
obj->setRotation(_decodeAsDegrees(value));
}
// ???
void mf::_set_isEnabled(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::MenuItem *>(obj)->setEnabled(_decodeAsCheck(value));
}
void mf::_set_contentSize(cc::Node *obj, const cc::Value &value)
{
obj->setContentSize(_decodeAsSize(value));
}
// Color / Opacity //
void mf::_set_color(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::LayerColor *>(obj)->setColor(_decodeAsColor3(value));
}
void mf::_set_opacity(cc::Node *obj, const cc::Value &value)
{
obj->setOpacity(_decodeAsByte(value));
}
// Input //
void mf::_set_isTouchEnabled(cc::Node *obj, const cc::Value &value)
{
//COWTODO:: Ignoring by now, but must check what this method will do.
}
void mf::_set_isAccelerometerEnabled(cc::Node *obj, const cc::Value &value)
{
//COWTODO:: Ignoring by now, but must check what this method will do.
}
// Frame //
void mf::_set_displayFrame(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Sprite *>(obj)->setSpriteFrame(_decodeAsSpriteFrame(value));
}
// Button //
void mf::_set_normalSpriteFrame(cc::Node *obj, const cc::Value &value)
{
//COWTODO: Refactor and comment.
if(typeid(*obj) == typeid(cc::MenuItemToggle))
{
auto toggle = static_cast<cc::MenuItemToggle *>(obj);
cc::Sprite *sprite1 = cc::Sprite::create();
cc::Sprite *sprite2 = cc::Sprite::create();
mf::_set_displayFrame(sprite1, value);
mf::_set_displayFrame(sprite2, value);
auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);
toggle->addSubItem(menuItem);
toggle->setSelectedIndex(0);
}
else
{
cc::Sprite *sprite = cc::Sprite::create();
mf::_set_displayFrame(sprite, value);
static_cast<cc::MenuItemSprite *>(obj)->setNormalImage(sprite);
}
}
void mf::_set_selectedSpriteFrame(cc::Node *obj, const cc::Value &value)
{
//COWTODO: Refactor and comment.
if(typeid(*obj) == typeid(cc::MenuItemToggle))
{
auto toggle = static_cast<cc::MenuItemToggle *>(obj);
cc::Sprite *sprite1 = cc::Sprite::create();
cc::Sprite *sprite2 = cc::Sprite::create();
mf::_set_displayFrame(sprite1, value);
mf::_set_displayFrame(sprite2, value);
auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);
toggle->addSubItem(menuItem);
}
else
{
cc::Sprite *sprite = cc::Sprite::create();
mf::_set_displayFrame(sprite, value);
static_cast<cc::MenuItemSprite *>(obj)->setSelectedImage(sprite);
}
}
void mf::_set_disabledSpriteFrame(cc::Node *obj, const cc::Value &value)
{
//COWTODO: Implement MFToggle support.
//There's no information to set the sprite, this is due
//the CocosBuild set the disabledSpriteFrame in plist even
//if the user doesn't set any of them...
if(_decodeAsSpriteFrame(value) == "")
return;
cc::Sprite *sprite = cc::Sprite::create();
mf::_set_displayFrame(sprite, value);
static_cast<cc::MenuItemSprite *>(obj)->setDisabledImage(sprite);
}
void mf::_set_block(cc::Node *obj, const cc::Value &value,
ILoadResolver *pResolver)
{
pResolver->resolveMenuSelector(_decodeAsBlock(value),
static_cast<cc::MenuItem *>(obj));
}
// Font //
void mf::_set_fontName(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Label *>(obj)->setSystemFontName(value.asString());
}
void mf::_set_fontSize(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Label *>(obj)->setSystemFontSize(_decodeAsFontScale(value));
}
void mf::_set_string(cc::Node *obj, const cc::Value &value)
{
static_cast<cc::Label *>(obj)->setString(_decodeAsString(value));
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"
#include "IECore/Renderer.h"
#include "IECore/CompoundObject.h"
#include "IECore/CompoundParameter.h"
#include "IECore/MessageHandler.h"
#include "IECore/ParameterisedProcedural.h"
#include "IECore/bindings/ParameterisedProceduralBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/Wrapper.h"
using namespace boost::python;
namespace IECore
{
class ParameterisedProceduralWrap : public ParameterisedProcedural, public Wrapper<ParameterisedProcedural>
{
public :
ParameterisedProceduralWrap( PyObject *self )
: Wrapper<ParameterisedProcedural>( self, this )
{
}
virtual void doRenderState( RendererPtr renderer, ConstCompoundObjectPtr args ) const
{
try
{
override o = this->get_override( "doRenderState" );
if( o )
{
o( renderer, boost::const_pointer_cast<CompoundObject>( args ) );
}
else
{
ParameterisedProcedural::doRenderState( renderer, args );
}
}
catch( error_already_set )
{
PyErr_Print();
}
catch( const std::exception &e )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", "Caught unknown exception" );
}
}
virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const
{
try
{
override o = this->get_override( "doBound" );
if( o )
{
return o( boost::const_pointer_cast<CompoundObject>( args ) );
}
else
{
msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "doBound() python method not defined" );
}
}
catch( error_already_set )
{
PyErr_Print();
}
catch( const std::exception &e )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doBound", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "Caught unknown exception" );
}
return Imath::Box3f(); // empty
}
virtual void doRender( RendererPtr r, ConstCompoundObjectPtr args ) const
{
// ideally we might not do any exception handling here, and always leave it to the host.
// but in our case the host is mainly 3delight and that does no exception handling at all.
try
{
override o = this->get_override( "doRender" );
if( o )
{
o( r, boost::const_pointer_cast<CompoundObject>( args ) );
}
else
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "doRender() python method not defined" );
}
}
catch( error_already_set )
{
PyErr_Print();
}
catch( const std::exception &e )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRender", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "Caught unknown exception" );
}
}
};
IE_CORE_DECLAREPTR( ParameterisedProceduralWrap );
static ParameterPtr parameterisedProceduralGetItem( ParameterisedProcedural &o, const std::string &n )
{
ParameterPtr p = o.parameters()->parameter<Parameter>( n );
if( !p )
{
throw Exception( std::string("Parameter ") + n + " doesn't exist" );
}
return p;
}
void bindParameterisedProcedural()
{
RunTimeTypedClass<ParameterisedProcedural, ParameterisedProceduralWrapPtr>()
.def( init<>() )
.def( "parameters", (CompoundParameterPtr (ParameterisedProcedural::*)())&ParameterisedProcedural::parameters )
.def( "render", (void (ParameterisedProcedural::*)( RendererPtr ) const )&ParameterisedProcedural::render )
.def( "render", (void (ParameterisedProcedural::*)( RendererPtr, bool, bool, bool, bool ) const )&ParameterisedProcedural::render, ( arg( "renderer" ), arg( "inAttributeBlock" ) = true, arg( "withState" ) = true, arg( "withGeometry" ) = true, arg( "immediateGeometry" ) = false ) )
.def( "__getitem__", ¶meterisedProceduralGetItem )
;
}
} // namespace IECore
<commit_msg>Fixed failing test<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"
#include "IECore/Renderer.h"
#include "IECore/CompoundObject.h"
#include "IECore/CompoundParameter.h"
#include "IECore/MessageHandler.h"
#include "IECore/ParameterisedProcedural.h"
#include "IECore/bindings/ParameterisedProceduralBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/Wrapper.h"
using namespace boost::python;
namespace IECore
{
class ParameterisedProceduralWrap : public ParameterisedProcedural, public Wrapper<ParameterisedProcedural>
{
public :
ParameterisedProceduralWrap( PyObject *self )
: Wrapper<ParameterisedProcedural>( self, this )
{
}
virtual void doRenderState( RendererPtr renderer, ConstCompoundObjectPtr args ) const
{
try
{
override o = this->get_override( "doRenderState" );
if( o )
{
o( renderer, boost::const_pointer_cast<CompoundObject>( args ) );
}
else
{
ParameterisedProcedural::doRenderState( renderer, args );
}
}
catch( error_already_set )
{
PyErr_Print();
}
catch( const std::exception &e )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", "Caught unknown exception" );
}
}
virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const
{
try
{
override o = this->get_override( "doBound" );
if( o )
{
return o( boost::const_pointer_cast<CompoundObject>( args ) );
}
else
{
msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "doBound() python method not defined" );
}
}
catch( error_already_set )
{
PyErr_Print();
}
catch( const std::exception &e )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doBound", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "Caught unknown exception" );
}
return Imath::Box3f(); // empty
}
virtual void doRender( RendererPtr r, ConstCompoundObjectPtr args ) const
{
// ideally we might not do any exception handling here, and always leave it to the host.
// but in our case the host is mainly 3delight and that does no exception handling at all.
try
{
override o = this->get_override( "doRender" );
if( o )
{
o( r, boost::const_pointer_cast<CompoundObject>( args ) );
}
else
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "doRender() python method not defined" );
}
}
catch( error_already_set )
{
PyErr_Print();
}
catch( const std::exception &e )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRender", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "Caught unknown exception" );
}
}
IE_COREPYTHON_RUNTIMETYPEDWRAPPERFNS( ParameterisedProcedural );
};
IE_CORE_DECLAREPTR( ParameterisedProceduralWrap );
static ParameterPtr parameterisedProceduralGetItem( ParameterisedProcedural &o, const std::string &n )
{
ParameterPtr p = o.parameters()->parameter<Parameter>( n );
if( !p )
{
throw Exception( std::string("Parameter ") + n + " doesn't exist" );
}
return p;
}
void bindParameterisedProcedural()
{
RunTimeTypedClass<ParameterisedProcedural, ParameterisedProceduralWrapPtr>()
.def( init<>() )
.def( "parameters", (CompoundParameterPtr (ParameterisedProcedural::*)())&ParameterisedProcedural::parameters )
.def( "render", (void (ParameterisedProcedural::*)( RendererPtr ) const )&ParameterisedProcedural::render )
.def( "render", (void (ParameterisedProcedural::*)( RendererPtr, bool, bool, bool, bool ) const )&ParameterisedProcedural::render, ( arg( "renderer" ), arg( "inAttributeBlock" ) = true, arg( "withState" ) = true, arg( "withGeometry" ) = true, arg( "immediateGeometry" ) = false ) )
.def( "__getitem__", ¶meterisedProceduralGetItem )
;
}
} // namespace IECore
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "../huffman/huffman_tree.hpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace unit_test_for_huffman
{
using FrequencyMap = cpr::huffman::FrequencyMap < unsigned char, unsigned long > ;
using HuffmanTree = cpr::huffman::HuffmanTree < unsigned char, unsigned long > ;
TEST_CLASS(unit_test_for_huffman_tree)
{
public:
TEST_METHOD(ctor)
{
std::vector<unsigned char> test_case{ 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c' };
FrequencyMap fmap(test_case);
HuffmanTree htree{ fmap };
}
};
}<commit_msg>tested ctor for huffman_tree, but more test cases needed.<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "../huffman/huffman_tree.hpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace unit_test_for_huffman
{
using FrequencyMap = cpr::huffman::FrequencyMap < unsigned char, unsigned long > ;
using HuffmanTree = cpr::huffman::HuffmanTree < unsigned char, unsigned long > ;
TEST_CLASS(unit_test_for_huffman_tree)
{
public:
TEST_METHOD(ctor)
{
//case 1 made up on my own
std::vector<unsigned char> test_case{ 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c' };
FrequencyMap fmap(test_case);
HuffmanTree htree{ fmap };
Assert::IsNotNull(htree.root().get());
//case 2 based on 16.3 clrs
auto empty_case = std::vector<unsigned char>();
FrequencyMap fmap_from_clrs(empty_case);
fmap_from_clrs['a'] = 45;
fmap_from_clrs['b'] = 13;
fmap_from_clrs['c'] = 12;
fmap_from_clrs['d'] = 16;
fmap_from_clrs['e'] = 9;
fmap_from_clrs['f'] = 5;
HuffmanTree htree_from_clrs{ fmap_from_clrs };
Assert::AreEqual(100ul, htree_from_clrs.root()->freq_);
Assert::AreEqual((unsigned char)0, htree_from_clrs.root()->character_);
Assert::AreEqual((unsigned char)'a', htree_from_clrs.root()->left_->character_);
// more test needed , but for now clrs is unavailable
}
};
}<|endoftext|> |
<commit_before><commit_msg>Transform: Remove unused std header.<commit_after><|endoftext|> |
<commit_before>// $Id: ThreadPool.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2009 University of Edinburgh
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 <stdio.h>
#ifdef __linux
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <thread>
#include "ThreadPool.h"
using namespace std;
namespace Moses2
{
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
ThreadPool::ThreadPool(size_t numThreads, int cpuAffinityOffset,
int cpuAffinityIncr) :
m_stopped(false), m_stopping(false), m_queueLimit(0)
{
//size_t numCPU = sysconf(_SC_NPROCESSORS_ONLN);
size_t numCPU = std::thread::hardware_concurrency();
int cpuInd = cpuAffinityOffset % numCPU;
for (size_t i = 0; i < numThreads; ++i) {
boost::thread *thread = m_threads.create_thread(
boost::bind(&ThreadPool::Execute, this));
#ifdef __linux
if (cpuAffinityOffset >= 0) {
int s;
boost::thread::native_handle_type handle = thread->native_handle();
//cerr << "numCPU=" << numCPU << endl;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpuInd, &cpuset);
cpuInd += cpuAffinityIncr;
cpuInd = cpuInd % numCPU;
s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
if (s != 0) {
handle_error_en(s, "pthread_setaffinity_np");
//cerr << "affinity error with thread " << i << endl;
}
// get affinity
CPU_ZERO(&cpuset);
s = pthread_getaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
cerr << "Set returned by pthread_getaffinity_np() contained:\n";
for (int j = 0; j < CPU_SETSIZE; j++) {
if (CPU_ISSET(j, &cpuset)) {
cerr << " CPU " << j << "\n";
}
}
}
#endif
}
}
void ThreadPool::Execute()
{
do {
boost::shared_ptr<Task> task;
{
// Find a job to perform
boost::mutex::scoped_lock lock(m_mutex);
if (m_tasks.empty() && !m_stopped) {
m_threadNeeded.wait(lock);
}
if (!m_stopped && !m_tasks.empty()) {
task = m_tasks.front();
m_tasks.pop();
}
}
//Execute job
if (task) {
// must read from task before run. otherwise task may be deleted by main thread
// race condition
task->DeleteAfterExecution();
task->Run();
}
m_threadAvailable.notify_all();
} while (!m_stopped);
}
void ThreadPool::Submit(boost::shared_ptr<Task> task)
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_stopping) {
throw runtime_error("ThreadPool stopping - unable to accept new jobs");
}
while (m_queueLimit > 0 && m_tasks.size() >= m_queueLimit) {
m_threadAvailable.wait(lock);
}
m_tasks.push(task);
m_threadNeeded.notify_all();
}
void ThreadPool::Stop(bool processRemainingJobs)
{
{
//prevent more jobs from being added to the queue
boost::mutex::scoped_lock lock(m_mutex);
if (m_stopped) return;
m_stopping = true;
}
if (processRemainingJobs) {
boost::mutex::scoped_lock lock(m_mutex);
//wait for queue to drain.
while (!m_tasks.empty() && !m_stopped) {
m_threadAvailable.wait(lock);
}
}
//tell all threads to stop
{
boost::mutex::scoped_lock lock(m_mutex);
m_stopped = true;
}
m_threadNeeded.notify_all();
m_threads.join_all();
}
}
<commit_msg>go back to using sysconf() for linux/osx. Runs ok on new systems but not thor. std::thread::hardware_concurrency() returns 0 on thor<commit_after>// $Id: ThreadPool.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2009 University of Edinburgh
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 <stdio.h>
#ifdef __linux
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <thread>
#include "ThreadPool.h"
using namespace std;
namespace Moses2
{
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
ThreadPool::ThreadPool(size_t numThreads, int cpuAffinityOffset,
int cpuAffinityIncr) :
m_stopped(false), m_stopping(false), m_queueLimit(0)
{
#if defined(_WIN32) || defined(_WIN64)
size_t numCPU = std::thread::hardware_concurrency();
#else
size_t numCPU = sysconf(_SC_NPROCESSORS_ONLN);
#endif
//cerr << "numCPU=" << numCPU << endl;
int cpuInd = cpuAffinityOffset % numCPU;
for (size_t i = 0; i < numThreads; ++i) {
boost::thread *thread = m_threads.create_thread(
boost::bind(&ThreadPool::Execute, this));
#ifdef __linux
if (cpuAffinityOffset >= 0) {
int s;
boost::thread::native_handle_type handle = thread->native_handle();
//cerr << "numCPU=" << numCPU << endl;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpuInd, &cpuset);
cpuInd += cpuAffinityIncr;
cpuInd = cpuInd % numCPU;
s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
if (s != 0) {
handle_error_en(s, "pthread_setaffinity_np");
//cerr << "affinity error with thread " << i << endl;
}
// get affinity
CPU_ZERO(&cpuset);
s = pthread_getaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
cerr << "Set returned by pthread_getaffinity_np() contained:\n";
for (int j = 0; j < CPU_SETSIZE; j++) {
if (CPU_ISSET(j, &cpuset)) {
cerr << " CPU " << j << "\n";
}
}
}
#endif
}
}
void ThreadPool::Execute()
{
do {
boost::shared_ptr<Task> task;
{
// Find a job to perform
boost::mutex::scoped_lock lock(m_mutex);
if (m_tasks.empty() && !m_stopped) {
m_threadNeeded.wait(lock);
}
if (!m_stopped && !m_tasks.empty()) {
task = m_tasks.front();
m_tasks.pop();
}
}
//Execute job
if (task) {
// must read from task before run. otherwise task may be deleted by main thread
// race condition
task->DeleteAfterExecution();
task->Run();
}
m_threadAvailable.notify_all();
} while (!m_stopped);
}
void ThreadPool::Submit(boost::shared_ptr<Task> task)
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_stopping) {
throw runtime_error("ThreadPool stopping - unable to accept new jobs");
}
while (m_queueLimit > 0 && m_tasks.size() >= m_queueLimit) {
m_threadAvailable.wait(lock);
}
m_tasks.push(task);
m_threadNeeded.notify_all();
}
void ThreadPool::Stop(bool processRemainingJobs)
{
{
//prevent more jobs from being added to the queue
boost::mutex::scoped_lock lock(m_mutex);
if (m_stopped) return;
m_stopping = true;
}
if (processRemainingJobs) {
boost::mutex::scoped_lock lock(m_mutex);
//wait for queue to drain.
while (!m_tasks.empty() && !m_stopped) {
m_threadAvailable.wait(lock);
}
}
//tell all threads to stop
{
boost::mutex::scoped_lock lock(m_mutex);
m_stopped = true;
}
m_threadNeeded.notify_all();
m_threads.join_all();
}
}
<|endoftext|> |
<commit_before><commit_msg>vcl: cosmetic reident and cleanup of RawBitmap class definition<commit_after><|endoftext|> |
<commit_before>#include "stdafx.h"
#include "../NWindow.h"
namespace nui
{
namespace Ui
{
NWindow::NWindow()
{
}
NWindow::~NWindow()
{
}
NFrame* NWindow::GetRootFrame()
{
if(rootFrame_ == NULL)
{
Base::NInstPtr<NFrame> rootFrame(MemToolParam);
rootFrame_ = (NFrame*)rootFrame;
rootFrame_->window_ = this;
Base::NRect rect;
GetRect(rect);
rootFrame_->SetSize(rect.Width(), rect.Height());
}
return rootFrame_;
}
NRender* NWindow::GetRender() const
{
return render_;
}
void NWindow::SetDrawCallback(WindowDrawCallback callback)
{
drawCallback_ = callback;
}
// WindowMsgFilter
bool NWindow::OnMessage(UINT message, WPARAM wParam, LPARAM lParam, LRESULT& lResult)
{
if(NWindowBase::OnMessage(message, wParam, lParam, lResult))
return true;
switch(message)
{
case WM_CREATE:
render_ = NUiBus::Instance().CreateRender();
break;
case WM_DESTROY:
render_ = NULL;
rootFrame_ = NULL;
break;
case WM_ERASEBKGND:
lResult = 1;
return true;
case WM_NCACTIVATE:
{
if(::IsIconic(window_))
return false;
lResult = (wParam == 0) ? TRUE : FALSE;
return true;
}
case WM_NCHITTEST:
{
lResult = HTCLIENT;
return true;
}
case WM_NCPAINT:
case WM_NCCALCSIZE:
{
lResult = 0;
return true;
}
case WM_PAINT:
{
PAINTSTRUCT ps = {0};
HDC hDc = ::BeginPaint(window_, &ps);
Draw(hDc);
::EndPaint(window_, &ps);
}
break;
case WM_PRINT:
{
HDC hDc = (HDC)wParam;
Draw(hDc);
}
break;
case WM_SIZE:
if(wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED)
{
lResult = DoDefault(message, wParam, lParam);
OnSize(LOWORD(lParam), HIWORD(lParam));
return true;
}
break;
case WM_ACTIVATE:
{
BOOL bActive = (LOWORD(wParam) != WA_INACTIVE);
if(!bActive)
{
SetHoverItem(NULL);
NUiBus::Instance().SetCaptureFrame(NULL);
}
break;
}
case WM_MOUSEMOVE:
{
Base::NPoint point(LOWORD(lParam), HIWORD(lParam));
RefreshHoverItem(point);
}
break;
case WM_LBUTTONDOWN:
::SendMessage(window_, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
break;
case WM_LBUTTONUP:
break;
break;
}
return false;
}
void NWindow::OnSize(int width, int height)
{
if(rootFrame_)
rootFrame_->SetSize(width, height);
HRGN rgn = ::CreateRectRgn(0, 0, width, height);
if(rgn != NULL)
::SetWindowRgn(GetNative(), rgn, FALSE);
}
void NWindow::OnDraw(NRender* render, const Base::NRect& clipRect)
{
if(drawCallback_ && drawCallback_(this, render, clipRect))
return;
if(rootFrame_ != NULL)
{
Base::NPoint pt;
rootFrame_->Draw(render, pt, clipRect);
}
}
void NWindow::Draw(HDC hDc)
{
Base::NRect clientRect;
::GetClientRect(window_, clientRect);
render_->Init(hDc, clientRect);
Base::NRect clipRect;
int nResult = GetClipBox(hDc, clipRect);
if(nResult == NULLREGION)
::GetClientRect(window_, clipRect);
OnDraw(render_, clipRect);
render_->DrawBack(IsLayered());
}
void NWindow::SetHoverItem(NFrame* frame)
{
if(hoverFrame_ == frame)
return;
if(hoverFrame_)
hoverFrame_->CancelHover();
hoverFrame_ = frame;
if(hoverFrame_)
hoverFrame_->BeginHover();
}
void NWindow::RefreshHoverItem(const Base::NPoint& point)
{
NFrame* newHover = NULL;
if(hoverFrame_)
{
newHover = hoverFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
}
if(!newHover)
{
newHover = rootFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
}
SetHoverItem(newHover);
}
}
}
<commit_msg>fix crash<commit_after>#include "stdafx.h"
#include "../NWindow.h"
namespace nui
{
namespace Ui
{
NWindow::NWindow()
{
}
NWindow::~NWindow()
{
}
NFrame* NWindow::GetRootFrame()
{
if(rootFrame_ == NULL)
{
Base::NInstPtr<NFrame> rootFrame(MemToolParam);
rootFrame_ = (NFrame*)rootFrame;
rootFrame_->window_ = this;
Base::NRect rect;
GetRect(rect);
rootFrame_->SetSize(rect.Width(), rect.Height());
}
return rootFrame_;
}
NRender* NWindow::GetRender() const
{
return render_;
}
void NWindow::SetDrawCallback(WindowDrawCallback callback)
{
drawCallback_ = callback;
}
// WindowMsgFilter
bool NWindow::OnMessage(UINT message, WPARAM wParam, LPARAM lParam, LRESULT& lResult)
{
if(NWindowBase::OnMessage(message, wParam, lParam, lResult))
return true;
switch(message)
{
case WM_CREATE:
render_ = NUiBus::Instance().CreateRender();
break;
case WM_DESTROY:
render_ = NULL;
rootFrame_ = NULL;
break;
case WM_ERASEBKGND:
lResult = 1;
return true;
case WM_NCACTIVATE:
{
if(::IsIconic(window_))
return false;
lResult = (wParam == 0) ? TRUE : FALSE;
return true;
}
case WM_NCHITTEST:
{
lResult = HTCLIENT;
return true;
}
case WM_NCPAINT:
case WM_NCCALCSIZE:
{
lResult = 0;
return true;
}
case WM_PAINT:
{
PAINTSTRUCT ps = {0};
HDC hDc = ::BeginPaint(window_, &ps);
Draw(hDc);
::EndPaint(window_, &ps);
}
break;
case WM_PRINT:
{
HDC hDc = (HDC)wParam;
Draw(hDc);
}
break;
case WM_SIZE:
if(wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED)
{
lResult = DoDefault(message, wParam, lParam);
OnSize(LOWORD(lParam), HIWORD(lParam));
return true;
}
break;
case WM_ACTIVATE:
{
BOOL bActive = (LOWORD(wParam) != WA_INACTIVE);
if(!bActive)
{
SetHoverItem(NULL);
NUiBus::Instance().SetCaptureFrame(NULL);
}
break;
}
case WM_MOUSEMOVE:
{
Base::NPoint point(LOWORD(lParam), HIWORD(lParam));
RefreshHoverItem(point);
}
break;
case WM_LBUTTONDOWN:
::SendMessage(window_, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
break;
case WM_LBUTTONUP:
break;
break;
}
return false;
}
void NWindow::OnSize(int width, int height)
{
if(rootFrame_)
rootFrame_->SetSize(width, height);
HRGN rgn = ::CreateRectRgn(0, 0, width, height);
if(rgn != NULL)
::SetWindowRgn(GetNative(), rgn, FALSE);
}
void NWindow::OnDraw(NRender* render, const Base::NRect& clipRect)
{
if(drawCallback_ && drawCallback_(this, render, clipRect))
return;
if(rootFrame_ != NULL)
{
Base::NPoint pt;
rootFrame_->Draw(render, pt, clipRect);
}
}
void NWindow::Draw(HDC hDc)
{
Base::NRect clientRect;
::GetClientRect(window_, clientRect);
render_->Init(hDc, clientRect);
Base::NRect clipRect;
int nResult = GetClipBox(hDc, clipRect);
if(nResult == NULLREGION)
::GetClientRect(window_, clipRect);
OnDraw(render_, clipRect);
render_->DrawBack(IsLayered());
}
void NWindow::SetHoverItem(NFrame* frame)
{
if(hoverFrame_ == frame)
return;
if(hoverFrame_)
hoverFrame_->CancelHover();
hoverFrame_ = frame;
if(hoverFrame_)
hoverFrame_->BeginHover();
}
void NWindow::RefreshHoverItem(const Base::NPoint& point)
{
if(rootFrame_ == NULL)
return;
NFrame* newHover = NULL;
if(hoverFrame_)
{
newHover = hoverFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
}
if(!newHover)
{
newHover = rootFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
}
SetHoverItem(newHover);
}
}
}
<|endoftext|> |
<commit_before>//===--- ToolChain.cpp - Collections of tools for one platform ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/ToolChain.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang::driver;
using namespace clang;
ToolChain::ToolChain(const Driver &D, const llvm::Triple &T)
: D(D), Triple(T) {
}
ToolChain::~ToolChain() {
}
const Driver &ToolChain::getDriver() const {
return D;
}
std::string ToolChain::getDefaultUniversalArchName() const {
// In universal driver terms, the arch name accepted by -arch isn't exactly
// the same as the ones that appear in the triple. Roughly speaking, this is
// an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
// only interesting special case is powerpc.
switch (Triple.getArch()) {
case llvm::Triple::ppc:
return "ppc";
case llvm::Triple::ppc64:
return "ppc64";
default:
return Triple.getArchName();
}
}
bool ToolChain::IsUnwindTablesDefault() const {
return false;
}
std::string ToolChain::GetFilePath(const char *Name) const {
return D.GetFilePath(Name, *this);
}
std::string ToolChain::GetProgramPath(const char *Name) const {
return D.GetProgramPath(Name, *this);
}
types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
return types::lookupTypeForExtension(Ext);
}
bool ToolChain::HasNativeLLVMSupport() const {
return false;
}
ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
VersionTuple());
}
/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
//
// FIXME: tblgen this.
static const char *getARMTargetCPU(const ArgList &Args,
const llvm::Triple &Triple) {
// For Darwin targets, the -arch option (which is translated to a
// corresponding -march option) should determine the architecture
// (and the Mach-O slice) regardless of any -mcpu options.
if (!Triple.isOSDarwin()) {
// FIXME: Warn on inconsistent use of -mcpu and -march.
// If we have -mcpu=, use that.
if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
return A->getValue();
}
StringRef MArch;
if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
// Otherwise, if we have -march= choose the base CPU for that arch.
MArch = A->getValue();
} else {
// Otherwise, use the Arch from the triple.
MArch = Triple.getArchName();
}
return llvm::StringSwitch<const char *>(MArch)
.Cases("armv2", "armv2a","arm2")
.Case("armv3", "arm6")
.Case("armv3m", "arm7m")
.Cases("armv4", "armv4t", "arm7tdmi")
.Cases("armv5", "armv5t", "arm10tdmi")
.Cases("armv5e", "armv5te", "arm1026ejs")
.Case("armv5tej", "arm926ej-s")
.Cases("armv6", "armv6k", "arm1136jf-s")
.Case("armv6j", "arm1136j-s")
.Cases("armv6z", "armv6zk", "arm1176jzf-s")
.Case("armv6t2", "arm1156t2-s")
.Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
.Cases("armv7l", "armv7-l", "cortex-a8")
.Cases("armv7f", "armv7-f", "cortex-a9-mp")
.Cases("armv7s", "armv7-s", "swift")
.Cases("armv7r", "armv7-r", "cortex-r4", "cortex-r5")
.Cases("armv7m", "armv7-m", "cortex-m3")
.Case("ep9312", "ep9312")
.Case("iwmmxt", "iwmmxt")
.Case("xscale", "xscale")
.Cases("armv6m", "armv6-m", "cortex-m0")
// If all else failed, return the most base CPU LLVM supports.
.Default("arm7tdmi");
}
/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
/// CPU.
//
// FIXME: This is redundant with -mcpu, why does LLVM use this.
// FIXME: tblgen this, or kill it!
static const char *getLLVMArchSuffixForARM(StringRef CPU) {
return llvm::StringSwitch<const char *>(CPU)
.Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
.Cases("arm720t", "arm9", "arm9tdmi", "v4t")
.Cases("arm920", "arm920t", "arm922t", "v4t")
.Cases("arm940t", "ep9312","v4t")
.Cases("arm10tdmi", "arm1020t", "v5")
.Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e")
.Cases("arm966e-s", "arm968e-s", "arm10e", "v5e")
.Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e")
.Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6")
.Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6")
.Cases("arm1156t2-s", "arm1156t2f-s", "v6t2")
.Cases("cortex-a8", "cortex-a9", "cortex-a15", "v7")
.Case("cortex-m3", "v7m")
.Case("cortex-m4", "v7m")
.Case("cortex-m0", "v6m")
.Case("cortex-a9-mp", "v7f")
.Case("swift", "v7s")
.Default("");
}
std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
types::ID InputType) const {
switch (getTriple().getArch()) {
default:
return getTripleString();
case llvm::Triple::arm:
case llvm::Triple::thumb: {
// FIXME: Factor into subclasses.
llvm::Triple Triple = getTriple();
// Thumb2 is the default for V7 on Darwin.
//
// FIXME: Thumb should just be another -target-feaure, not in the triple.
StringRef Suffix =
getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
bool ThumbDefault = (Suffix.startswith("v7") && getTriple().isOSDarwin());
std::string ArchName = "arm";
// Assembly files should start in ARM mode.
if (InputType != types::TY_PP_Asm &&
Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
ArchName = "thumb";
Triple.setArchName(ArchName + Suffix.str());
return Triple.getTriple();
}
}
}
std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
types::ID InputType) const {
// Diagnose use of Darwin OS deployment target arguments on non-Darwin.
if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
options::OPT_miphoneos_version_min_EQ,
options::OPT_mios_simulator_version_min_EQ))
getDriver().Diag(diag::err_drv_clang_unsupported)
<< A->getAsString(Args);
return ComputeLLVMTriple(Args, InputType);
}
void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
// Each toolchain should provide the appropriate include flags.
}
void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
}
ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
const ArgList &Args) const
{
if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
StringRef Value = A->getValue();
if (Value == "compiler-rt")
return ToolChain::RLT_CompilerRT;
if (Value == "libgcc")
return ToolChain::RLT_Libgcc;
getDriver().Diag(diag::err_drv_invalid_rtlib_name)
<< A->getAsString(Args);
}
return GetDefaultRuntimeLibType();
}
ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
StringRef Value = A->getValue();
if (Value == "libc++")
return ToolChain::CST_Libcxx;
if (Value == "libstdc++")
return ToolChain::CST_Libstdcxx;
getDriver().Diag(diag::err_drv_invalid_stdlib_name)
<< A->getAsString(Args);
}
return ToolChain::CST_Libstdcxx;
}
/// \brief Utility function to add a system include directory to CC1 arguments.
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
ArgStringList &CC1Args,
const Twine &Path) {
CC1Args.push_back("-internal-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(Path));
}
/// \brief Utility function to add a system include directory with extern "C"
/// semantics to CC1 arguments.
///
/// Note that this should be used rarely, and only for directories that
/// historically and for legacy reasons are treated as having implicit extern
/// "C" semantics. These semantics are *ignored* by and large today, but its
/// important to preserve the preprocessor changes resulting from the
/// classification.
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
ArgStringList &CC1Args,
const Twine &Path) {
CC1Args.push_back("-internal-externc-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(Path));
}
/// \brief Utility function to add a list of system include directories to CC1.
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
ArgStringList &CC1Args,
ArrayRef<StringRef> Paths) {
for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
I != E; ++I) {
CC1Args.push_back("-internal-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(*I));
}
}
void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
// Header search paths should be handled by each of the subclasses.
// Historically, they have not been, and instead have been handled inside of
// the CC1-layer frontend. As the logic is hoisted out, this generic function
// will slowly stop being called.
//
// While it is being called, replicate a bit of a hack to propagate the
// '-stdlib=' flag down to CC1 so that it can in turn customize the C++
// header search paths with it. Once all systems are overriding this
// function, the CC1 flag and this line can be removed.
DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
}
void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
CXXStdlibType Type = GetCXXStdlibType(Args);
switch (Type) {
case ToolChain::CST_Libcxx:
CmdArgs.push_back("-lc++");
break;
case ToolChain::CST_Libstdcxx:
CmdArgs.push_back("-lstdc++");
break;
}
}
void ToolChain::AddCCKextLibArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
CmdArgs.push_back("-lcc_kext");
}
bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
ArgStringList &CmdArgs) const {
// Check if -ffast-math or -funsafe-math is enabled.
Arg *A = Args.getLastArg(options::OPT_ffast_math,
options::OPT_fno_fast_math,
options::OPT_funsafe_math_optimizations,
options::OPT_fno_unsafe_math_optimizations);
if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
return false;
// If crtfastmath.o exists add it to the arguments.
std::string Path = GetFilePath("crtfastmath.o");
if (Path == "crtfastmath.o") // Not found.
return false;
CmdArgs.push_back(Args.MakeArgString(Path));
return true;
}
<commit_msg>Fix confused use of llvm::StringSwitch for armv7r architecture.<commit_after>//===--- ToolChain.cpp - Collections of tools for one platform ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/ToolChain.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang::driver;
using namespace clang;
ToolChain::ToolChain(const Driver &D, const llvm::Triple &T)
: D(D), Triple(T) {
}
ToolChain::~ToolChain() {
}
const Driver &ToolChain::getDriver() const {
return D;
}
std::string ToolChain::getDefaultUniversalArchName() const {
// In universal driver terms, the arch name accepted by -arch isn't exactly
// the same as the ones that appear in the triple. Roughly speaking, this is
// an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
// only interesting special case is powerpc.
switch (Triple.getArch()) {
case llvm::Triple::ppc:
return "ppc";
case llvm::Triple::ppc64:
return "ppc64";
default:
return Triple.getArchName();
}
}
bool ToolChain::IsUnwindTablesDefault() const {
return false;
}
std::string ToolChain::GetFilePath(const char *Name) const {
return D.GetFilePath(Name, *this);
}
std::string ToolChain::GetProgramPath(const char *Name) const {
return D.GetProgramPath(Name, *this);
}
types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
return types::lookupTypeForExtension(Ext);
}
bool ToolChain::HasNativeLLVMSupport() const {
return false;
}
ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
VersionTuple());
}
/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
//
// FIXME: tblgen this.
static const char *getARMTargetCPU(const ArgList &Args,
const llvm::Triple &Triple) {
// For Darwin targets, the -arch option (which is translated to a
// corresponding -march option) should determine the architecture
// (and the Mach-O slice) regardless of any -mcpu options.
if (!Triple.isOSDarwin()) {
// FIXME: Warn on inconsistent use of -mcpu and -march.
// If we have -mcpu=, use that.
if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
return A->getValue();
}
StringRef MArch;
if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
// Otherwise, if we have -march= choose the base CPU for that arch.
MArch = A->getValue();
} else {
// Otherwise, use the Arch from the triple.
MArch = Triple.getArchName();
}
return llvm::StringSwitch<const char *>(MArch)
.Cases("armv2", "armv2a","arm2")
.Case("armv3", "arm6")
.Case("armv3m", "arm7m")
.Cases("armv4", "armv4t", "arm7tdmi")
.Cases("armv5", "armv5t", "arm10tdmi")
.Cases("armv5e", "armv5te", "arm1026ejs")
.Case("armv5tej", "arm926ej-s")
.Cases("armv6", "armv6k", "arm1136jf-s")
.Case("armv6j", "arm1136j-s")
.Cases("armv6z", "armv6zk", "arm1176jzf-s")
.Case("armv6t2", "arm1156t2-s")
.Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
.Cases("armv7l", "armv7-l", "cortex-a8")
.Cases("armv7f", "armv7-f", "cortex-a9-mp")
.Cases("armv7s", "armv7-s", "swift")
.Cases("armv7r", "armv7-r", "cortex-r4")
.Cases("armv7m", "armv7-m", "cortex-m3")
.Case("ep9312", "ep9312")
.Case("iwmmxt", "iwmmxt")
.Case("xscale", "xscale")
.Cases("armv6m", "armv6-m", "cortex-m0")
// If all else failed, return the most base CPU LLVM supports.
.Default("arm7tdmi");
}
/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
/// CPU.
//
// FIXME: This is redundant with -mcpu, why does LLVM use this.
// FIXME: tblgen this, or kill it!
static const char *getLLVMArchSuffixForARM(StringRef CPU) {
return llvm::StringSwitch<const char *>(CPU)
.Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
.Cases("arm720t", "arm9", "arm9tdmi", "v4t")
.Cases("arm920", "arm920t", "arm922t", "v4t")
.Cases("arm940t", "ep9312","v4t")
.Cases("arm10tdmi", "arm1020t", "v5")
.Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e")
.Cases("arm966e-s", "arm968e-s", "arm10e", "v5e")
.Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e")
.Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6")
.Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6")
.Cases("arm1156t2-s", "arm1156t2f-s", "v6t2")
.Cases("cortex-a8", "cortex-a9", "cortex-a15", "v7")
.Case("cortex-m3", "v7m")
.Case("cortex-m4", "v7m")
.Case("cortex-m0", "v6m")
.Case("cortex-a9-mp", "v7f")
.Case("swift", "v7s")
.Default("");
}
std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
types::ID InputType) const {
switch (getTriple().getArch()) {
default:
return getTripleString();
case llvm::Triple::arm:
case llvm::Triple::thumb: {
// FIXME: Factor into subclasses.
llvm::Triple Triple = getTriple();
// Thumb2 is the default for V7 on Darwin.
//
// FIXME: Thumb should just be another -target-feaure, not in the triple.
StringRef Suffix =
getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
bool ThumbDefault = (Suffix.startswith("v7") && getTriple().isOSDarwin());
std::string ArchName = "arm";
// Assembly files should start in ARM mode.
if (InputType != types::TY_PP_Asm &&
Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
ArchName = "thumb";
Triple.setArchName(ArchName + Suffix.str());
return Triple.getTriple();
}
}
}
std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
types::ID InputType) const {
// Diagnose use of Darwin OS deployment target arguments on non-Darwin.
if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
options::OPT_miphoneos_version_min_EQ,
options::OPT_mios_simulator_version_min_EQ))
getDriver().Diag(diag::err_drv_clang_unsupported)
<< A->getAsString(Args);
return ComputeLLVMTriple(Args, InputType);
}
void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
// Each toolchain should provide the appropriate include flags.
}
void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
}
ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
const ArgList &Args) const
{
if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
StringRef Value = A->getValue();
if (Value == "compiler-rt")
return ToolChain::RLT_CompilerRT;
if (Value == "libgcc")
return ToolChain::RLT_Libgcc;
getDriver().Diag(diag::err_drv_invalid_rtlib_name)
<< A->getAsString(Args);
}
return GetDefaultRuntimeLibType();
}
ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
StringRef Value = A->getValue();
if (Value == "libc++")
return ToolChain::CST_Libcxx;
if (Value == "libstdc++")
return ToolChain::CST_Libstdcxx;
getDriver().Diag(diag::err_drv_invalid_stdlib_name)
<< A->getAsString(Args);
}
return ToolChain::CST_Libstdcxx;
}
/// \brief Utility function to add a system include directory to CC1 arguments.
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
ArgStringList &CC1Args,
const Twine &Path) {
CC1Args.push_back("-internal-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(Path));
}
/// \brief Utility function to add a system include directory with extern "C"
/// semantics to CC1 arguments.
///
/// Note that this should be used rarely, and only for directories that
/// historically and for legacy reasons are treated as having implicit extern
/// "C" semantics. These semantics are *ignored* by and large today, but its
/// important to preserve the preprocessor changes resulting from the
/// classification.
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
ArgStringList &CC1Args,
const Twine &Path) {
CC1Args.push_back("-internal-externc-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(Path));
}
/// \brief Utility function to add a list of system include directories to CC1.
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
ArgStringList &CC1Args,
ArrayRef<StringRef> Paths) {
for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
I != E; ++I) {
CC1Args.push_back("-internal-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(*I));
}
}
void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
// Header search paths should be handled by each of the subclasses.
// Historically, they have not been, and instead have been handled inside of
// the CC1-layer frontend. As the logic is hoisted out, this generic function
// will slowly stop being called.
//
// While it is being called, replicate a bit of a hack to propagate the
// '-stdlib=' flag down to CC1 so that it can in turn customize the C++
// header search paths with it. Once all systems are overriding this
// function, the CC1 flag and this line can be removed.
DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
}
void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
CXXStdlibType Type = GetCXXStdlibType(Args);
switch (Type) {
case ToolChain::CST_Libcxx:
CmdArgs.push_back("-lc++");
break;
case ToolChain::CST_Libstdcxx:
CmdArgs.push_back("-lstdc++");
break;
}
}
void ToolChain::AddCCKextLibArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
CmdArgs.push_back("-lcc_kext");
}
bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
ArgStringList &CmdArgs) const {
// Check if -ffast-math or -funsafe-math is enabled.
Arg *A = Args.getLastArg(options::OPT_ffast_math,
options::OPT_fno_fast_math,
options::OPT_funsafe_math_optimizations,
options::OPT_fno_unsafe_math_optimizations);
if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
return false;
// If crtfastmath.o exists add it to the arguments.
std::string Path = GetFilePath("crtfastmath.o");
if (Path == "crtfastmath.o") // Not found.
return false;
CmdArgs.push_back(Args.MakeArgString(Path));
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <random>
#define SIZEF 500
struct Position{
int x;
int y;
};
using namespace std;
void walk(Position *p,int &board,int size){
//https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
random_device rd;
mt19937_64 gen(rd());
//http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
uniform_int_distribution<int> uni(0,100);
int random = uni(gen);
cout << random<<"\n";
}
int main(int argc, char const *argv[]) {
int board [SIZEF][SIZEF];
int size,count;
Position *p;
p = (Position *) malloc(sizeof(Position));
cin >> size;
p->x = 0;
p->y = 0;
board[0][0] = 1;
count = 2;
for (int i = 0; i < size; i++) {
for (int j = 0;j < size; j++){
walk(p,**board,size);
}
}
return 0;
}
<commit_msg>walk() func walking???<commit_after>#include <iostream>
#include <random>
#define SIZEF 500
struct Position{
int x;
int y;
};
using namespace std;
int walk(Position *p,int &board,int size){
//https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
random_device rd;
mt19937_64 gen(rd());
//http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
uniform_real_distribution<> uni(0,99);
cout << uni(gen)<<"\n";
float random = uni(gen);
while(1){
if (0 <= random%100 < 12.5) { // move 1
if((p->x-2>=0)&&(p->y+1<size)){
if (board[p->x-2][p->y+1] == 0) {
p->x-=2;
p->y+=1;
}
}
}else if (12.5 <= random%100 < 25){ // move 2
if((p->x-1>=0)&&(p->y+2<size)){
if (board[p->x-1][p->y+2] == 0) {
p->x-=1;
p->y+=2;
}
}
}else if (25 <= random%100 < 37.5){ // move 3
if((p->x+1<size)&&(p->y+2<size)){
if (board[p->x+1][p->y+2] == 0) {
p->x+=1;
p->y+=2;
}
}
}else if (37.5 <= random%100 < 50){ // move 4
if((p->x+2<size)&&(p->y+1<size)){
if (board[p->x+2][p->y+1] == 0) {
p->x+=2;
p->y+=1;
}
}
}else if (50 <= random%100 < 62.5){ // move 5
if((p->x+2<size)&&(p->y-1>=0)){
if (board[p->x+2][p->y+1] == 0) {
p->x+=2;
p->y-=1;
}
}
}else if (62.5 <= random%100 < 75){ // move 6
if((p->x+1<size)&&(p->y-2>=0)){
if (board[p->x+1][p->y+2] == 0) {
p->x+=1;
p->y-=2;
}
}
}else if (75 <= random%100 < 87.5){ // move 7
if((p->x-1>=0)&&(p->y-2>=0)){
if (board[p->x-1][p->y-2] == 0) {
p->x-=1;
p->y-=2;
}
}
}else if (87.5 <= random%100 < 100){ // move 8
if((p->x-2>=0)&&(p->y-1>=0)){
if (board[p->x-2][p->y-1] == 0) {
p->x-=2;
p->y-=1;
}
}
}
}
}
int main(int argc, char const *argv[]) {
int board [SIZEF][SIZEF] = {0};
int size,count,end;
int i, j;
Position *p;
p = (Position *) malloc(sizeof(Position));
cin >> size;
while (1) {
p->x = 0;
p->y = 0;
board[0][0] = 1;
count = 2;
for (i = 0; i < size; i++) {
for (j = 0;j < size; j++){
end = walk(p,**board,size);
if (end == 1) {
}
}
}
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>fix windows build<commit_after><|endoftext|> |
<commit_before>/*
Sequence hot to se the PWG1 analysis tasks:
//1. Load libraries if needed:
//
gSystem->Load("/usr/local/grid/XRootd/GSI/lib/libXrdClient.so");
gSystem->Load("libANALYSIS.so");
gSystem->Load("libANALYSISalice.so");
gSystem->Load("libPWG0base.so");
gSystem->Load("libPWG0dep.so");
gSystem->Load("libPWG1.so");
AliLog::SetGlobalLogLevel(AliLog::kError);
//2. Make a chain e.g.:
//
gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+");
AliXRDPROOFtoolkit tool;
TChain * chainEsd = tool.MakeChain("esd.txt","esdTree",0,5000);
chainEsd->Lookup();
//
//3. Make a analysis manager with attached task:
.L $ALICE_ROOT/PWG1/Macros/taskComp.C
Init();
AliAnalysisManager *mgr = MakeManager();
//4. Process task localy
//
mgr->SetNSysInfo(100);
mgr->SetDebugLevel(1);
mgr->StartAnalysis("local",chainEsd);
//
//4. Process task on proof
//
TProof::Open("");
.L /u/miranov/macros/ProofEnableAliRoot.C
ProofEnableAliRoot("/usr/local/grid/AliRoot/HEAD0108");
gProof->Exec("gSystem->Load(\"libANALYSIS.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libAOD.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libANALYSISalice.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libPWG0base.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libPWG0dep.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libPWG1.so\")",kTRUE);
mgr->StartAnalysis("proof",chainEsd);
//5. Get debug stream - if speciefied
TFile f("mcTaskDebug.root");
TTree *treeCMP = (TTree*)f.Get("RC");
//6. Read the analysis object
TFile f("Output.root");
TObjArray * array = (TObjArray*)f.Get("AliComparisonRes");
AliComparisonRes * compObj = (AliComparisonRes*)array->FindObject("AliComparisonRes");
//
//7. Get debug streamer on PROOF
gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+")
AliXRDPROOFtoolkit tool;
TChain * chainTr = tool.MakeChain("cmp.txt","RC",0,1000000);
chainTr->Lookup();
chainTr->SetProof(kTRUE);
TChain * chainTPC = tool.MakeChain("tpc.txt","Crefit",0,50);
chainTPC->Lookup();
chainTr->SetProof(kTRUE);
TFile f("mcTaskDebug.root");
TTree *treeCMP = (TTree*)f.Get("RC");
*/
void AddComparison( AliGenInfoTask * task);
void Init(){
//
// Init mag field and the geo manager
//
TGeoManager::Import("/u/miranov/proof/geometry.root");
AliGeomManager::LoadGeometry("/u/miranov/proof/geometry.root");
TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));
}
AliAnalysisManager * MakeManager(){
//
//
//
AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisComponentManager");
mgr->SetDebugLevel(1);
cout << "Creating ESD event handler" << endl;
AliESDInputHandler* esdH = new AliESDInputHandler();
// set the ESDfriend branch active (my modification of AliESDInputHandler)
esdH->SetActiveBranches("ESDfriend");
mgr->SetInputEventHandler(esdH);
AliMCEventHandler* mcHandler = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mcHandler);
//
AliGenInfoTask *genTask = new AliGenInfoTask("genTask");
genTask->SetStreamLevel(10);
genTask->SetDebugLevel(10);
genTask->SetDebugOuputhPath(gSystem->pwd());
// //AddComparison(genTask);
// mgr->AddTask(genTask);
// //
// //
// AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
// mgr->ConnectInput(genTask,0,cinput1);
// //
// AliAnalysisDataContainer *coutput1
// =mgr->CreateContainer("AliComparisonRes",TObjArray::Class(),
// AliAnalysisManager::kOutputContainer,
// "Output.root");
// mgr->ConnectOutput(genTask,0,coutput1);
//
// TPC PID task
//
AliTPCtaskPID *pidTask = new AliTPCtaskPID("pidTask");
mgr->AddTask(pidTask);
AliAnalysisDataContainer *cinput2 = mgr->GetCommonInputContainer();
mgr->ConnectInput(pidTask,0,cinput2);
//
AliAnalysisDataContainer *coutput2
=mgr->CreateContainer("tpcTaskPID", TObjArray::Class(),
AliAnalysisManager::kOutputContainer,
"OutputPID.root");
mgr->ConnectOutput(pidTask,0,coutput2);
//
// TPC QA task
//
AliTPCtaskQA *qaTask = new AliTPCtaskQA("qaTask");
mgr->AddTask(qaTask);
AliAnalysisDataContainer *cinput3 = mgr->GetCommonInputContainer();
mgr->ConnectInput(qaTask,0,cinput3);
//
AliAnalysisDataContainer *coutput3
=mgr->CreateContainer("tpcTaskQA", TObjArray::Class(),
AliAnalysisManager::kOutputContainer,
"OutputQA.root");
mgr->ConnectOutput(qaTask,0,coutput3);
//
if (!mgr->InitAnalysis()) return 0;
return mgr;
}
void AddComparison( AliGenInfoTask * task){
// Create ESD track reconstruction cuts
AliRecInfoCuts *pRecInfoCuts = new AliRecInfoCuts();
if(pRecInfoCuts) {
pRecInfoCuts->SetPtRange(0.15,200.0);
pRecInfoCuts->SetMaxAbsTanTheta(1.0);
pRecInfoCuts->SetMinNClustersTPC(10);
pRecInfoCuts->SetMinNClustersITS(2);
pRecInfoCuts->SetMinTPCsignalN(50);
pRecInfoCuts->SetHistogramsOn(kFALSE);
} else {
AliDebug(AliLog::kError, "ERROR: Cannot create AliRecInfoCuts object");
}
// Create MC track reconstruction cuts
AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts();
if(pMCInfoCuts) {
pMCInfoCuts->SetMinRowsWithDigits(50);
pMCInfoCuts->SetMaxR(0.001);
pMCInfoCuts->SetMaxVz(0.001);
pMCInfoCuts->SetRangeTPCSignal(0.5,1.4);
} else {
AliDebug(AliLog::kError, "ERROR: Cannot AliMCInfoCuts object");
}
//
// Create comparison objects and set cuts
//
// Resolution
AliComparisonRes *pCompRes = new AliComparisonRes("AliComparisonRes","AliComparisonRes");
if(!pCompRes) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonRes object");
}
pCompRes->SetAliRecInfoCuts(pRecInfoCuts);
pCompRes->SetAliMCInfoCuts(pMCInfoCuts);
// Efficiency
AliComparisonEff *pCompEff = new AliComparisonEff("AliComparisonEff","AliComparisonEff");
if(!pCompEff) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonEff object");
}
pCompEff->SetAliRecInfoCuts(pRecInfoCuts);
pCompEff->SetAliMCInfoCuts(pMCInfoCuts);
// dE/dx
AliComparisonDEdx *pCompDEdx = new AliComparisonDEdx("AliComparisonDEdx","AliComparisonDEdx");
if(!pCompDEdx) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDEdx object");
}
pCompDEdx->SetAliRecInfoCuts(pRecInfoCuts);
pCompDEdx->SetAliMCInfoCuts(pMCInfoCuts);
pCompDEdx->SetMCPtMin(0.5);
pCompDEdx->SetMCAbsTanThetaMax(0.5);
pCompDEdx->SetMCPdgCode(pMCInfoCuts->GetPiP()); // only pi+ particles
// DCA
AliComparisonDCA *pCompDCA = new AliComparisonDCA("AliComparisonDCA","AliComparisonDCA");
if(!pCompDCA) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDCA object");
}
pCompDCA->SetAliRecInfoCuts(pRecInfoCuts);
pCompDCA->SetAliMCInfoCuts(pMCInfoCuts);
//
//
//
task->AddComparisonObject( pCompRes );
task->AddComparisonObject( pCompEff );
task->AddComparisonObject( pCompDEdx );
task->AddComparisonObject( pCompDCA );
}
<commit_msg>Example macro to run ( not only) AliMCTrackinTestTask<commit_after>/*
Sequence hot to se the PWG1 analysis tasks:
//1. Load libraries if needed:
//
gSystem->Load("/usr/local/grid/XRootd/GSI/lib/libXrdClient.so");
gSystem->Load("libANALYSIS.so");
gSystem->Load("libANALYSISalice.so");
gSystem->Load("libPWG0base.so");
gSystem->Load("libPWG0dep.so");
gSystem->Load("libPWG1.so");
AliLog::SetGlobalLogLevel(AliLog::kError);
//2. Make a chain e.g.:
//
gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+");
AliXRDPROOFtoolkit tool;
TChain * chainEsd = tool.MakeChain("esd.txt","esdTree",0,5);
chainEsd->Lookup();
//
//3. Make a analysis manager with attached task:
.L $ALICE_ROOT/PWG1/macros/taskComp.C
Init();
AliAnalysisManager *mgr = MakeManager();
//4. Process task localy
//
mgr->SetNSysInfo(100);
mgr->SetDebugLevel(1);
mgr->StartAnalysis("local",chainEsd);
//
//4. Process task on proof
//
TProof::Open("");
.L /u/miranov/macros/ProofEnableAliRoot.C
ProofEnableAliRoot("/usr/local/grid/AliRoot/HEAD0108");
gProof->Exec("gSystem->Load(\"libANALYSIS.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libAOD.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libANALYSISalice.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libPWG0base.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libPWG0dep.so\")",kTRUE);
gProof->Exec("gSystem->Load(\"libPWG1.so\")",kTRUE);
TString path=gSystem->pwd();
TString execCDB="gROOT->Macro(\"";
execCDB+=path+"/ConfigOCDB.C\"\)";
gProof->Exec(execCDB->Data(),kFALSE);
mgr->StartAnalysis("proof",chainEsd);
//5. Get debug stream - if speciefied
TFile f("mcTaskDebug.root");
TTree *treeCMP = (TTree*)f.Get("RC");
//6. Read the analysis object
TFile f("Output.root");
TObjArray * array = (TObjArray*)f.Get("AliComparisonRes");
AliComparisonRes * compObj = (AliComparisonRes*)array->FindObject("AliComparisonRes");
//
//7. Get debug streamer on PROOF
gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+")
AliXRDPROOFtoolkit tool;
TChain * chainTr = tool.MakeChain("cmp.txt","RC",0,1000000);
chainTr->Lookup();
chainTr->SetProof(kTRUE);
TChain * chainTPC = tool.MakeChain("tpc.txt","Crefit",0,50);
chainTPC->Lookup();
chainTr->SetProof(kTRUE);
TChain * chainTracking = tool.MakeChain("mctracking.txt","MCupdate",0,50);
chainTracking->Lookup();
chainTracking->SetProof(kTRUE);
TFile f("mcTaskDebug.root");
TTree *treeCMP = (TTree*)f.Get("RC");
*/
void AddComparison( AliGenInfoTask * task);
void Init(){
//
// Init mag field and the geo manager
//
TGeoManager::Import("/u/miranov/proof/geometry.root");
AliGeomManager::LoadGeometry("/u/miranov/proof/geometry.root");
TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));
}
AliAnalysisManager * MakeManager(){
//
//
//
AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisComponentManager");
mgr->SetDebugLevel(1);
cout << "Creating ESD event handler" << endl;
AliESDInputHandler* esdH = new AliESDInputHandler();
// set the ESDfriend branch active (my modification of AliESDInputHandler)
esdH->SetActiveBranches("ESDfriend");
mgr->SetInputEventHandler(esdH);
AliMCEventHandler* mcHandler = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mcHandler);
//
AliGenInfoTask *genTask = new AliGenInfoTask("genTask");
genTask->SetStreamLevel(10);
genTask->SetDebugLevel(10);
genTask->SetDebugOuputhPath(Form("%s/",gSystem->pwd()));
// //AddComparison(genTask);
// mgr->AddTask(genTask);
// //
// //
// AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
// mgr->ConnectInput(genTask,0,cinput1);
// //
// AliAnalysisDataContainer *coutput1
// =mgr->CreateContainer("AliComparisonRes",TObjArray::Class(),
// AliAnalysisManager::kOutputContainer,
// "Output.root");
// mgr->ConnectOutput(genTask,0,coutput1);
//
// TPC PID task
//
AliTPCtaskPID *pidTask = new AliTPCtaskPID("pidTask");
mgr->AddTask(pidTask);
AliAnalysisDataContainer *cinput2 = mgr->GetCommonInputContainer();
mgr->ConnectInput(pidTask,0,cinput2);
//
AliAnalysisDataContainer *coutput2
=mgr->CreateContainer("tpcTaskPID", TObjArray::Class(),
AliAnalysisManager::kOutputContainer,
"OutputPID.root");
mgr->ConnectOutput(pidTask,0,coutput2);
//
// TPC QA task
//
AliTPCtaskQA *qaTask = new AliTPCtaskQA("qaTask");
mgr->AddTask(qaTask);
AliAnalysisDataContainer *cinput3 = mgr->GetCommonInputContainer();
mgr->ConnectInput(qaTask,0,cinput3);
//
AliAnalysisDataContainer *coutput3
=mgr->CreateContainer("tpcTaskQA", TObjArray::Class(),
AliAnalysisManager::kOutputContainer,
"OutputQA.root");
mgr->ConnectOutput(qaTask,0,coutput3);
//
//
//
AliMCTrackingTestTask *mcTracking = new AliMCTrackingTestTask("mcTracking");
mcTracking->SetStreamLevel(10);
mcTracking->SetDebugLevel(10);
mgr->AddTask(mcTracking);
mcTracking->SetDebugOuputhPath(gSystem->pwd());
AliAnalysisDataContainer *cinput4 = mgr->GetCommonInputContainer();
mgr->ConnectInput(mcTracking,0,cinput4);
//
AliAnalysisDataContainer *coutput4
=mgr->CreateContainer("mcTask", TObjArray::Class(),
AliAnalysisManager::kOutputContainer,
"OutputMC.root");
mgr->ConnectOutput(mcTracking,0,coutput4);
//
if (!mgr->InitAnalysis()) return 0;
return mgr;
}
void AddComparison( AliGenInfoTask * task){
// Create ESD track reconstruction cuts
AliRecInfoCuts *pRecInfoCuts = new AliRecInfoCuts();
if(pRecInfoCuts) {
pRecInfoCuts->SetPtRange(0.15,200.0);
pRecInfoCuts->SetMaxAbsTanTheta(1.0);
pRecInfoCuts->SetMinNClustersTPC(10);
pRecInfoCuts->SetMinNClustersITS(2);
pRecInfoCuts->SetMinTPCsignalN(50);
pRecInfoCuts->SetHistogramsOn(kFALSE);
} else {
AliDebug(AliLog::kError, "ERROR: Cannot create AliRecInfoCuts object");
}
// Create MC track reconstruction cuts
AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts();
if(pMCInfoCuts) {
pMCInfoCuts->SetMinRowsWithDigits(50);
pMCInfoCuts->SetMaxR(0.001);
pMCInfoCuts->SetMaxVz(0.001);
pMCInfoCuts->SetRangeTPCSignal(0.5,1.4);
} else {
AliDebug(AliLog::kError, "ERROR: Cannot AliMCInfoCuts object");
}
//
// Create comparison objects and set cuts
//
// Resolution
AliComparisonRes *pCompRes = new AliComparisonRes("AliComparisonRes","AliComparisonRes");
if(!pCompRes) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonRes object");
}
pCompRes->SetAliRecInfoCuts(pRecInfoCuts);
pCompRes->SetAliMCInfoCuts(pMCInfoCuts);
// Efficiency
AliComparisonEff *pCompEff = new AliComparisonEff("AliComparisonEff","AliComparisonEff");
if(!pCompEff) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonEff object");
}
pCompEff->SetAliRecInfoCuts(pRecInfoCuts);
pCompEff->SetAliMCInfoCuts(pMCInfoCuts);
// dE/dx
AliComparisonDEdx *pCompDEdx = new AliComparisonDEdx("AliComparisonDEdx","AliComparisonDEdx");
if(!pCompDEdx) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDEdx object");
}
pCompDEdx->SetAliRecInfoCuts(pRecInfoCuts);
pCompDEdx->SetAliMCInfoCuts(pMCInfoCuts);
pCompDEdx->SetMCPtMin(0.5);
pCompDEdx->SetMCAbsTanThetaMax(0.5);
pCompDEdx->SetMCPdgCode(pMCInfoCuts->GetPiP()); // only pi+ particles
// DCA
AliComparisonDCA *pCompDCA = new AliComparisonDCA("AliComparisonDCA","AliComparisonDCA");
if(!pCompDCA) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDCA object");
}
pCompDCA->SetAliRecInfoCuts(pRecInfoCuts);
pCompDCA->SetAliMCInfoCuts(pMCInfoCuts);
//
//
//
task->AddComparisonObject( pCompRes );
task->AddComparisonObject( pCompEff );
task->AddComparisonObject( pCompDEdx );
task->AddComparisonObject( pCompDCA );
}
<|endoftext|> |
<commit_before><commit_msg>use LanguageTag<commit_after><|endoftext|> |
<commit_before><commit_msg>WaE: comparison between signed and unsigned integer expressions<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <agency/new_executor_traits.hpp>
#include <agency/future.hpp>
#include <agency/detail/executor_traits/check_for_member_functions.hpp>
#include <type_traits>
#include <iostream>
namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
namespace multi_agent_when_all_execute_and_select_implementation_strategies
{
struct use_multi_agent_when_all_execute_and_select_member_function {};
struct use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function {};
struct use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute {};
template<class IndexSequence, class Executor, class Function, class TupleOfFutures>
using has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits =
has_multi_agent_when_all_execute_and_select_with_shared_inits<
IndexSequence,
Executor,
Function,
TupleOfFutures,
detail::type_list_repeat<new_executor_traits<Executor>::execution_depth, detail::ignore_t>
>;
template<class Executor>
struct dummy_functor_taking_index_type
{
__AGENCY_ANNOTATION
void operator()(const typename new_executor_traits<Executor>::index_type&) const {}
};
template<class Executor>
using has_multi_agent_execute_returning_void =
new_executor_traits_detail::has_multi_agent_execute_returning_void<
Executor,
dummy_functor_taking_index_type<Executor>
>;
template<class Executor, class Function, class TupleOfFutures, size_t... Indices>
using select_multi_agent_when_all_execute_and_select_implementation =
typename std::conditional<
has_multi_agent_when_all_execute_and_select<Executor, Function, TupleOfFutures, Indices...>::value,
use_multi_agent_when_all_execute_and_select_member_function,
typename std::conditional<
has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits<detail::index_sequence<Indices...>, Executor, Function, TupleOfFutures>::value,
use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute
>::type
>::type;
template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<Indices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_member_function,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
return ex.template when_all_execute_and_select<Indices...>(f, shape, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()
template<size_t num_ignored_arguments, class Function>
struct multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor
{
mutable Function f;
template<size_t... ArgIndices, class Index, class Tuple>
__AGENCY_ANNOTATION
void impl(detail::index_sequence<ArgIndices...>, Index&& idx, Tuple&& arg_tuple) const
{
f(idx, std::get<ArgIndices>(std::forward<Tuple>(arg_tuple))...);
}
template<class Index, class... Args>
__AGENCY_ANNOTATION
void operator()(Index&& idx, Args&&... args) const
{
// ignore the arguments that come after the futures
constexpr size_t num_non_ignored_arguments = sizeof...(Args) - num_ignored_arguments;
impl(detail::make_index_sequence<num_non_ignored_arguments>(), std::forward<Index>(idx), detail::forward_as_tuple(std::forward<Args>(args)...));
}
};
template<size_t... SelectedIndices, size_t... SharedInitIndices, class Executor, class Function, class TupleOfFutures, class... Types>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<SelectedIndices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
detail::index_sequence<SharedInitIndices...>,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures, const detail::tuple<Types...>& ignored_shared_inits)
{
constexpr size_t num_ignored_arguments = sizeof...(Types);
auto g = multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor<num_ignored_arguments, Function>{f};
return ex.template when_all_execute_and_select<SelectedIndices...>(g, shape, std::forward<TupleOfFutures>(futures), std::get<SharedInitIndices>(ignored_shared_inits)...);
} // end multi_agent_when_all_execute_and_select()
template<size_t... SelectedIndices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<SelectedIndices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function implementation_strategy,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
constexpr size_t depth = new_executor_traits<Executor>::execution_depth;
// create ignored shared initializers
auto ignored_shared_inits = detail::tuple_repeat<depth>(detail::ignore);
return multi_agent_when_all_execute_and_select<SelectedIndices...>(implementation_strategy,
detail::make_index_sequence<depth>(),
ex, f, shape, std::forward<TupleOfFutures>(futures), ignored_shared_inits);
} // end multi_agent_when_all_execute_and_select()
template<class Executor, class Function>
struct multi_agent_when_all_execute_and_select_functor_using_nested_execute
{
Executor& ex;
mutable Function f;
typename new_executor_traits<Executor>::shape_type shape;
template<class... Args>
struct inner_functor
{
mutable Function f;
mutable detail::tuple<Args&...> args;
template<size_t... TupleIndices, class Index>
__AGENCY_ANNOTATION
void impl(detail::index_sequence<TupleIndices...>, const Index& idx) const
{
f(idx, std::get<TupleIndices>(args)...);
}
template<class Index>
__AGENCY_ANNOTATION
void operator()(const Index& idx) const
{
impl(detail::make_index_sequence<sizeof...(Args)>(), idx);
}
};
template<class... Args>
__AGENCY_ANNOTATION
void operator()(Args&... args) const
{
new_executor_traits<Executor>::execute(ex, inner_functor<Args...>{f, detail::tie(args...)}, shape);
}
};
template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<Indices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
return new_executor_traits<Executor>::template when_all_execute_and_select<Indices...>(ex, multi_agent_when_all_execute_and_select_functor_using_nested_execute<Executor,Function>{ex,f,shape}, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()
} // end multi_agent_when_all_execute_and_select_implementation_strategies
} // end new_executor_traits_detail
} // end detail
template<class Executor>
template<size_t... Indices, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<Indices...>,
typename std::decay<TupleOfFutures>::type
>
>
new_executor_traits<Executor>
::when_all_execute_and_select(typename new_executor_traits<Executor>::executor_type& ex,
Function f,
typename new_executor_traits<Executor>::shape_type shape,
TupleOfFutures&& futures)
{
namespace ns = detail::new_executor_traits_detail::multi_agent_when_all_execute_and_select_implementation_strategies;
using implementation_strategy = ns::select_multi_agent_when_all_execute_and_select_implementation<
Executor,
Function,
typename std::decay<TupleOfFutures>::type,
Indices...
>;
return ns::multi_agent_when_all_execute_and_select<Indices...>(implementation_strategy(), ex, f, shape, std::forward<TupleOfFutures>(futures));
} // end new_executor_traits::when_all_execute_and_select()
} // end agency
<commit_msg>Use agency::invoke() to avoid __host__ __device__ warnings with nvcc<commit_after>#pragma once
#include <agency/new_executor_traits.hpp>
#include <agency/future.hpp>
#include <agency/detail/executor_traits/check_for_member_functions.hpp>
#include <agency/functional.hpp>
#include <type_traits>
#include <iostream>
namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
namespace multi_agent_when_all_execute_and_select_implementation_strategies
{
struct use_multi_agent_when_all_execute_and_select_member_function {};
struct use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function {};
struct use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute {};
template<class IndexSequence, class Executor, class Function, class TupleOfFutures>
using has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits =
has_multi_agent_when_all_execute_and_select_with_shared_inits<
IndexSequence,
Executor,
Function,
TupleOfFutures,
detail::type_list_repeat<new_executor_traits<Executor>::execution_depth, detail::ignore_t>
>;
template<class Executor>
struct dummy_functor_taking_index_type
{
__AGENCY_ANNOTATION
void operator()(const typename new_executor_traits<Executor>::index_type&) const {}
};
template<class Executor>
using has_multi_agent_execute_returning_void =
new_executor_traits_detail::has_multi_agent_execute_returning_void<
Executor,
dummy_functor_taking_index_type<Executor>
>;
template<class Executor, class Function, class TupleOfFutures, size_t... Indices>
using select_multi_agent_when_all_execute_and_select_implementation =
typename std::conditional<
has_multi_agent_when_all_execute_and_select<Executor, Function, TupleOfFutures, Indices...>::value,
use_multi_agent_when_all_execute_and_select_member_function,
typename std::conditional<
has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits<detail::index_sequence<Indices...>, Executor, Function, TupleOfFutures>::value,
use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute
>::type
>::type;
template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<Indices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_member_function,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
return ex.template when_all_execute_and_select<Indices...>(f, shape, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()
template<size_t num_ignored_arguments, class Function>
struct multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor
{
mutable Function f;
template<size_t... ArgIndices, class Index, class Tuple>
__AGENCY_ANNOTATION
void impl(detail::index_sequence<ArgIndices...>, Index&& idx, Tuple&& arg_tuple) const
{
f(idx, std::get<ArgIndices>(std::forward<Tuple>(arg_tuple))...);
}
template<class Index, class... Args>
__AGENCY_ANNOTATION
void operator()(Index&& idx, Args&&... args) const
{
// ignore the arguments that come after the futures
constexpr size_t num_non_ignored_arguments = sizeof...(Args) - num_ignored_arguments;
impl(detail::make_index_sequence<num_non_ignored_arguments>(), std::forward<Index>(idx), detail::forward_as_tuple(std::forward<Args>(args)...));
}
};
template<size_t... SelectedIndices, size_t... SharedInitIndices, class Executor, class Function, class TupleOfFutures, class... Types>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<SelectedIndices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
detail::index_sequence<SharedInitIndices...>,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures, const detail::tuple<Types...>& ignored_shared_inits)
{
constexpr size_t num_ignored_arguments = sizeof...(Types);
auto g = multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor<num_ignored_arguments, Function>{f};
return ex.template when_all_execute_and_select<SelectedIndices...>(g, shape, std::forward<TupleOfFutures>(futures), std::get<SharedInitIndices>(ignored_shared_inits)...);
} // end multi_agent_when_all_execute_and_select()
template<size_t... SelectedIndices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<SelectedIndices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function implementation_strategy,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
constexpr size_t depth = new_executor_traits<Executor>::execution_depth;
// create ignored shared initializers
auto ignored_shared_inits = detail::tuple_repeat<depth>(detail::ignore);
return multi_agent_when_all_execute_and_select<SelectedIndices...>(implementation_strategy,
detail::make_index_sequence<depth>(),
ex, f, shape, std::forward<TupleOfFutures>(futures), ignored_shared_inits);
} // end multi_agent_when_all_execute_and_select()
template<class Executor, class Function>
struct multi_agent_when_all_execute_and_select_functor_using_nested_execute
{
Executor& ex;
mutable Function f;
typename new_executor_traits<Executor>::shape_type shape;
template<class... Args>
struct inner_functor
{
mutable Function f;
mutable detail::tuple<Args&...> args;
template<size_t... TupleIndices, class Index>
__AGENCY_ANNOTATION
void impl(detail::index_sequence<TupleIndices...>, const Index& idx) const
{
agency::invoke(f, idx, std::get<TupleIndices>(args)...);
}
template<class Index>
__AGENCY_ANNOTATION
void operator()(const Index& idx) const
{
impl(detail::make_index_sequence<sizeof...(Args)>(), idx);
}
};
template<class... Args>
__AGENCY_ANNOTATION
void operator()(Args&... args) const
{
new_executor_traits<Executor>::execute(ex, inner_functor<Args...>{f, detail::tie(args...)}, shape);
}
};
template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<Indices...>,
typename std::decay<TupleOfFutures>::type
>
>
multi_agent_when_all_execute_and_select(use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute,
Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
return new_executor_traits<Executor>::template when_all_execute_and_select<Indices...>(ex, multi_agent_when_all_execute_and_select_functor_using_nested_execute<Executor,Function>{ex,f,shape}, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()
} // end multi_agent_when_all_execute_and_select_implementation_strategies
} // end new_executor_traits_detail
} // end detail
template<class Executor>
template<size_t... Indices, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
detail::when_all_execute_and_select_result_t<
detail::index_sequence<Indices...>,
typename std::decay<TupleOfFutures>::type
>
>
new_executor_traits<Executor>
::when_all_execute_and_select(typename new_executor_traits<Executor>::executor_type& ex,
Function f,
typename new_executor_traits<Executor>::shape_type shape,
TupleOfFutures&& futures)
{
namespace ns = detail::new_executor_traits_detail::multi_agent_when_all_execute_and_select_implementation_strategies;
using implementation_strategy = ns::select_multi_agent_when_all_execute_and_select_implementation<
Executor,
Function,
typename std::decay<TupleOfFutures>::type,
Indices...
>;
return ns::multi_agent_when_all_execute_and_select<Indices...>(implementation_strategy(), ex, f, shape, std::forward<TupleOfFutures>(futures));
} // end new_executor_traits::when_all_execute_and_select()
} // end agency
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: oslfile2streamwrap.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 22:53:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_
#include <comphelper/oslfile2streamwrap.hxx>
#endif
#include <algorithm>
namespace comphelper
{
using namespace osl;
//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File& _rFile )
:m_pFile(&_rFile)
,m_bFileOwner(sal_False)
{
}
//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File* pStream, sal_Bool bOwner )
:m_pFile( pStream )
,m_bFileOwner( bOwner )
{
}
//------------------------------------------------------------------
OSLInputStreamWrapper::~OSLInputStreamWrapper()
{
if( m_bFileOwner )
delete m_pFile;
}
//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead)
throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
if (nBytesToRead < 0)
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
::osl::MutexGuard aGuard( m_aMutex );
aData.realloc(nBytesToRead);
sal_uInt64 nRead = 0;
FileBase::RC eError = m_pFile->read((void*)aData.getArray(), nBytesToRead, nRead);
if (eError != FileBase::E_None)
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
// Wenn gelesene Zeichen < MaxLength, staruno::Sequence anpassen
if (nRead < (sal_uInt32)nBytesToRead)
aData.realloc( sal::static_int_cast< sal_Int32 >(nRead) );
return sal::static_int_cast< sal_Int32 >(nRead);
}
//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readSomeBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
if (nMaxBytesToRead < 0)
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
/*
if (m_pFile->IsEof())
{
aData.realloc(0);
return 0;
}
else
*/
return readBytes(aData, nMaxBytesToRead);
}
//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::skipBytes(sal_Int32 nBytesToSkip) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
sal_uInt64 nCurrentPos;
m_pFile->getPos(nCurrentPos);
sal_uInt64 nNewPos = nCurrentPos + nBytesToSkip;
FileBase::RC eError = m_pFile->setPos(osl_Pos_Absolut, nNewPos);
if (eError != FileBase::E_None)
{
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
}
#ifdef DBG_UTIL
m_pFile->getPos(nCurrentPos);
// volatile int dummy = 0; // to take a look at last changes ;-)
#endif
}
//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::available() throw( stario::NotConnectedException, staruno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
sal_uInt64 nPos;
FileBase::RC eError = m_pFile->getPos(nPos);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
sal_uInt64 nDummy = 0;
eError = m_pFile->setPos(Pos_End, nDummy);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
sal_uInt64 nAvailable;
eError = m_pFile->getPos(nAvailable);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
nAvailable = nAvailable - nPos;
eError = m_pFile->setPos(Pos_Absolut, nPos);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
return sal::static_int_cast< sal_Int32 >(
std::max(nAvailable, sal::static_int_cast< sal_uInt64 >(SAL_MAX_INT32)));
}
//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::closeInput() throw( stario::NotConnectedException, staruno::RuntimeException )
{
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
m_pFile->close();
if (m_bFileOwner)
delete m_pFile;
m_pFile = NULL;
}
/*************************************************************************/
// stario::XOutputStream
//------------------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::writeBytes(const staruno::Sequence< sal_Int8 >& aData) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
sal_uInt64 nWritten;
FileBase::RC eError = rFile.write(aData.getConstArray(),aData.getLength(), nWritten);
if (eError != FileBase::E_None
|| nWritten != sal::static_int_cast< sal_uInt32 >(aData.getLength()))
{
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
}
}
//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::flush() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
}
//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::closeOutput() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
rFile.close();
}
} // namespace comphelper
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.36); FILE MERGED 2006/09/01 17:19:49 kaib 1.3.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: oslfile2streamwrap.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 17:20:34 $
*
* 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_comphelper.hxx"
#ifndef _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_
#include <comphelper/oslfile2streamwrap.hxx>
#endif
#include <algorithm>
namespace comphelper
{
using namespace osl;
//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File& _rFile )
:m_pFile(&_rFile)
,m_bFileOwner(sal_False)
{
}
//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File* pStream, sal_Bool bOwner )
:m_pFile( pStream )
,m_bFileOwner( bOwner )
{
}
//------------------------------------------------------------------
OSLInputStreamWrapper::~OSLInputStreamWrapper()
{
if( m_bFileOwner )
delete m_pFile;
}
//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead)
throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
if (nBytesToRead < 0)
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
::osl::MutexGuard aGuard( m_aMutex );
aData.realloc(nBytesToRead);
sal_uInt64 nRead = 0;
FileBase::RC eError = m_pFile->read((void*)aData.getArray(), nBytesToRead, nRead);
if (eError != FileBase::E_None)
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
// Wenn gelesene Zeichen < MaxLength, staruno::Sequence anpassen
if (nRead < (sal_uInt32)nBytesToRead)
aData.realloc( sal::static_int_cast< sal_Int32 >(nRead) );
return sal::static_int_cast< sal_Int32 >(nRead);
}
//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readSomeBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
if (nMaxBytesToRead < 0)
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
/*
if (m_pFile->IsEof())
{
aData.realloc(0);
return 0;
}
else
*/
return readBytes(aData, nMaxBytesToRead);
}
//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::skipBytes(sal_Int32 nBytesToSkip) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
sal_uInt64 nCurrentPos;
m_pFile->getPos(nCurrentPos);
sal_uInt64 nNewPos = nCurrentPos + nBytesToSkip;
FileBase::RC eError = m_pFile->setPos(osl_Pos_Absolut, nNewPos);
if (eError != FileBase::E_None)
{
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
}
#ifdef DBG_UTIL
m_pFile->getPos(nCurrentPos);
// volatile int dummy = 0; // to take a look at last changes ;-)
#endif
}
//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::available() throw( stario::NotConnectedException, staruno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
sal_uInt64 nPos;
FileBase::RC eError = m_pFile->getPos(nPos);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
sal_uInt64 nDummy = 0;
eError = m_pFile->setPos(Pos_End, nDummy);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
sal_uInt64 nAvailable;
eError = m_pFile->getPos(nAvailable);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
nAvailable = nAvailable - nPos;
eError = m_pFile->setPos(Pos_Absolut, nPos);
if (eError != FileBase::E_None)
throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
return sal::static_int_cast< sal_Int32 >(
std::max(nAvailable, sal::static_int_cast< sal_uInt64 >(SAL_MAX_INT32)));
}
//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::closeInput() throw( stario::NotConnectedException, staruno::RuntimeException )
{
if (!m_pFile)
throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
m_pFile->close();
if (m_bFileOwner)
delete m_pFile;
m_pFile = NULL;
}
/*************************************************************************/
// stario::XOutputStream
//------------------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::writeBytes(const staruno::Sequence< sal_Int8 >& aData) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
sal_uInt64 nWritten;
FileBase::RC eError = rFile.write(aData.getConstArray(),aData.getLength(), nWritten);
if (eError != FileBase::E_None
|| nWritten != sal::static_int_cast< sal_uInt32 >(aData.getLength()))
{
throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
}
}
//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::flush() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
}
//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::closeOutput() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
rFile.close();
}
} // namespace comphelper
<|endoftext|> |
<commit_before>#ifndef PYTHONMULTIMAPPING_INL
#define PYTHONMULTIMAPPING_INL
#include "PythonMultiMapping.h"
namespace sofa {
namespace component {
namespace mapping {
template<class TIn, class TOut>
PythonMultiMapping<TIn, TOut>::PythonMultiMapping() :
matrix(initData(&matrix, "jacobian", "jacobian for the mapping (row-major)")),
value(initData(&value, "value", "mapping value")),
gs_matrix(initData(&gs_matrix, "geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
use_gs(initData(&use_gs, true, "use_geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
out_force(initData(&out_force, "out_force", "output force used to compute geometric stiffness (read-only)")) {
}
template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble_geometric( const helper::vector<typename self::in_pos_type>& in,
const typename self::const_out_deriv_type& out) {
if(use_gs.getValue()) {
// copy force in data
set(out_force) = out.ref();
// std::cout << "c++ out_force: " << set(out_force) << std::endl;
// hand over to python
if(this->py_callback) {
this->py_callback( gs_state );
}
// assemble sparse jacobian from data
unsigned rows = 0;
for(unsigned i = 0, n = in.size(); i < n; ++i) {
rows += this->from(i)->getMatrixSize();
}
typedef typename self::geometric_type::CompressedMatrix gs_type;
gs_type& dJ = this->geometric.compressedMatrix;
dJ.resize(rows, rows);
dJ.setZero();
const unsigned size = rows * rows;
const matrix_type& gs = gs_matrix.getValue();
if( gs.size() != size ) {
if( gs.size() ) {
serr << "assemble: incorrect geometric stiffness size, treating as zero";
}
return;
}
for(unsigned i = 0; i < rows; ++i) {
dJ.startVec(i);
for(unsigned j = 0; j < rows; ++j) {
const SReal value = gs[ rows * i + j];
if(value ) dJ.insertBack(i, j) = value;
}
}
dJ.finalize();
// std::cout << "c++ dJT" << std::endl
// << dJ << std::endl;
}
}
template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble( const helper::vector<typename self::in_pos_type>& in ) {
// initialize jacobians
const value_type& value = this->value.getValue();
const matrix_type& matrix = this->matrix.getValue();
typedef typename self::jacobian_type::CompressedMatrix block_type;
// resize jacobian blocks
unsigned size = 0;
const unsigned rows = value.size() * out_deriv_size;
for(unsigned j = 0, m = in.size(); j < m; ++j) {
block_type& block = this->jacobian(j).compressedMatrix;
const unsigned cols = this->from(j)->getMatrixSize();
block.resize(rows, cols);
block.setZero();
size += rows * cols;
}
if(matrix.size() != size) {
// note: empty 'jacobian' will be silently treated as zero
if( matrix.size() ) {
serr << "assemble: incorrect jacobian size, treating as zero" << sendl;
}
return;
}
// each out dof
unsigned off = 0;
// each output mstate
for(unsigned i = 0, n = value.size(); i < n; ++i) {
for(unsigned v = 0; v < out_deriv_size; ++v) {
// each input mstate
for(unsigned j = 0, m = in.size(); j < m; ++j) {
block_type& block = this->jacobian(j).compressedMatrix;
const unsigned dim = this->from(j)->getMatrixSize();
const unsigned r = out_deriv_size * i + v;
block.startVec(r);
// each input mstate dof
for(unsigned k = 0, p = in[j].size(); k < p; ++k) {
// each dof dimension
for(unsigned u = 0; u < in_deriv_size; ++u) {
const unsigned c = k * in_deriv_size + u;
const SReal value = matrix[off + c];
if( value ) block.insertBack(r, c) = value;
}
}
off += dim;
}
}
}
assert( off == matrix.size() );
// each input mstate
for(unsigned j = 0, m = in.size(); j < m; ++j) {
block_type& block = this->jacobian(j).compressedMatrix;
block.finalize();
}
}
template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::apply(typename self::out_pos_type& out,
const helper::vector<typename self::in_pos_type>& /*in*/ ){
if(this->py_callback) {
this->py_callback( apply_state );
}
const value_type& value = this->value.getValue();
if( out.size() != value.size() ) {
serr << "apply: size for data 'value' does not match output, auto-resizing" << sendl;
const_cast<value_type&>(value).resize( out.size() );
}
for(unsigned i = 0, n = out.size(); i < n; ++i) {
out[i] = value[i];
}
}
}
}
}
#endif
<commit_msg>[Compliant] some debug info in python mappings<commit_after>#ifndef PYTHONMULTIMAPPING_INL
#define PYTHONMULTIMAPPING_INL
#include "PythonMultiMapping.h"
namespace sofa {
namespace component {
namespace mapping {
template<class TIn, class TOut>
PythonMultiMapping<TIn, TOut>::PythonMultiMapping() :
matrix(initData(&matrix, "jacobian", "jacobian for the mapping (row-major)")),
value(initData(&value, "value", "mapping value")),
gs_matrix(initData(&gs_matrix, "geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
use_gs(initData(&use_gs, true, "use_geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
out_force(initData(&out_force, "out_force", "output force used to compute geometric stiffness (read-only)")) {
}
template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble_geometric( const helper::vector<typename self::in_pos_type>& in,
const typename self::const_out_deriv_type& out) {
if(use_gs.getValue()) {
// copy force in data
set(out_force) = out.ref();
// std::cout << "c++ out_force: " << set(out_force) << std::endl;
// hand over to python
if(this->py_callback) {
this->py_callback( gs_state );
}
// assemble sparse jacobian from data
unsigned rows = 0;
for(unsigned i = 0, n = in.size(); i < n; ++i) {
rows += this->from(i)->getMatrixSize();
}
typedef typename self::geometric_type::CompressedMatrix gs_type;
gs_type& dJ = this->geometric.compressedMatrix;
dJ.resize(rows, rows);
dJ.setZero();
const unsigned size = rows * rows;
const matrix_type& gs = gs_matrix.getValue();
if( gs.size() != size ) {
if( gs.size() ) {
serr << "assemble: incorrect geometric stiffness size, treating as zero";
}
return;
}
for(unsigned i = 0; i < rows; ++i) {
dJ.startVec(i);
for(unsigned j = 0; j < rows; ++j) {
const SReal value = gs[ rows * i + j];
if(value ) dJ.insertBack(i, j) = value;
}
}
dJ.finalize();
// std::cout << "c++ dJT" << std::endl
// << dJ << std::endl;
}
}
template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble( const helper::vector<typename self::in_pos_type>& in ) {
// initialize jacobians
const value_type& value = this->value.getValue();
const matrix_type& matrix = this->matrix.getValue();
typedef typename self::jacobian_type::CompressedMatrix block_type;
// resize jacobian blocks
unsigned size = 0;
const unsigned rows = value.size() * out_deriv_size;
for(unsigned j = 0, m = in.size(); j < m; ++j) {
block_type& block = this->jacobian(j).compressedMatrix;
const unsigned cols = this->from(j)->getMatrixSize();
block.resize(rows, cols);
block.setZero();
size += rows * cols;
}
if(matrix.size() != size) {
// note: empty 'jacobian' will be silently treated as zero
if( matrix.size() ) {
serr << "assemble: incorrect jacobian size, treating as zero (solve *will* fail !)"
<< sendl;
}
return;
}
// each out dof
unsigned off = 0;
unsigned nnz = 0;
// each output mstate
for(unsigned i = 0, n = value.size(); i < n; ++i) {
for(unsigned v = 0; v < out_deriv_size; ++v) {
// each input mstate
for(unsigned j = 0, m = in.size(); j < m; ++j) {
block_type& block = this->jacobian(j).compressedMatrix;
const unsigned dim = this->from(j)->getMatrixSize();
const unsigned r = out_deriv_size * i + v;
block.startVec(r);
// each input mstate dof
for(unsigned k = 0, p = in[j].size(); k < p; ++k) {
// each dof dimension
for(unsigned u = 0; u < in_deriv_size; ++u) {
const unsigned c = k * in_deriv_size + u;
const SReal value = matrix[off + c];
if( value ) {
block.insertBack(r, c) = value;
++nnz;
}
}
}
off += dim;
}
}
}
assert( off == matrix.size() );
if(!nnz) {
serr << "assemble: zero jacobian, solve *will* fail !" << sendl;
}
// each input mstate
for(unsigned j = 0, m = in.size(); j < m; ++j) {
block_type& block = this->jacobian(j).compressedMatrix;
block.finalize();
}
}
template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::apply(typename self::out_pos_type& out,
const helper::vector<typename self::in_pos_type>& /*in*/ ){
if(this->py_callback) {
this->py_callback( apply_state );
}
const value_type& value = this->value.getValue();
if( out.size() != value.size() ) {
serr << "apply: size for data 'value' does not match output, auto-resizing" << sendl;
const_cast<value_type&>(value).resize( out.size() );
}
for(unsigned i = 0, n = out.size(); i < n; ++i) {
out[i] = value[i];
}
}
}
}
}
#endif
<|endoftext|> |
<commit_before>//
// Created by everettjf on 2017/7/5.
//
#include "CommonDisplay.h"
#include <iostream>
#include "../util/Utility.h"
#include <libmoex/node/loadcommand.h>
using namespace std;
bool CommonDisplay::Init(const std::string & filepath,bool is_csv){
print_ = BeautyTextPrinterFactory::CreatePrinter(is_csv);
try{
bin_ = std::make_shared<moex::Binary>(filepath);
}catch(std::exception & ex){
cout << "Parse failed : " << ex.what() <<endl;
return false;
}
return true;
}
void CommonDisplay::ForEachHeader(std::function<void(moex::MachHeaderPtr)> callback){
bin_->ForEachHeader([&](moex::MachHeaderPtr header) {
std::string arch = moex::hp::GetArchStringFromCpuType(header->data_ptr()->cputype);
if(!arch_.empty() && arch != arch_)
return;
callback(header);
});
}
void CommonDisplay::IsFat(){
cout << (bin_->IsFat() ? "true" : "false") <<endl;
}
void CommonDisplay::FatList(){
if(!bin_->IsFat())
return;
print_->SetHeaders({"cputype","cpusubtype","offset","size","align"});
print_->SetWidths({15,14,10,10,10});
print_->Begin();
for(auto & arch : bin_->fath()->archs()){
const fat_arch & f = arch->data();
print_->AddRow({
moex::hp::GetCpuTypeString(f.cputype),
moex::hp::GetCpuSubTypeString(f.cpusubtype),
ToString(f.offset),
ToString(f.size),
ToString(f.align),
});
}
print_->End();
}
void CommonDisplay::HeaderList(){
print_->SetHeaders({"magic","cputype","cpusubtype","ncmds","sizeofcmds","flags"});
print_->SetWidths({10,15,14,10,10,10});
print_->Begin();
bin_->ForEachHeader([&](moex::MachHeaderPtr header){
mach_header *h = header->data_ptr();
print_->AddRow({
ToString(h->magic),
moex::hp::GetCpuTypeString(h->cputype),
moex::hp::GetCpuSubTypeString(h->cpusubtype),
ToString(h->ncmds),
ToString(h->sizeofcmds),
ToString(h->flags),
});
});
print_->End();
}
void CommonDisplay::ArchList(){
print_->SetHeaders({"arch"});
print_->SetWidths({10});
print_->Begin();
bin_->ForEachHeader([&](moex::MachHeaderPtr header){
mach_header *h = header->data_ptr();
print_->AddRow({
moex::hp::GetArchStringFromCpuType(h->cputype)
});
});
print_->End();
}
void CommonDisplay::LoadCommandList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + "/ cmd","cmdsize","cmdtype","description"});
print_->SetWidths({20,10,25,130});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
print_->AddRow({
ToString(cmd->offset()->cmd),
ToString(cmd->offset()->cmdsize),
cmd->GetTypeName(),
cmd->GetDescription()
});
}
print_->End();
cout << endl;
});
}
void CommonDisplay::SegmentList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + " / cmd","cmdsize","segname","vmaddr","vmsize",
"fileoff","filesize","maxprot","initprot","nsects",
"flags","cmdtype"});
print_->SetWidths({10,10,20,15,15,
10,10,10,10,10,
10,20});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
if(cmd->offset()->cmd == LC_SEGMENT) {
moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
print_->AddRow({
ToString(seg->cmd()->cmd),
ToString(seg->cmd()->cmdsize),
seg->segment_name(),
ToString(seg->cmd()->vmaddr),
ToString(seg->cmd()->vmsize),
ToString(seg->cmd()->fileoff),
ToString(seg->cmd()->filesize),
ToString(seg->cmd()->maxprot),
ToString(seg->cmd()->initprot),
ToString(seg->cmd()->nsects),
ToString(seg->cmd()->flags),
seg->GetTypeName(),
});
}else if(cmd->offset()->cmd == LC_SEGMENT_64) {
moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
print_->AddRow({
ToString(seg->cmd()->cmd),
ToString(seg->cmd()->cmdsize),
seg->segment_name(),
ToString(seg->cmd()->vmaddr),
ToString(seg->cmd()->vmsize),
ToString(seg->cmd()->fileoff),
ToString(seg->cmd()->filesize),
ToString(seg->cmd()->maxprot),
ToString(seg->cmd()->initprot),
ToString(seg->cmd()->nsects),
ToString(seg->cmd()->flags),
seg->GetTypeName(),
});
}
}
print_->End();
});
}
void CommonDisplay::SectionList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + " / section","segment","addr","size","offset",
"align","reloff","nreloc","flags"});
print_->SetWidths({20,15,10,10,10,
10,10,10,10});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
if(cmd->offset()->cmd == LC_SEGMENT) {
moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
for(auto sect : seg->sections_ref()){
print_->AddRow({
sect->section_name(),
sect->segment_name(),
ToString(sect->offset()->addr),
ToString(sect->offset()->size),
ToString(sect->offset()->offset),
ToString(sect->offset()->align),
ToString(sect->offset()->reloff),
ToString(sect->offset()->nreloc),
ToString(sect->offset()->flags),
});
}
}else if(cmd->offset()->cmd == LC_SEGMENT_64) {
moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
for(auto sect : seg->sections_ref()){
print_->AddRow({
sect->section_name(),
sect->segment_name(),
ToString(sect->offset()->addr),
ToString(sect->offset()->size),
ToString(sect->offset()->offset),
ToString(sect->offset()->align),
ToString(sect->offset()->reloff),
ToString(sect->offset()->nreloc),
ToString(sect->offset()->flags),
});
}
}
}
print_->End();
});
}
void CommonDisplay::SymbolList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + " / strx","type","sect","desc"});
print_->SetWidths({20,15,10,10});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
if(cmd->offset()->cmd == LC_SYMTAB) {
moex::LoadCommand_LC_SYMTAB *seg = static_cast<moex::LoadCommand_LC_SYMTAB*>(cmd.get());
if(seg->is64()){
for(auto & item : seg->nlist64s_ref()){
print_->AddRow({
ToString(item->offset()->n_un.n_strx),
ToString(item->offset()->n_type),
ToString(item->offset()->n_sect),
ToString(item->offset()->n_desc)
});
}
}else{
for(auto & item : seg->nlists_ref()){
print_->AddRow({
ToString(item->offset()->n_un.n_strx),
ToString(item->offset()->n_type),
ToString(item->offset()->n_sect),
ToString(item->offset()->n_desc)
});
}
}
}
}
print_->End();
});
}
<commit_msg>n_value<commit_after>//
// Created by everettjf on 2017/7/5.
//
#include "CommonDisplay.h"
#include <iostream>
#include "../util/Utility.h"
#include <libmoex/node/loadcommand.h>
using namespace std;
bool CommonDisplay::Init(const std::string & filepath,bool is_csv){
print_ = BeautyTextPrinterFactory::CreatePrinter(is_csv);
try{
bin_ = std::make_shared<moex::Binary>(filepath);
}catch(std::exception & ex){
cout << "Parse failed : " << ex.what() <<endl;
return false;
}
return true;
}
void CommonDisplay::ForEachHeader(std::function<void(moex::MachHeaderPtr)> callback){
bin_->ForEachHeader([&](moex::MachHeaderPtr header) {
std::string arch = moex::hp::GetArchStringFromCpuType(header->data_ptr()->cputype);
if(!arch_.empty() && arch != arch_)
return;
callback(header);
});
}
void CommonDisplay::IsFat(){
cout << (bin_->IsFat() ? "true" : "false") <<endl;
}
void CommonDisplay::FatList(){
if(!bin_->IsFat())
return;
print_->SetHeaders({"cputype","cpusubtype","offset","size","align"});
print_->SetWidths({15,14,10,10,10});
print_->Begin();
for(auto & arch : bin_->fath()->archs()){
const fat_arch & f = arch->data();
print_->AddRow({
moex::hp::GetCpuTypeString(f.cputype),
moex::hp::GetCpuSubTypeString(f.cpusubtype),
ToString(f.offset),
ToString(f.size),
ToString(f.align),
});
}
print_->End();
}
void CommonDisplay::HeaderList(){
print_->SetHeaders({"magic","cputype","cpusubtype","ncmds","sizeofcmds","flags"});
print_->SetWidths({10,15,14,10,10,10});
print_->Begin();
bin_->ForEachHeader([&](moex::MachHeaderPtr header){
mach_header *h = header->data_ptr();
print_->AddRow({
ToString(h->magic),
moex::hp::GetCpuTypeString(h->cputype),
moex::hp::GetCpuSubTypeString(h->cpusubtype),
ToString(h->ncmds),
ToString(h->sizeofcmds),
ToString(h->flags),
});
});
print_->End();
}
void CommonDisplay::ArchList(){
print_->SetHeaders({"arch"});
print_->SetWidths({10});
print_->Begin();
bin_->ForEachHeader([&](moex::MachHeaderPtr header){
mach_header *h = header->data_ptr();
print_->AddRow({
moex::hp::GetArchStringFromCpuType(h->cputype)
});
});
print_->End();
}
void CommonDisplay::LoadCommandList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + "/ cmd","cmdsize","cmdtype","description"});
print_->SetWidths({20,10,25,130});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
print_->AddRow({
ToString(cmd->offset()->cmd),
ToString(cmd->offset()->cmdsize),
cmd->GetTypeName(),
cmd->GetDescription()
});
}
print_->End();
cout << endl;
});
}
void CommonDisplay::SegmentList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + " / cmd","cmdsize","segname","vmaddr","vmsize",
"fileoff","filesize","maxprot","initprot","nsects",
"flags","cmdtype"});
print_->SetWidths({10,10,20,15,15,
10,10,10,10,10,
10,20});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
if(cmd->offset()->cmd == LC_SEGMENT) {
moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
print_->AddRow({
ToString(seg->cmd()->cmd),
ToString(seg->cmd()->cmdsize),
seg->segment_name(),
ToString(seg->cmd()->vmaddr),
ToString(seg->cmd()->vmsize),
ToString(seg->cmd()->fileoff),
ToString(seg->cmd()->filesize),
ToString(seg->cmd()->maxprot),
ToString(seg->cmd()->initprot),
ToString(seg->cmd()->nsects),
ToString(seg->cmd()->flags),
seg->GetTypeName(),
});
}else if(cmd->offset()->cmd == LC_SEGMENT_64) {
moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
print_->AddRow({
ToString(seg->cmd()->cmd),
ToString(seg->cmd()->cmdsize),
seg->segment_name(),
ToString(seg->cmd()->vmaddr),
ToString(seg->cmd()->vmsize),
ToString(seg->cmd()->fileoff),
ToString(seg->cmd()->filesize),
ToString(seg->cmd()->maxprot),
ToString(seg->cmd()->initprot),
ToString(seg->cmd()->nsects),
ToString(seg->cmd()->flags),
seg->GetTypeName(),
});
}
}
print_->End();
});
}
void CommonDisplay::SectionList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + " / section","segment","addr","size","offset",
"align","reloff","nreloc","flags"});
print_->SetWidths({20,15,10,10,10,
10,10,10,10});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
if(cmd->offset()->cmd == LC_SEGMENT) {
moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
for(auto & sect : seg->sections_ref()){
print_->AddRow({
sect->section_name(),
sect->segment_name(),
ToString(sect->offset()->addr),
ToString(sect->offset()->size),
ToString(sect->offset()->offset),
ToString(sect->offset()->align),
ToString(sect->offset()->reloff),
ToString(sect->offset()->nreloc),
ToString(sect->offset()->flags),
});
}
}else if(cmd->offset()->cmd == LC_SEGMENT_64) {
moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
for(auto & sect : seg->sections_ref()){
print_->AddRow({
sect->section_name(),
sect->segment_name(),
ToString(sect->offset()->addr),
ToString(sect->offset()->size),
ToString(sect->offset()->offset),
ToString(sect->offset()->align),
ToString(sect->offset()->reloff),
ToString(sect->offset()->nreloc),
ToString(sect->offset()->flags),
});
}
}
}
print_->End();
});
}
void CommonDisplay::SymbolList(){
ForEachHeader([&](moex::MachHeaderPtr header){
print_->SetHeaders({header->GetArch() + " / strx","type","sect","desc","value"});
print_->SetWidths({20,15,10,10,10});
print_->Begin();
for(auto cmd : header->loadcmds_ref()){
if(cmd->offset()->cmd == LC_SYMTAB) {
moex::LoadCommand_LC_SYMTAB *seg = static_cast<moex::LoadCommand_LC_SYMTAB*>(cmd.get());
if(seg->is64()){
for(auto & item : seg->nlist64s_ref()){
print_->AddRow({
ToString(item->offset()->n_un.n_strx),
ToString(item->offset()->n_type),
ToString(item->offset()->n_sect),
ToString(item->offset()->n_desc),
ToString(item->offset()->n_value)
});
}
}else{
for(auto & item : seg->nlists_ref()){
print_->AddRow({
ToString(item->offset()->n_un.n_strx),
ToString(item->offset()->n_type),
ToString(item->offset()->n_sect),
ToString(item->offset()->n_desc),
ToString(item->offset()->n_value)
});
}
}
}
}
print_->End();
});
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planner/em/em_planner.h"
#include <fstream>
#include <utility>
#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/planning/common/data_center.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/em_planning_data.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
namespace apollo {
namespace planning {
using apollo::common::TrajectoryPoint;
using apollo::common::vehicle_state::VehicleState;
EMPlanner::EMPlanner() {}
bool EMPlanner::MakePlan(const TrajectoryPoint& start_point,
std::vector<TrajectoryPoint>* discretized_trajectory) {
DataCenter* data_center = DataCenter::instance();
// Frame* frame = data_center->current_frame();
frame->set_planning_data(new EMPlanningData());
// frame->mutable_planning_data()->set_reference_line(reference_line);
// frame->mutable_planning_data()->set_decision_data(decision_data);
// frame->mutable_planning_data()->set_init_planning_point(
// frame->environment().vehicle_state_proxy().init_point(data_center->last_frame()));
return true;
}
std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
const double init_v, const double init_a) {
// TODO(@lianglia_apollo): this is a dummy simple hot start, need refine later
std::array<double, 3> start_state;
// distance 0.0
start_state[0] = 0.0;
// start velocity
start_state[1] = init_v;
// start acceleration
start_state[2] = init_a;
std::array<double, 2> end_state;
// end state velocity
end_state[0] = 10.0;
// end state acceleration
end_state[1] = 0.0;
// pre assume the curve time is 8 second, can be change later
QuarticPolynomialCurve1d speed_curve(start_state, end_state,
FLAGS_trajectory_time_length);
// assume the time resolution is 0.1
std::size_t num_time_steps =
static_cast<std::size_t>(FLAGS_trajectory_time_length /
FLAGS_trajectory_time_resolution) +
1;
std::vector<SpeedPoint> speed_profile;
speed_profile.reserve(num_time_steps);
for (std::size_t i = 0; i < num_time_steps; ++i) {
double t = i * FLAGS_trajectory_time_resolution;
double s = speed_curve.evaluate(0, t);
double v = speed_curve.evaluate(1, t);
double a = speed_curve.evaluate(2, t);
double da = speed_curve.evaluate(3, t);
SpeedPoint speed_point;
speed_point.mutable_st_point()->set_s(s);
speed_point.mutable_st_point()->set_t(t);
speed_point.set_v(v);
speed_point.set_a(a);
speed_point.set_da(da);
speed_profile.push_back(speed_point);
}
return std::move(speed_profile);
}
} // namespace planning
} // namespace apollo
<commit_msg>fix typo.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planner/em/em_planner.h"
#include <fstream>
#include <utility>
#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/planning/common/data_center.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/em_planning_data.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
namespace apollo {
namespace planning {
using apollo::common::TrajectoryPoint;
using apollo::common::vehicle_state::VehicleState;
EMPlanner::EMPlanner() {}
bool EMPlanner::MakePlan(const TrajectoryPoint& start_point,
std::vector<TrajectoryPoint>* discretized_trajectory) {
DataCenter* data_center = DataCenter::instance();
Frame* frame = data_center->current_frame();
frame->set_planning_data(new EMPlanningData());
// frame->mutable_planning_data()->set_reference_line(reference_line);
// frame->mutable_planning_data()->set_decision_data(decision_data);
// frame->mutable_planning_data()->set_init_planning_point(
// frame->environment().vehicle_state_proxy().init_point(data_center->last_frame()));
return true;
}
std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
const double init_v, const double init_a) {
// TODO(@lianglia_apollo): this is a dummy simple hot start, need refine later
std::array<double, 3> start_state;
// distance 0.0
start_state[0] = 0.0;
// start velocity
start_state[1] = init_v;
// start acceleration
start_state[2] = init_a;
std::array<double, 2> end_state;
// end state velocity
end_state[0] = 10.0;
// end state acceleration
end_state[1] = 0.0;
// pre assume the curve time is 8 second, can be change later
QuarticPolynomialCurve1d speed_curve(start_state, end_state,
FLAGS_trajectory_time_length);
// assume the time resolution is 0.1
std::size_t num_time_steps =
static_cast<std::size_t>(FLAGS_trajectory_time_length /
FLAGS_trajectory_time_resolution) +
1;
std::vector<SpeedPoint> speed_profile;
speed_profile.reserve(num_time_steps);
for (std::size_t i = 0; i < num_time_steps; ++i) {
double t = i * FLAGS_trajectory_time_resolution;
double s = speed_curve.evaluate(0, t);
double v = speed_curve.evaluate(1, t);
double a = speed_curve.evaluate(2, t);
double da = speed_curve.evaluate(3, t);
SpeedPoint speed_point;
speed_point.mutable_st_point()->set_s(s);
speed_point.mutable_st_point()->set_t(t);
speed_point.set_v(v);
speed_point.set_a(a);
speed_point.set_da(da);
speed_profile.push_back(speed_point);
}
return std::move(speed_profile);
}
} // namespace planning
} // namespace apollo
<|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 <BufferedStreamSocket.hxx>
#include <algorithm>
#ifdef WIN32
// LO vs WinAPI conflict
#undef WB_LEFT
#undef WB_RIGHT
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <unistd.h>
#endif
using namespace sd;
using namespace std;
using namespace osl;
BufferedStreamSocket::BufferedStreamSocket( const osl::StreamSocket &aSocket ):
StreamSocket( aSocket ),
aRet( 0 ),
aRead( 0 ),
aBuffer(),
mSocket( 0 ),
usingCSocket( false )
{
}
BufferedStreamSocket::BufferedStreamSocket( int aSocket ):
StreamSocket(),
aRet( 0 ),
aRead( 0 ),
aBuffer(),
mSocket( aSocket ),
usingCSocket( true )
{
}
void BufferedStreamSocket::getPeerAddr(osl::SocketAddr& rAddr)
{
assert ( !usingCSocket );
StreamSocket::getPeerAddr( rAddr );
}
sal_Int32 BufferedStreamSocket::write( const void* pBuffer, sal_uInt32 n )
{
if ( !usingCSocket )
return StreamSocket::write( pBuffer, n );
else
return ::send(
mSocket,
#if defined WNT
static_cast<char *>(pBuffer),
#else
pBuffer,
#endif
(size_t) n, 0 );
}
void BufferedStreamSocket::close()
{
if( usingCSocket && mSocket != -1 )
{
#ifdef WIN32
::closesocket( mSocket );
#else
::close( mSocket );
#endif
mSocket = -1;
}
else
::osl::StreamSocket::close();
}
sal_Int32 BufferedStreamSocket::readLine( OString& aLine )
{
while ( true )
{
// Process buffer first incase data already present.
vector<char>::iterator aIt;
if ( (aIt = find( aBuffer.begin(), aBuffer.end(), '\n' ))
!= aBuffer.end() )
{
sal_uInt64 aLocation = aIt - aBuffer.begin();
aLine = OString( &(*aBuffer.begin()), aLocation );
aBuffer.erase( aBuffer.begin(), aIt + 1 ); // Also delete the empty line
aRead -= (aLocation + 1);
SAL_INFO( "sdremote.bluetooth", "recv line '" << aLine << "'" );
return aLine.getLength() + 1;
}
// Then try and receive if nothing present
aBuffer.resize( aRead + 100 );
if ( !usingCSocket)
aRet = StreamSocket::recv( &aBuffer[aRead], 100 );
else
aRet = ::recv( mSocket, &aBuffer[aRead], 100, 0 );
SAL_INFO( "sdremote.bluetooth", "recv " << aRet << " aBuffer len " << aBuffer.size() );
if ( aRet <= 0 )
{
return 0;
}
// Prevent buffer from growing massively large.
if ( aRead > MAX_LINE_LENGTH )
{
aBuffer.erase( aBuffer.begin(), aBuffer.end() );
return 0;
}
aRead += aRet;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Missing const<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 <BufferedStreamSocket.hxx>
#include <algorithm>
#ifdef WIN32
// LO vs WinAPI conflict
#undef WB_LEFT
#undef WB_RIGHT
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <unistd.h>
#endif
using namespace sd;
using namespace std;
using namespace osl;
BufferedStreamSocket::BufferedStreamSocket( const osl::StreamSocket &aSocket ):
StreamSocket( aSocket ),
aRet( 0 ),
aRead( 0 ),
aBuffer(),
mSocket( 0 ),
usingCSocket( false )
{
}
BufferedStreamSocket::BufferedStreamSocket( int aSocket ):
StreamSocket(),
aRet( 0 ),
aRead( 0 ),
aBuffer(),
mSocket( aSocket ),
usingCSocket( true )
{
}
void BufferedStreamSocket::getPeerAddr(osl::SocketAddr& rAddr)
{
assert ( !usingCSocket );
StreamSocket::getPeerAddr( rAddr );
}
sal_Int32 BufferedStreamSocket::write( const void* pBuffer, sal_uInt32 n )
{
if ( !usingCSocket )
return StreamSocket::write( pBuffer, n );
else
return ::send(
mSocket,
#if defined WNT
static_cast<char const *>(pBuffer),
#else
pBuffer,
#endif
(size_t) n, 0 );
}
void BufferedStreamSocket::close()
{
if( usingCSocket && mSocket != -1 )
{
#ifdef WIN32
::closesocket( mSocket );
#else
::close( mSocket );
#endif
mSocket = -1;
}
else
::osl::StreamSocket::close();
}
sal_Int32 BufferedStreamSocket::readLine( OString& aLine )
{
while ( true )
{
// Process buffer first incase data already present.
vector<char>::iterator aIt;
if ( (aIt = find( aBuffer.begin(), aBuffer.end(), '\n' ))
!= aBuffer.end() )
{
sal_uInt64 aLocation = aIt - aBuffer.begin();
aLine = OString( &(*aBuffer.begin()), aLocation );
aBuffer.erase( aBuffer.begin(), aIt + 1 ); // Also delete the empty line
aRead -= (aLocation + 1);
SAL_INFO( "sdremote.bluetooth", "recv line '" << aLine << "'" );
return aLine.getLength() + 1;
}
// Then try and receive if nothing present
aBuffer.resize( aRead + 100 );
if ( !usingCSocket)
aRet = StreamSocket::recv( &aBuffer[aRead], 100 );
else
aRet = ::recv( mSocket, &aBuffer[aRead], 100, 0 );
SAL_INFO( "sdremote.bluetooth", "recv " << aRet << " aBuffer len " << aBuffer.size() );
if ( aRet <= 0 )
{
return 0;
}
// Prevent buffer from growing massively large.
if ( aRead > MAX_LINE_LENGTH )
{
aBuffer.erase( aBuffer.begin(), aBuffer.end() );
return 0;
}
aRead += aRet;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|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 "net/base/cert_verifier.h"
#include "base/bind.h"
#include "base/file_path.h"
#include "base/format_macros.h"
#include "base/stringprintf.h"
#include "net/base/cert_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/test_completion_callback.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
void FailTest(int /* result */) {
FAIL();
}
} // namespace;
// Tests a cache hit, which should result in synchronous completion.
TEST(CertVerifierTest, CacheHit) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(1u, verifier.GetCacheSize());
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
// Synchronous completion.
ASSERT_NE(ERR_IO_PENDING, error);
ASSERT_TRUE(IsCertificateError(error));
ASSERT_TRUE(request_handle == NULL);
ASSERT_EQ(2u, verifier.requests());
ASSERT_EQ(1u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(1u, verifier.GetCacheSize());
}
// Tests the same server certificate with different intermediate CA
// certificates. These should be treated as different certificate chains even
// though the two X509Certificate objects contain the same server certificate.
TEST(CertVerifierTest, DifferentCACerts) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert);
scoped_refptr<X509Certificate> intermediate_cert1 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert1);
scoped_refptr<X509Certificate> intermediate_cert2 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert2);
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate_cert1->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain1 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
intermediates.clear();
intermediates.push_back(intermediate_cert2->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain2 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(cert_chain1, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(1u, verifier.GetCacheSize());
error = verifier.Verify(cert_chain2, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(2u, verifier.GetCacheSize());
}
// Tests an inflight join.
TEST(CertVerifierTest, InflightJoin) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
CertVerifyResult verify_result2;
TestCompletionCallback callback2;
CertVerifier::RequestHandle request_handle2;
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = verifier.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result2,
callback2.callback(), &request_handle2, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle2 != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
error = callback2.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(1u, verifier.inflight_joins());
}
// Tests that the callback of a canceled request is never made.
TEST(CertVerifierTest, CancelRequest) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result,
base::Bind(&FailTest), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier.CancelRequest(request_handle);
// Issue a few more requests to the worker pool and wait for their
// completion, so that the task of the canceled request (which runs on a
// worker thread) is likely to complete by the end of this test.
TestCompletionCallback callback;
for (int i = 0; i < 5; ++i) {
error = verifier.Verify(
test_cert, "www2.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
verifier.ClearCache();
}
}
// Tests that a canceled request is not leaked.
TEST(CertVerifierTest, CancelRequestThenQuit) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier.CancelRequest(request_handle);
// Destroy |verifier| by going out of scope.
}
TEST(CertVerifierTest, RequestParamsComparators) {
SHA1Fingerprint a_key;
memset(a_key.data, 'a', sizeof(a_key.data));
SHA1Fingerprint z_key;
memset(z_key.data, 'z', sizeof(z_key.data));
struct {
// Keys to test
CertVerifier::RequestParams key1;
CertVerifier::RequestParams key2;
// Expectation:
// -1 means key1 is less than key2
// 0 means key1 equals key2
// 1 means key1 is greater than key2
int expected_result;
} tests[] = {
{ // Test for basic equivalence.
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
0,
},
{ // Test that different certificates but with the same CA and for
// the same host are different validation keys.
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
CertVerifier::RequestParams(z_key, a_key, "www.example.test", 0),
-1,
},
{ // Test that the same EE certificate for the same host, but with
// different chains are different validation keys.
CertVerifier::RequestParams(a_key, z_key, "www.example.test", 0),
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
1,
},
{ // The same certificate, with the same chain, but for different
// hosts are different validation keys.
CertVerifier::RequestParams(a_key, a_key, "www1.example.test", 0),
CertVerifier::RequestParams(a_key, a_key, "www2.example.test", 0),
-1,
},
{ // The same certificate, chain, and host, but with different flags
// are different validation keys.
CertVerifier::RequestParams(a_key, a_key, "www.example.test",
X509Certificate::VERIFY_EV_CERT),
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
1,
}
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));
const CertVerifier::RequestParams& key1 = tests[i].key1;
const CertVerifier::RequestParams& key2 = tests[i].key2;
switch (tests[i].expected_result) {
case -1:
EXPECT_TRUE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 0:
EXPECT_FALSE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 1:
EXPECT_FALSE(key1 < key2);
EXPECT_TRUE(key2 < key1);
break;
default:
FAIL() << "Invalid expectation. Can be only -1, 0, 1";
}
}
}
} // namespace net
<commit_msg>Mark CertVerifierTest.CacheHit test as FAILS_ for Mac OSX.<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 "net/base/cert_verifier.h"
#include "base/bind.h"
#include "base/file_path.h"
#include "base/format_macros.h"
#include "base/stringprintf.h"
#include "net/base/cert_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/test_completion_callback.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
void FailTest(int /* result */) {
FAIL();
}
} // namespace;
// Tests a cache hit, which should result in synchronous completion.
#if defined(OS_MACOSX)
// http://crbug.com/117372
#define MAYBE_CacheHit FAILS_CacheHit
#else
#define MAYBE_CacheHit CacheHit
#endif // defined(OS_MACOSX)
TEST(CertVerifierTest, MAYBE_CacheHit) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(1u, verifier.GetCacheSize());
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
// Synchronous completion.
ASSERT_NE(ERR_IO_PENDING, error);
ASSERT_TRUE(IsCertificateError(error));
ASSERT_TRUE(request_handle == NULL);
ASSERT_EQ(2u, verifier.requests());
ASSERT_EQ(1u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(1u, verifier.GetCacheSize());
}
// Tests the same server certificate with different intermediate CA
// certificates. These should be treated as different certificate chains even
// though the two X509Certificate objects contain the same server certificate.
TEST(CertVerifierTest, DifferentCACerts) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert);
scoped_refptr<X509Certificate> intermediate_cert1 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert1);
scoped_refptr<X509Certificate> intermediate_cert2 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert2);
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate_cert1->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain1 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
intermediates.clear();
intermediates.push_back(intermediate_cert2->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain2 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(cert_chain1, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(1u, verifier.GetCacheSize());
error = verifier.Verify(cert_chain2, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(0u, verifier.inflight_joins());
ASSERT_EQ(2u, verifier.GetCacheSize());
}
// Tests an inflight join.
TEST(CertVerifierTest, InflightJoin) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
CertVerifyResult verify_result2;
TestCompletionCallback callback2;
CertVerifier::RequestHandle request_handle2;
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = verifier.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result2,
callback2.callback(), &request_handle2, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle2 != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
error = callback2.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier.requests());
ASSERT_EQ(0u, verifier.cache_hits());
ASSERT_EQ(1u, verifier.inflight_joins());
}
// Tests that the callback of a canceled request is never made.
TEST(CertVerifierTest, CancelRequest) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result,
base::Bind(&FailTest), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier.CancelRequest(request_handle);
// Issue a few more requests to the worker pool and wait for their
// completion, so that the task of the canceled request (which runs on a
// worker thread) is likely to complete by the end of this test.
TestCompletionCallback callback;
for (int i = 0; i < 5; ++i) {
error = verifier.Verify(
test_cert, "www2.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
verifier.ClearCache();
}
}
// Tests that a canceled request is not leaked.
TEST(CertVerifierTest, CancelRequestThenQuit) {
CertVerifier verifier;
FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier.CancelRequest(request_handle);
// Destroy |verifier| by going out of scope.
}
TEST(CertVerifierTest, RequestParamsComparators) {
SHA1Fingerprint a_key;
memset(a_key.data, 'a', sizeof(a_key.data));
SHA1Fingerprint z_key;
memset(z_key.data, 'z', sizeof(z_key.data));
struct {
// Keys to test
CertVerifier::RequestParams key1;
CertVerifier::RequestParams key2;
// Expectation:
// -1 means key1 is less than key2
// 0 means key1 equals key2
// 1 means key1 is greater than key2
int expected_result;
} tests[] = {
{ // Test for basic equivalence.
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
0,
},
{ // Test that different certificates but with the same CA and for
// the same host are different validation keys.
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
CertVerifier::RequestParams(z_key, a_key, "www.example.test", 0),
-1,
},
{ // Test that the same EE certificate for the same host, but with
// different chains are different validation keys.
CertVerifier::RequestParams(a_key, z_key, "www.example.test", 0),
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
1,
},
{ // The same certificate, with the same chain, but for different
// hosts are different validation keys.
CertVerifier::RequestParams(a_key, a_key, "www1.example.test", 0),
CertVerifier::RequestParams(a_key, a_key, "www2.example.test", 0),
-1,
},
{ // The same certificate, chain, and host, but with different flags
// are different validation keys.
CertVerifier::RequestParams(a_key, a_key, "www.example.test",
X509Certificate::VERIFY_EV_CERT),
CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
1,
}
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));
const CertVerifier::RequestParams& key1 = tests[i].key1;
const CertVerifier::RequestParams& key2 = tests[i].key2;
switch (tests[i].expected_result) {
case -1:
EXPECT_TRUE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 0:
EXPECT_FALSE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 1:
EXPECT_FALSE(key1 < key2);
EXPECT_TRUE(key2 < key1);
break;
default:
FAIL() << "Invalid expectation. Can be only -1, 0, 1";
}
}
}
} // namespace net
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_TEST_GRIDS_HH
#define DUNE_GDT_TEST_GRIDS_HH
#include <dune/grid/sgrid.hh>
#include <dune/grid/yaspgrid.hh>
#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#endif
#include <dune/gdt/spaces/tools.hh>
using namespace Dune;
using namespace GDT;
#define SGRID_TYPES(dim) \
typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLeafGridPartType; \
typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLevelGridPartType; \
typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLeafGridViewType; \
typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLevelGridViewType;
SGRID_TYPES(1)
SGRID_TYPES(2)
SGRID_TYPES(3)
#undef SGRID_TYPES
#define YASPGRID_TYPES(dim) \
typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLeafGridPartType; \
typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLevelGridPartType; \
typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLeafGridViewType; \
typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLevelGridViewType;
YASPGRID_TYPES(1)
YASPGRID_TYPES(2)
YASPGRID_TYPES(3)
#undef YASPGRID_TYPES
#if HAVE_ALUGRID
typedef ALUGrid<2, 2, simplex, conforming> AluConform2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, false>::Type AluConform2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, false>::Type AluConform2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, true>::Type AluConform2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, true>::Type AluConform2dLevelGridViewType;
typedef ALUGrid<2, 2, simplex, nonconforming> AluSimplex2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLevelGridViewType;
typedef ALUGrid<3, 3, simplex, nonconforming> AluSimplex3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLevelGridViewType;
typedef ALUGrid<2, 2, cube, nonconforming> AluCube2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, false>::Type AluCube2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, false>::Type AluCube2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, true>::Type AluCube2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, true>::Type AluCube2dLevelGridViewType;
typedef ALUGrid<3, 3, cube, nonconforming> AluCube3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, false>::Type AluCube3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, false>::Type AluCube3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, true>::Type AluCube3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, true>::Type AluCube3dLevelGridViewType;
#endif // HAVE_ALUGRID
#endif // DUNE_GDT_TEST_GRIDS_HH
<commit_msg>[test.grids] add definition of AluConform3dGridType<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_TEST_GRIDS_HH
#define DUNE_GDT_TEST_GRIDS_HH
#include <dune/grid/sgrid.hh>
#include <dune/grid/yaspgrid.hh>
#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#endif
#include <dune/gdt/spaces/tools.hh>
using namespace Dune;
using namespace GDT;
#define SGRID_TYPES(dim) \
typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLeafGridPartType; \
typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLevelGridPartType; \
typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLeafGridViewType; \
typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLevelGridViewType;
SGRID_TYPES(1)
SGRID_TYPES(2)
SGRID_TYPES(3)
#undef SGRID_TYPES
#define YASPGRID_TYPES(dim) \
typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLeafGridPartType; \
typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLevelGridPartType; \
typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLeafGridViewType; \
typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLevelGridViewType;
YASPGRID_TYPES(1)
YASPGRID_TYPES(2)
YASPGRID_TYPES(3)
#undef YASPGRID_TYPES
#if HAVE_ALUGRID
typedef ALUGrid<2, 2, simplex, conforming> AluConform2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, false>::Type AluConform2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, false>::Type AluConform2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, true>::Type AluConform2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, true>::Type AluConform2dLevelGridViewType;
typedef ALUGrid<3, 3, simplex, conforming> AluConform3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluConform3dGridType, false>::Type AluConform3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluConform3dGridType, false>::Type AluConform3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluConform3dGridType, true>::Type AluConform3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluConform3dGridType, true>::Type AluConform3dLevelGridViewType;
typedef ALUGrid<2, 2, simplex, nonconforming> AluSimplex2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLevelGridViewType;
typedef ALUGrid<3, 3, simplex, nonconforming> AluSimplex3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLevelGridViewType;
typedef ALUGrid<2, 2, cube, nonconforming> AluCube2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, false>::Type AluCube2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, false>::Type AluCube2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, true>::Type AluCube2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, true>::Type AluCube2dLevelGridViewType;
typedef ALUGrid<3, 3, cube, nonconforming> AluCube3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, false>::Type AluCube3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, false>::Type AluCube3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, true>::Type AluCube3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, true>::Type AluCube3dLevelGridViewType;
#endif // HAVE_ALUGRID
#endif // DUNE_GDT_TEST_GRIDS_HH
<|endoftext|> |
<commit_before>#include "serial.h"
int main()
{
Serial gps(4800,"/dev/ttyUSB0",false);
std::cout << gps.serialRead(41);
}
<commit_msg>Got rid of getData()<commit_after>#include "serial.h"
int main()
{
Serial gps(4800,"/dev/ttyUSB0",false);
std::cout << gps.serialRead(41) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <opencv2/core.hpp>
#include <opencv2/core/affine.hpp>
namespace cv
{
typedef std::string String;
namespace viz
{
class CV_EXPORTS Color : public Scalar
{
public:
Color();
Color(double gray);
Color(double blue, double green, double red);
Color(const Scalar& color);
static Color black();
static Color blue();
static Color green();
static Color cyan();
static Color red();
static Color magenta();
static Color yellow();
static Color white();
static Color gray();
};
class CV_EXPORTS Mesh3d
{
public:
Mat cloud, colors;
Mat polygons;
static cv::viz::Mesh3d loadMesh(const String& file);
private:
struct loadMeshImpl;
};
class CV_EXPORTS KeyboardEvent
{
public:
static const unsigned int Alt = 1;
static const unsigned int Ctrl = 2;
static const unsigned int Shift = 4;
/** \brief Constructor
* \param[in] action true for key was pressed, false for released
* \param[in] key_sym the key-name that caused the action
* \param[in] key the key code that caused the action
* \param[in] alt whether the alt key was pressed at the time where this event was triggered
* \param[in] ctrl whether the ctrl was pressed at the time where this event was triggered
* \param[in] shift whether the shift was pressed at the time where this event was triggered
*/
KeyboardEvent (bool action, const std::string& key_sym, unsigned char key, bool alt, bool ctrl, bool shift);
bool isAltPressed () const;
bool isCtrlPressed () const;
bool isShiftPressed () const;
unsigned char getKeyCode () const;
const String& getKeySym () const;
bool keyDown () const;
bool keyUp () const;
protected:
bool action_;
unsigned int modifiers_;
unsigned char key_code_;
String key_sym_;
};
class CV_EXPORTS MouseEvent
{
public:
enum Type { MouseMove = 1, MouseButtonPress, MouseButtonRelease, MouseScrollDown, MouseScrollUp, MouseDblClick } ;
enum MouseButton { NoButton = 0, LeftButton, MiddleButton, RightButton, VScroll } ;
MouseEvent (const Type& type, const MouseButton& button, const Point& p, bool alt, bool ctrl, bool shift);
Type type;
MouseButton button;
Point pointer;
unsigned int key_state;
};
class CV_EXPORTS Camera
{
public:
Camera(float f_x, float f_y, float c_x, float c_y, const Size &window_size);
Camera(const Vec2f &fov, const Size &window_size);
Camera(const cv::Matx33f &K, const Size &window_size);
Camera(const cv::Matx44f &proj, const Size &window_size);
inline const Vec2d & getClip() const { return clip_; }
inline void setClip(const Vec2d &clip) { clip_ = clip; }
inline const Size & getWindowSize() const { return window_size_; }
void setWindowSize(const Size &window_size);
inline const Vec2f & getFov() const { return fov_; }
inline void setFov(const Vec2f & fov) { fov_ = fov; }
void computeProjectionMatrix(Matx44f &proj) const;
static Camera KinectCamera(const Size &window_size);
private:
void init(float f_x, float f_y, float c_x, float c_y, const Size &window_size);
Vec2d clip_;
Vec2f fov_;
Size window_size_;
Vec2f principal_point_;
Vec2f focal_;
};
} /* namespace viz */
} /* namespace cv */
<commit_msg>access focal length and principal point in camera<commit_after>#pragma once
#include <string>
#include <opencv2/core.hpp>
#include <opencv2/core/affine.hpp>
namespace cv
{
typedef std::string String;
namespace viz
{
class CV_EXPORTS Color : public Scalar
{
public:
Color();
Color(double gray);
Color(double blue, double green, double red);
Color(const Scalar& color);
static Color black();
static Color blue();
static Color green();
static Color cyan();
static Color red();
static Color magenta();
static Color yellow();
static Color white();
static Color gray();
};
class CV_EXPORTS Mesh3d
{
public:
Mat cloud, colors;
Mat polygons;
static cv::viz::Mesh3d loadMesh(const String& file);
private:
struct loadMeshImpl;
};
class CV_EXPORTS KeyboardEvent
{
public:
static const unsigned int Alt = 1;
static const unsigned int Ctrl = 2;
static const unsigned int Shift = 4;
/** \brief Constructor
* \param[in] action true for key was pressed, false for released
* \param[in] key_sym the key-name that caused the action
* \param[in] key the key code that caused the action
* \param[in] alt whether the alt key was pressed at the time where this event was triggered
* \param[in] ctrl whether the ctrl was pressed at the time where this event was triggered
* \param[in] shift whether the shift was pressed at the time where this event was triggered
*/
KeyboardEvent (bool action, const std::string& key_sym, unsigned char key, bool alt, bool ctrl, bool shift);
bool isAltPressed () const;
bool isCtrlPressed () const;
bool isShiftPressed () const;
unsigned char getKeyCode () const;
const String& getKeySym () const;
bool keyDown () const;
bool keyUp () const;
protected:
bool action_;
unsigned int modifiers_;
unsigned char key_code_;
String key_sym_;
};
class CV_EXPORTS MouseEvent
{
public:
enum Type { MouseMove = 1, MouseButtonPress, MouseButtonRelease, MouseScrollDown, MouseScrollUp, MouseDblClick } ;
enum MouseButton { NoButton = 0, LeftButton, MiddleButton, RightButton, VScroll } ;
MouseEvent (const Type& type, const MouseButton& button, const Point& p, bool alt, bool ctrl, bool shift);
Type type;
MouseButton button;
Point pointer;
unsigned int key_state;
};
class CV_EXPORTS Camera
{
public:
Camera(float f_x, float f_y, float c_x, float c_y, const Size &window_size);
Camera(const Vec2f &fov, const Size &window_size);
Camera(const cv::Matx33f &K, const Size &window_size);
Camera(const cv::Matx44f &proj, const Size &window_size);
inline const Vec2d & getClip() const { return clip_; }
inline void setClip(const Vec2d &clip) { clip_ = clip; }
inline const Size & getWindowSize() const { return window_size_; }
void setWindowSize(const Size &window_size);
inline const Vec2f & getFov() const { return fov_; }
inline void setFov(const Vec2f & fov) { fov_ = fov; }
inline const Vec2f & getPrincipalPoint() const { return principal_point_; }
inline const Vec2f & getFocalLength() const { return focal_; }
void computeProjectionMatrix(Matx44f &proj) const;
static Camera KinectCamera(const Size &window_size);
private:
void init(float f_x, float f_y, float c_x, float c_y, const Size &window_size);
Vec2d clip_;
Vec2f fov_;
Size window_size_;
Vec2f principal_point_;
Vec2f focal_;
};
} /* namespace viz */
} /* namespace cv */
<|endoftext|> |
<commit_before>#include <luabind/detail/typetraits.hpp>
#include <boost/static_assert.hpp>
using namespace luabind::detail;
struct tester {};
void test_type_traits()
{
BOOST_STATIC_ASSERT(is_nonconst_reference<int&>::value);
BOOST_STATIC_ASSERT(!is_nonconst_reference<const int&>::value);
BOOST_STATIC_ASSERT(is_nonconst_reference<tester&>::value);
BOOST_STATIC_ASSERT(!is_nonconst_reference<const tester&>::value);
BOOST_STATIC_ASSERT(!is_const_reference<int&>::value);
BOOST_STATIC_ASSERT(is_const_reference<const int&>::value);
BOOST_STATIC_ASSERT(!is_const_reference<tester&>::value);
BOOST_STATIC_ASSERT(is_const_reference<const tester&>::value);
BOOST_STATIC_ASSERT(!is_const_pointer<int*>::value);
BOOST_STATIC_ASSERT(is_const_pointer<const int*>::value);
BOOST_STATIC_ASSERT(!is_const_pointer<tester*>::value);
BOOST_STATIC_ASSERT(is_const_pointer<const tester*>::value);
BOOST_STATIC_ASSERT(is_nonconst_pointer<int*>::value);
BOOST_STATIC_ASSERT(!is_nonconst_pointer<const int*>::value);
BOOST_STATIC_ASSERT(is_nonconst_pointer<tester*>::value);
BOOST_STATIC_ASSERT(!is_nonconst_pointer<const tester*>::value);
BOOST_STATIC_ASSERT(!is_const_reference<const tester>::value);
}
<commit_msg>*** empty log message ***<commit_after>#include <luabind/detail/typetraits.hpp>
#include <luabind/detail/is_indirect_const.hpp>
#include <luabind/detail/pointee_sizeof.hpp>
#include <boost/static_assert.hpp>
using namespace luabind;
using namespace luabind::detail;
struct tester {};
void test_type_traits()
{
BOOST_STATIC_ASSERT(is_nonconst_reference<int&>::value);
BOOST_STATIC_ASSERT(!is_nonconst_reference<const int&>::value);
BOOST_STATIC_ASSERT(is_nonconst_reference<tester&>::value);
BOOST_STATIC_ASSERT(!is_nonconst_reference<const tester&>::value);
BOOST_STATIC_ASSERT(!is_const_reference<int&>::value);
BOOST_STATIC_ASSERT(is_const_reference<const int&>::value);
BOOST_STATIC_ASSERT(!is_const_reference<tester&>::value);
BOOST_STATIC_ASSERT(is_const_reference<const tester&>::value);
BOOST_STATIC_ASSERT(!is_const_pointer<int*>::value);
BOOST_STATIC_ASSERT(is_const_pointer<const int*>::value);
BOOST_STATIC_ASSERT(!is_const_pointer<tester*>::value);
BOOST_STATIC_ASSERT(is_const_pointer<const tester*>::value);
BOOST_STATIC_ASSERT(is_nonconst_pointer<int*>::value);
BOOST_STATIC_ASSERT(!is_nonconst_pointer<const int*>::value);
BOOST_STATIC_ASSERT(is_nonconst_pointer<tester*>::value);
BOOST_STATIC_ASSERT(!is_nonconst_pointer<const tester*>::value);
BOOST_STATIC_ASSERT(!is_const_reference<const tester>::value);
BOOST_STATIC_ASSERT(!luabind::is_indirect_const<int&>::value);
BOOST_STATIC_ASSERT(is_indirect_const<const int>::value);
BOOST_STATIC_ASSERT(is_indirect_const<const int&>::value);
BOOST_STATIC_ASSERT(!is_indirect_const<int*>::value);
BOOST_STATIC_ASSERT(is_indirect_const<const int*>::value);
}
<|endoftext|> |
<commit_before>#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
using namespace tiramisu;
/**
* Benchmark for BLAS GEMV
* out = a*A*x + b*y
*
* A : is a M x N matrix
* x : is a size N vector
* y : is a size M vector
* a,b : are scalars
*
* out : is a size M vector
**
We will make a tiramisu implementation of this code :
for(int i=0; i<M; i++)
{
tmp=0;
for(int j=0; j<N; j++){
tmp+= A(i, j) * x(j)
}
tmp *= alpha
result(i)= tmp + beta * y(i)
}
*/
int main(int argc, char **argv)
{
tiramisu::init("gemv");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant MM("M", expr(M)), NN("N", expr(N));
//Iteration variables
var i("i", 0, MM), j("j", 0, NN);
//Inputs
input A("A", {i,j}, p_float64);
input x("x", {j}, p_float64);
input y("y", {i}, p_float64);
input alpha("alpha", {}, p_float64);
input beta("beta", {}, p_float64);
//Computations
computation result_init("result_init", {i}, expr(cast(p_float64, 0)), p_float64);
computation sum_row("sum_row", {i,j}, p_float64);
sum_row.set_expression(expr(sum_row(i, j-1) + A(i, j) * x(j)));
computation mult_alpha("mult_alpha", {i}, expr(alpha(0)* sum_row(i, NN-1)), p_float64);
computation add_y("add_y", {i}, expr(mult_alpha(i) + beta(0) * y(i)), p_float64);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
add_y.after(mult_alpha, i);
mult_alpha.after(sum_row, i);
sum_row.after(result_init, i);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
//Input Buffers
buffer buf_A("buf_A", {MM,NN}, p_float64, a_input);
buffer buf_x("buf_x", {NN}, p_float64, a_input);
buffer buf_y("buf_y", {MM}, p_float64, a_input);
buffer buf_alpha("buf_alpha", {1}, p_float64, a_input);
buffer buf_beta("buf_beta", {1}, p_float64, a_input);
//Output Buffers
buffer buf_result("buf_result", {MM}, p_float64, a_output);
//Store inputs
A.store_in(&buf_A);
x.store_in(&buf_x);
y.store_in(&buf_y);
alpha.store_in(&buf_alpha);
beta.store_in(&buf_beta);
//Store computations
result_init.store_in(&buf_result);
sum_row.store_in(&buf_result, {i});
mult_alpha.store_in(&buf_result);
add_y.store_in(&buf_result);
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&buf_A, &buf_x, &buf_y, &buf_alpha, &buf_beta, &buf_result}, "generated_gemv.o");
return 0;
}
<commit_msg>Add optimizations to gemv blas function<commit_after>#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
#define UNROLL_FACTOR 64
using namespace tiramisu;
/**
* Benchmark for BLAS GEMV
* out = a*A*x + b*y
*
* A : is a M x N matrix
* x : is a size N vector
* y : is a size M vector
* a,b : are scalars
*
* out : is a size M vector
**
We will make a tiramisu implementation of this code :
for(int i=0; i<M; i++)
{
tmp=0;
for(int j=0; j<N; j++){
tmp+= A(i, j) * x(j)
}
tmp *= alpha
result(i)= tmp + beta * y(i)
}
*/
int main(int argc, char **argv)
{
tiramisu::init("gemv");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant MM("M", expr(M)), NN("N", expr(N));
//Iteration variables
var i("i", 0, MM), j("j", 0, NN);
//Inputs
input A("A", {i,j}, p_float64);
input x("x", {j}, p_float64);
input y("y", {i}, p_float64);
input alpha("alpha", {}, p_float64);
input beta("beta", {}, p_float64);
//Computations
computation result_init("result_init", {i}, expr(cast(p_float64, 0)), p_float64);
computation sum_row("sum_row", {i,j}, p_float64);
sum_row.set_expression(expr(sum_row(i, j-1) + A(i, j) * x(j)));
computation mult_alpha("mult_alpha", {i}, expr(alpha(0)* sum_row(i, NN-1)), p_float64);
computation add_y("add_y", {i}, expr(mult_alpha(i) + beta(0) * y(i)), p_float64);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
add_y.after(mult_alpha, i);
mult_alpha.after(sum_row, i);
sum_row.after(result_init, i);
//Unrolling
sum_row.unroll(j, UNROLL_FACTOR);
//Parallelization
sum_row.parallelize(i);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
//Input Buffers
buffer buf_A("buf_A", {MM,NN}, p_float64, a_input);
buffer buf_x("buf_x", {NN}, p_float64, a_input);
buffer buf_y("buf_y", {MM}, p_float64, a_input);
buffer buf_alpha("buf_alpha", {1}, p_float64, a_input);
buffer buf_beta("buf_beta", {1}, p_float64, a_input);
//Output Buffers
buffer buf_result("buf_result", {MM}, p_float64, a_output);
//Store inputs
A.store_in(&buf_A);
x.store_in(&buf_x);
y.store_in(&buf_y);
alpha.store_in(&buf_alpha);
beta.store_in(&buf_beta);
//Store computations
result_init.store_in(&buf_result);
sum_row.store_in(&buf_result, {i});
mult_alpha.store_in(&buf_result);
add_y.store_in(&buf_result);
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&buf_A, &buf_x, &buf_y, &buf_alpha, &buf_beta, &buf_result}, "generated_gemv.o");
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* mongodb_log_tf.cpp - MongoDB Logger for /tf
*
* Created: Wed Dec 8 17:00:25 2010 -0500
* Copyright 2010 Tim Niemueller [www.niemueller.de]
* 2010 Carnegie Mellon University
* 2010 Intel Labs Pittsburgh
* 2014 Jan Winkler <[email protected]>
****************************************************************************/
/* 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. A runtime exception applies to
* this software (see LICENSE.GPL_WRE file mentioned below for details).
*
* 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 Library General Public License for more details.
*
* Read the full text in the LICENSE.GPL_WRE file in the doc directory.
*/
// System
#include <list>
#include <string>
// ROS
#include <ros/ros.h>
#include <tf/tfMessage.h>
#include <tf/LinearMath/Quaternion.h>
// MongoDB
#include <mongo/client/dbclient.h>
#include <mongodb_store/util.h>
using namespace mongo;
typedef struct {
geometry_msgs::TransformStamped tsTransform;
} PoseStampedMemoryEntry;
float fVectorialDistanceThreshold;
float fAngularDistanceThreshold;
float fTimeDistanceThreshold;
list<PoseStampedMemoryEntry> lstPoseStampedMemory;
bool bAlwaysLog;
DBClientConnection *mongodb_conn;
std::string collection;
std::string topic;
unsigned int in_counter;
unsigned int out_counter;
unsigned int qsize;
unsigned int drop_counter;
static pthread_mutex_t in_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t out_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t drop_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t qsize_mutex = PTHREAD_MUTEX_INITIALIZER;
bool shouldLogTransform(std::vector<geometry_msgs::TransformStamped>::const_iterator t) {
if(bAlwaysLog) {
// When this flag is set, always return true immediately (and
// don't keep track of logged transforms).
return true;
}
string strMsgFrame = t->header.frame_id;
string strMsgChild = t->child_frame_id;
bool bFound = false;
for(list<PoseStampedMemoryEntry>::iterator itEntry = lstPoseStampedMemory.begin();
itEntry != lstPoseStampedMemory.end();
itEntry++) {
string strEntryFrame = (*itEntry).tsTransform.header.frame_id;
string strEntryChild = (*itEntry).tsTransform.child_frame_id;
// Is this the same transform as in tfMsg?
if((strEntryFrame == strMsgFrame && strEntryChild == strMsgChild) ||
(strEntryFrame == strMsgChild && strEntryChild == strMsgFrame)) {
// Yes, it is. Check vectorial and angular distance.
bFound = true;
float fVectorialDistance = sqrt(((t->transform.translation.x - (*itEntry).tsTransform.transform.translation.x) *
(t->transform.translation.x - (*itEntry).tsTransform.transform.translation.x)) +
((t->transform.translation.y - (*itEntry).tsTransform.transform.translation.y) *
(t->transform.translation.y - (*itEntry).tsTransform.transform.translation.y)) +
((t->transform.translation.z - (*itEntry).tsTransform.transform.translation.z) *
(t->transform.translation.z - (*itEntry).tsTransform.transform.translation.z)));
tf::Quaternion q1(t->transform.rotation.x, t->transform.rotation.y, t->transform.rotation.z, t->transform.rotation.w);
tf::Quaternion q2((*itEntry).tsTransform.transform.rotation.x,
(*itEntry).tsTransform.transform.rotation.y,
(*itEntry).tsTransform.transform.rotation.z,
(*itEntry).tsTransform.transform.rotation.w);
float fAngularDistance = 2.0 * fabs(q1.angle(q2));
float fTimeDistance = (fabs((t->header.stamp.sec * 1000.0 + t->header.stamp.nsec / 1000000.0) -
((*itEntry).tsTransform.header.stamp.sec * 1000.0 + (*itEntry).tsTransform.header.stamp.nsec / 1000000.0)) / 1000.0);
if(((fVectorialDistance > fVectorialDistanceThreshold) ||
(fAngularDistance > fAngularDistanceThreshold) ||
(fTimeDistanceThreshold > 0 &&
(fTimeDistance > fTimeDistanceThreshold)))) {
// Requirements met, this transform should be logged and the
// stored entry renewed.
(*itEntry).tsTransform = *t;
return true;
}
}
}
if(!bFound) {
// This transform is new, so log it.
PoseStampedMemoryEntry psEntry;
psEntry.tsTransform = *t;
lstPoseStampedMemory.push_back(psEntry);
return true;
}
return false;
}
void msg_callback(const tf::tfMessage::ConstPtr& msg) {
std::vector<BSONObj> transforms;
const tf::tfMessage& msg_in = *msg;
bool bDidLogTransforms = false;
std::vector<geometry_msgs::TransformStamped>::const_iterator t;
for (t = msg_in.transforms.begin(); t != msg_in.transforms.end(); ++t) {
if(shouldLogTransform(t)) {
bDidLogTransforms = true;
Date_t stamp = t->header.stamp.sec * 1000.0 + t->header.stamp.nsec / 1000000.0;
BSONObjBuilder transform_stamped;
BSONObjBuilder transform;
transform_stamped.append("header", BSON( "seq" << t->header.seq
<< "stamp" << stamp
<< "frame_id" << t->header.frame_id));
transform_stamped.append("child_frame_id", t->child_frame_id);
transform.append("translation", BSON( "x" << t->transform.translation.x
<< "y" << t->transform.translation.y
<< "z" << t->transform.translation.z));
transform.append("rotation", BSON( "x" << t->transform.rotation.x
<< "y" << t->transform.rotation.y
<< "z" << t->transform.rotation.z
<< "w" << t->transform.rotation.w));
transform_stamped.append("transform", transform.obj());
transforms.push_back(transform_stamped.obj());
}
}
if(bDidLogTransforms) {
mongodb_conn->insert(collection, BSON("transforms" << transforms <<
"__recorded" << Date_t(time(NULL) * 1000) <<
"__topic" << topic));
// If we'd get access to the message queue this could be more useful
// https://code.ros.org/trac/ros/ticket/744
pthread_mutex_lock(&in_counter_mutex);
++in_counter;
pthread_mutex_unlock(&in_counter_mutex);
pthread_mutex_lock(&out_counter_mutex);
++out_counter;
pthread_mutex_unlock(&out_counter_mutex);
}
}
void print_count(const ros::TimerEvent &te) {
unsigned int l_in_counter, l_out_counter, l_drop_counter, l_qsize;
pthread_mutex_lock(&in_counter_mutex);
l_in_counter = in_counter; in_counter = 0;
pthread_mutex_unlock(&in_counter_mutex);
pthread_mutex_lock(&out_counter_mutex);
l_out_counter = out_counter; out_counter = 0;
pthread_mutex_unlock(&out_counter_mutex);
pthread_mutex_lock(&drop_counter_mutex);
l_drop_counter = drop_counter; drop_counter = 0;
pthread_mutex_unlock(&drop_counter_mutex);
pthread_mutex_lock(&qsize_mutex);
l_qsize = qsize; qsize = 0;
pthread_mutex_unlock(&qsize_mutex);
printf("%u:%u:%u:%u\n", l_in_counter, l_out_counter, l_drop_counter, l_qsize);
fflush(stdout);
}
int main(int argc, char **argv) {
std::string mongodb = "localhost", nodename = "";
collection = topic = "";
in_counter = out_counter = drop_counter = qsize = 0;
fVectorialDistanceThreshold = 0.100; // Distance threshold in terms
// of vector distance between
// an old and a new pose of the
// same transform before it
// gets logged again
fAngularDistanceThreshold = 0.100; // Same for angular distance
fTimeDistanceThreshold = 1.0; // And same for timely distance (in seconds)
bAlwaysLog = true;
int c;
while ((c = getopt(argc, argv, "t:m:n:c:ak:l:g:")) != -1) {
if ((c == '?') || (c == ':')) {
printf("Usage: %s -t topic -m mongodb -n nodename -c collection -k vectorial-threshold -l angular-threshold -g time-threshold -a\n", argv[0]);
exit(-1);
} else if (c == 't') {
topic = optarg;
} else if (c == 'm') {
mongodb = optarg;
} else if (c == 'n') {
nodename = optarg;
} else if (c == 'c') {
collection = optarg;
} else if (c == 'a') {
bAlwaysLog = false;
} else if (c == 'k') {
sscanf(optarg, "%f", &fVectorialDistanceThreshold);
} else if (c == 'l') {
sscanf(optarg, "%f", &fAngularDistanceThreshold);
} else if (c == 'g') {
sscanf(optarg, "%f", &fTimeDistanceThreshold);
}
}
if (topic == "") {
printf("No topic given.\n");
exit(-2);
} else if (nodename == "") {
printf("No node name given.\n");
exit(-2);
}
ros::init(argc, argv, nodename);
ros::NodeHandle n;
std::string errmsg;
mongodb_conn = new DBClientConnection(/* auto reconnect*/ true);
if (! mongodb_conn->connect(mongodb, errmsg)) {
ROS_ERROR("Failed to connect to MongoDB: %s", errmsg.c_str());
return -1;
}
ros::Subscriber sub = n.subscribe<tf::tfMessage>(topic, 1000, msg_callback);
ros::Timer count_print_timer = n.createTimer(ros::Duration(5, 0), print_count);
ros::spin();
delete mongodb_conn;
return 0;
}
<commit_msg>Fixed missing namespace for mongodb_log<commit_after>/***************************************************************************
* mongodb_log_tf.cpp - MongoDB Logger for /tf
*
* Created: Wed Dec 8 17:00:25 2010 -0500
* Copyright 2010 Tim Niemueller [www.niemueller.de]
* 2010 Carnegie Mellon University
* 2010 Intel Labs Pittsburgh
* 2014 Jan Winkler <[email protected]>
****************************************************************************/
/* 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. A runtime exception applies to
* this software (see LICENSE.GPL_WRE file mentioned below for details).
*
* 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 Library General Public License for more details.
*
* Read the full text in the LICENSE.GPL_WRE file in the doc directory.
*/
// System
#include <list>
#include <string>
// ROS
#include <ros/ros.h>
#include <tf/tfMessage.h>
#include <tf/LinearMath/Quaternion.h>
// MongoDB
#include <mongo/client/dbclient.h>
#include <mongodb_store/util.h>
using namespace mongo;
using namespace std;
typedef struct {
geometry_msgs::TransformStamped tsTransform;
} PoseStampedMemoryEntry;
float fVectorialDistanceThreshold;
float fAngularDistanceThreshold;
float fTimeDistanceThreshold;
list<PoseStampedMemoryEntry> lstPoseStampedMemory;
bool bAlwaysLog;
DBClientConnection *mongodb_conn;
std::string collection;
std::string topic;
unsigned int in_counter;
unsigned int out_counter;
unsigned int qsize;
unsigned int drop_counter;
static pthread_mutex_t in_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t out_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t drop_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t qsize_mutex = PTHREAD_MUTEX_INITIALIZER;
bool shouldLogTransform(std::vector<geometry_msgs::TransformStamped>::const_iterator t) {
if(bAlwaysLog) {
// When this flag is set, always return true immediately (and
// don't keep track of logged transforms).
return true;
}
string strMsgFrame = t->header.frame_id;
string strMsgChild = t->child_frame_id;
bool bFound = false;
for(list<PoseStampedMemoryEntry>::iterator itEntry = lstPoseStampedMemory.begin();
itEntry != lstPoseStampedMemory.end();
itEntry++) {
string strEntryFrame = (*itEntry).tsTransform.header.frame_id;
string strEntryChild = (*itEntry).tsTransform.child_frame_id;
// Is this the same transform as in tfMsg?
if((strEntryFrame == strMsgFrame && strEntryChild == strMsgChild) ||
(strEntryFrame == strMsgChild && strEntryChild == strMsgFrame)) {
// Yes, it is. Check vectorial and angular distance.
bFound = true;
float fVectorialDistance = sqrt(((t->transform.translation.x - (*itEntry).tsTransform.transform.translation.x) *
(t->transform.translation.x - (*itEntry).tsTransform.transform.translation.x)) +
((t->transform.translation.y - (*itEntry).tsTransform.transform.translation.y) *
(t->transform.translation.y - (*itEntry).tsTransform.transform.translation.y)) +
((t->transform.translation.z - (*itEntry).tsTransform.transform.translation.z) *
(t->transform.translation.z - (*itEntry).tsTransform.transform.translation.z)));
tf::Quaternion q1(t->transform.rotation.x, t->transform.rotation.y, t->transform.rotation.z, t->transform.rotation.w);
tf::Quaternion q2((*itEntry).tsTransform.transform.rotation.x,
(*itEntry).tsTransform.transform.rotation.y,
(*itEntry).tsTransform.transform.rotation.z,
(*itEntry).tsTransform.transform.rotation.w);
float fAngularDistance = 2.0 * fabs(q1.angle(q2));
float fTimeDistance = (fabs((t->header.stamp.sec * 1000.0 + t->header.stamp.nsec / 1000000.0) -
((*itEntry).tsTransform.header.stamp.sec * 1000.0 + (*itEntry).tsTransform.header.stamp.nsec / 1000000.0)) / 1000.0);
if(((fVectorialDistance > fVectorialDistanceThreshold) ||
(fAngularDistance > fAngularDistanceThreshold) ||
(fTimeDistanceThreshold > 0 &&
(fTimeDistance > fTimeDistanceThreshold)))) {
// Requirements met, this transform should be logged and the
// stored entry renewed.
(*itEntry).tsTransform = *t;
return true;
}
}
}
if(!bFound) {
// This transform is new, so log it.
PoseStampedMemoryEntry psEntry;
psEntry.tsTransform = *t;
lstPoseStampedMemory.push_back(psEntry);
return true;
}
return false;
}
void msg_callback(const tf::tfMessage::ConstPtr& msg) {
std::vector<BSONObj> transforms;
const tf::tfMessage& msg_in = *msg;
bool bDidLogTransforms = false;
std::vector<geometry_msgs::TransformStamped>::const_iterator t;
for (t = msg_in.transforms.begin(); t != msg_in.transforms.end(); ++t) {
if(shouldLogTransform(t)) {
bDidLogTransforms = true;
Date_t stamp = t->header.stamp.sec * 1000.0 + t->header.stamp.nsec / 1000000.0;
BSONObjBuilder transform_stamped;
BSONObjBuilder transform;
transform_stamped.append("header", BSON( "seq" << t->header.seq
<< "stamp" << stamp
<< "frame_id" << t->header.frame_id));
transform_stamped.append("child_frame_id", t->child_frame_id);
transform.append("translation", BSON( "x" << t->transform.translation.x
<< "y" << t->transform.translation.y
<< "z" << t->transform.translation.z));
transform.append("rotation", BSON( "x" << t->transform.rotation.x
<< "y" << t->transform.rotation.y
<< "z" << t->transform.rotation.z
<< "w" << t->transform.rotation.w));
transform_stamped.append("transform", transform.obj());
transforms.push_back(transform_stamped.obj());
}
}
if(bDidLogTransforms) {
mongodb_conn->insert(collection, BSON("transforms" << transforms <<
"__recorded" << Date_t(time(NULL) * 1000) <<
"__topic" << topic));
// If we'd get access to the message queue this could be more useful
// https://code.ros.org/trac/ros/ticket/744
pthread_mutex_lock(&in_counter_mutex);
++in_counter;
pthread_mutex_unlock(&in_counter_mutex);
pthread_mutex_lock(&out_counter_mutex);
++out_counter;
pthread_mutex_unlock(&out_counter_mutex);
}
}
void print_count(const ros::TimerEvent &te) {
unsigned int l_in_counter, l_out_counter, l_drop_counter, l_qsize;
pthread_mutex_lock(&in_counter_mutex);
l_in_counter = in_counter; in_counter = 0;
pthread_mutex_unlock(&in_counter_mutex);
pthread_mutex_lock(&out_counter_mutex);
l_out_counter = out_counter; out_counter = 0;
pthread_mutex_unlock(&out_counter_mutex);
pthread_mutex_lock(&drop_counter_mutex);
l_drop_counter = drop_counter; drop_counter = 0;
pthread_mutex_unlock(&drop_counter_mutex);
pthread_mutex_lock(&qsize_mutex);
l_qsize = qsize; qsize = 0;
pthread_mutex_unlock(&qsize_mutex);
printf("%u:%u:%u:%u\n", l_in_counter, l_out_counter, l_drop_counter, l_qsize);
fflush(stdout);
}
int main(int argc, char **argv) {
std::string mongodb = "localhost", nodename = "";
collection = topic = "";
in_counter = out_counter = drop_counter = qsize = 0;
fVectorialDistanceThreshold = 0.100; // Distance threshold in terms
// of vector distance between
// an old and a new pose of the
// same transform before it
// gets logged again
fAngularDistanceThreshold = 0.100; // Same for angular distance
fTimeDistanceThreshold = 1.0; // And same for timely distance (in seconds)
bAlwaysLog = true;
int c;
while ((c = getopt(argc, argv, "t:m:n:c:ak:l:g:")) != -1) {
if ((c == '?') || (c == ':')) {
printf("Usage: %s -t topic -m mongodb -n nodename -c collection -k vectorial-threshold -l angular-threshold -g time-threshold -a\n", argv[0]);
exit(-1);
} else if (c == 't') {
topic = optarg;
} else if (c == 'm') {
mongodb = optarg;
} else if (c == 'n') {
nodename = optarg;
} else if (c == 'c') {
collection = optarg;
} else if (c == 'a') {
bAlwaysLog = false;
} else if (c == 'k') {
sscanf(optarg, "%f", &fVectorialDistanceThreshold);
} else if (c == 'l') {
sscanf(optarg, "%f", &fAngularDistanceThreshold);
} else if (c == 'g') {
sscanf(optarg, "%f", &fTimeDistanceThreshold);
}
}
if (topic == "") {
printf("No topic given.\n");
exit(-2);
} else if (nodename == "") {
printf("No node name given.\n");
exit(-2);
}
ros::init(argc, argv, nodename);
ros::NodeHandle n;
std::string errmsg;
mongodb_conn = new DBClientConnection(/* auto reconnect*/ true);
if (! mongodb_conn->connect(mongodb, errmsg)) {
ROS_ERROR("Failed to connect to MongoDB: %s", errmsg.c_str());
return -1;
}
ros::Subscriber sub = n.subscribe<tf::tfMessage>(topic, 1000, msg_callback);
ros::Timer count_print_timer = n.createTimer(ros::Duration(5, 0), print_count);
ros::spin();
delete mongodb_conn;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "../tools_common.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/md5_helper.h"
#include "test/test_vectors.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"
namespace {
enum DecodeMode {
kSerialMode,
kFrameParallelMode
};
const int kDecodeMode = 0;
const int kThreads = 1;
const int kFileName = 2;
typedef std::tr1::tuple<int, int, const char*> DecodeParam;
class TestVectorTest : public ::libvpx_test::DecoderTest,
public ::libvpx_test::CodecTestWithParam<DecodeParam> {
protected:
TestVectorTest()
: DecoderTest(GET_PARAM(0)),
md5_file_(NULL) {
}
virtual ~TestVectorTest() {
if (md5_file_)
fclose(md5_file_);
}
void OpenMD5File(const std::string& md5_file_name_) {
md5_file_ = libvpx_test::OpenTestDataFile(md5_file_name_);
ASSERT_TRUE(md5_file_ != NULL) << "Md5 file open failed. Filename: "
<< md5_file_name_;
}
virtual void DecompressedFrameHook(const vpx_image_t& img,
const unsigned int frame_number) {
ASSERT_TRUE(md5_file_ != NULL);
char expected_md5[33];
char junk[128];
// Read correct md5 checksums.
const int res = fscanf(md5_file_, "%s %s", expected_md5, junk);
ASSERT_NE(res, EOF) << "Read md5 data failed";
expected_md5[32] = '\0';
::libvpx_test::MD5 md5_res;
md5_res.Add(&img);
const char *actual_md5 = md5_res.Get();
// Check md5 match.
ASSERT_STREQ(expected_md5, actual_md5)
<< "Md5 checksums don't match: frame number = " << frame_number;
}
private:
FILE *md5_file_;
};
// This test runs through the whole set of test vectors, and decodes them.
// The md5 checksums are computed for each frame in the video file. If md5
// checksums match the correct md5 data, then the test is passed. Otherwise,
// the test failed.
TEST_P(TestVectorTest, MD5Match) {
const DecodeParam input = GET_PARAM(1);
const std::string filename = std::tr1::get<kFileName>(input);
const int threads = std::tr1::get<kThreads>(input);
const int mode = std::tr1::get<kDecodeMode>(input);
libvpx_test::CompressedVideoSource *video = NULL;
vpx_codec_flags_t flags = 0;
vpx_codec_dec_cfg_t cfg = {0};
char str[256];
if (mode == kFrameParallelMode) {
flags |= VPX_CODEC_USE_FRAME_THREADING;
}
cfg.threads = threads;
snprintf(str, sizeof(str) / sizeof(str[0]) - 1,
"file: %s mode: %s threads: %d",
filename.c_str(), mode == 0 ? "Serial" : "Parallel", threads);
SCOPED_TRACE(str);
// Open compressed video file.
if (filename.substr(filename.length() - 3, 3) == "ivf") {
video = new libvpx_test::IVFVideoSource(filename);
} else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
video = new libvpx_test::WebMVideoSource(filename);
#else
fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
filename.c_str());
return;
#endif
}
video->Init();
// Construct md5 file name.
const std::string md5_filename = filename + ".md5";
OpenMD5File(md5_filename);
// Set decode config and flags.
set_cfg(cfg);
set_flags(flags);
// Decode frame, and check the md5 matching.
ASSERT_NO_FATAL_FAILURE(RunLoop(video, cfg));
delete video;
}
// Test VP8 decode in serial mode with single thread.
// NOTE: VP8 only support serial mode.
VP8_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(0), // Serial Mode.
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP8TestVectors,
libvpx_test::kVP8TestVectors +
libvpx_test::kNumVP8TestVectors)));
// Test VP9 decode in serial mode with single thread.
VP9_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(0), // Serial Mode.
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors)));
#if CONFIG_VP9_DECODER
// Test VP9 decode in frame parallel mode with different number of threads.
INSTANTIATE_TEST_CASE_P(
VP9MultiThreadedFrameParallel, TestVectorTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)),
::testing::Combine(
::testing::Values(1), // Frame Parallel mode.
::testing::Range(2, 9), // With 2 ~ 8 threads.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors))));
#endif
} // namespace
<commit_msg>Fix compiler error in vp8/9 decoder test<commit_after>/*
* Copyright (c) 2013 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "../tools_common.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/md5_helper.h"
#include "test/test_vectors.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"
namespace {
enum DecodeMode {
kSerialMode,
kFrameParallelMode
};
const int kDecodeMode = 0;
const int kThreads = 1;
const int kFileName = 2;
typedef std::tr1::tuple<int, int, const char*> DecodeParam;
class TestVectorTest : public ::libvpx_test::DecoderTest,
public ::libvpx_test::CodecTestWithParam<DecodeParam> {
protected:
TestVectorTest()
: DecoderTest(GET_PARAM(0)),
md5_file_(NULL) {
}
virtual ~TestVectorTest() {
if (md5_file_)
fclose(md5_file_);
}
void OpenMD5File(const std::string& md5_file_name_) {
md5_file_ = libvpx_test::OpenTestDataFile(md5_file_name_);
ASSERT_TRUE(md5_file_ != NULL) << "Md5 file open failed. Filename: "
<< md5_file_name_;
}
virtual void DecompressedFrameHook(const vpx_image_t& img,
const unsigned int frame_number) {
ASSERT_TRUE(md5_file_ != NULL);
char expected_md5[33];
char junk[128];
// Read correct md5 checksums.
const int res = fscanf(md5_file_, "%s %s", expected_md5, junk);
ASSERT_NE(res, EOF) << "Read md5 data failed";
expected_md5[32] = '\0';
::libvpx_test::MD5 md5_res;
md5_res.Add(&img);
const char *actual_md5 = md5_res.Get();
// Check md5 match.
ASSERT_STREQ(expected_md5, actual_md5)
<< "Md5 checksums don't match: frame number = " << frame_number;
}
private:
FILE *md5_file_;
};
// This test runs through the whole set of test vectors, and decodes them.
// The md5 checksums are computed for each frame in the video file. If md5
// checksums match the correct md5 data, then the test is passed. Otherwise,
// the test failed.
TEST_P(TestVectorTest, MD5Match) {
const DecodeParam input = GET_PARAM(1);
const std::string filename = std::tr1::get<kFileName>(input);
const int threads = std::tr1::get<kThreads>(input);
const int mode = std::tr1::get<kDecodeMode>(input);
libvpx_test::CompressedVideoSource *video = NULL;
vpx_codec_flags_t flags = 0;
vpx_codec_dec_cfg_t cfg = {0};
char str[256];
if (mode == kFrameParallelMode) {
flags |= VPX_CODEC_USE_FRAME_THREADING;
}
cfg.threads = threads;
snprintf(str, sizeof(str) / sizeof(str[0]) - 1,
"file: %s mode: %s threads: %d",
filename.c_str(), mode == 0 ? "Serial" : "Parallel", threads);
SCOPED_TRACE(str);
// Open compressed video file.
if (filename.substr(filename.length() - 3, 3) == "ivf") {
video = new libvpx_test::IVFVideoSource(filename);
} else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
video = new libvpx_test::WebMVideoSource(filename);
#else
fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
filename.c_str());
return;
#endif
}
video->Init();
// Construct md5 file name.
const std::string md5_filename = filename + ".md5";
OpenMD5File(md5_filename);
// Set decode config and flags.
set_cfg(cfg);
set_flags(flags);
// Decode frame, and check the md5 matching.
ASSERT_NO_FATAL_FAILURE(RunLoop(video, cfg));
delete video;
}
// Test VP8 decode in serial mode with single thread.
// NOTE: VP8 only support serial mode.
#if CONFIG_VP8_DECODER
VP8_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(0), // Serial Mode.
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP8TestVectors,
libvpx_test::kVP8TestVectors +
libvpx_test::kNumVP8TestVectors)));
#endif // CONFIG_VP8_DECODER
// Test VP9 decode in serial mode with single thread.
#if CONFIG_VP9_DECODER
VP9_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(0), // Serial Mode.
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors)));
// Test VP9 decode in frame parallel mode with different number of threads.
INSTANTIATE_TEST_CASE_P(
VP9MultiThreadedFrameParallel, TestVectorTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)),
::testing::Combine(
::testing::Values(1), // Frame Parallel mode.
::testing::Range(2, 9), // With 2 ~ 8 threads.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors))));
#endif
} // namespace
<|endoftext|> |
<commit_before>#include <iostream>
#include <Python.h>
#include "character.h"
using namespace std;
static int error(const std::string & message){
std::cout << message << std::endl;
//PyErr_Print();
return -1;
}
int main(int argc, char ** argv){
if (argc > 1){
Py_Initialize();
/* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
try {
Character * character = new Character(argv[1]);
character->addAttribute("name", Character::String);
std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
delete character;
} catch (const PyException & ex){
error("Problem loading module! Reason: " + ex.getReason());
}
Py_Finalize();
return 0;
}
std::cout << "Usage: ./test character.py" << std::endl;
return 0;
}
<commit_msg>Correct usage line, no need to include .py in module name.<commit_after>#include <iostream>
#include <Python.h>
#include "character.h"
using namespace std;
static int error(const std::string & message){
std::cout << message << std::endl;
//PyErr_Print();
return -1;
}
int main(int argc, char ** argv){
if (argc > 1){
Py_Initialize();
/* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
try {
Character * character = new Character(argv[1]);
character->addAttribute("name", Character::String);
std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
delete character;
} catch (const PyException & ex){
error("Problem loading module! Reason: " + ex.getReason());
}
Py_Finalize();
return 0;
}
std::cout << "Usage: ./test character_module_name" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CCopasiMethod.cpp,v $
// $Revision: 1.46 $
// $Name: $
// $Author: jdada $
// $Date: 2007/11/06 15:01:39 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
/**
* CCopasiMethod class.
* This class is used to describe a task in COPASI. This class is
* intended to be used as the parent class for all methods whithin COPASI.
*
* Created for Copasi by Stefan Hoops 2003
*/
#include "copasi.h"
#include "CCopasiMethod.h"
#include "CCopasiMessage.h"
#include "CCopasiProblem.h"
const std::string CCopasiMethod::SubTypeName[] =
{
"Not set",
"Random Search",
"Random Search (PVM)",
"Simulated Annealing",
"Genetic Algorithm",
"Evolutionary Programming",
"Steepest Descent",
"Hybrid GA/SA",
"Genetic Algorithm SR",
"Hooke & Jeeves",
"Levenberg - Marquardt",
"Nelder - Mead",
"Evolution Strategy (SRES)",
"Current Solution Statistics",
"Particle Swarm",
"Praxis",
"Truncated Newton",
"Enhanced Newton",
"Deterministic (LSODA)",
"Deterministic (LSODAR)",
"Stochastic (Gibson + Bruck)",
"Hybrid (Runge-Kutta)",
"Hybrid (LSODA)",
#ifdef COPASI_TSSA
//"Time Scale Separation (ILDM)",
//"Time Scale Separation (CSP)",
"ILDM (LSODA)",
"CSP (LSODA)",
#endif // COPASI_TSSA
"Stochastic (\xcf\x84-Leap)",
"MCA Method (Reder)",
"Scan Framework",
"Wolf Method",
#ifdef COPASI_TSS
"Time Scale Separation Method",
#endif // COPASI_TSS
"Sensitivities Method",
#ifdef COPASI_SSA
"Stoichiometric Stability Analysis Method",
#endif // COPASI_SSA
#ifdef COPASI_EXTREMECURRENTS
"Extreme Current Calculator",
#endif // COPAISI_EXTREMECURRENTS
"EFM Algorithm",
""
};
const char* CCopasiMethod::XMLSubType[] =
{
"NotSet",
"RandomSearch",
"RandomSearch(PVM)",
"SimulatedAnnealing",
"GeneticAlgorithm",
"EvolutionaryProgram",
"SteepestDescent",
"HybridGASA",
"GeneticAlgorithmSR",
"HookeJeeves",
"LevenbergMarquardt",
"NelderMead",
"EvolutionaryStrategySR",
"CurrentSolutionStatistics",
"ParticleSwarm",
"Praxis",
"EnhancedNewton",
"Deterministic(LSODA)",
"Deterministic(LSODAR)",
"Stochastic",
"Hybrid",
"Hybrid (LSODA)",
#ifdef COPASI_DEBUG
"TimeScaleSeparation(ILDM)",
"TimeScaleSeparation(CSP)",
#endif // COPASI_DEBUG
"TauLeap",
"MCAMethod(Reder)",
"ScanFramework",
"WolfMethod",
#ifdef COPASI_TSS
"TimeScaleSeparationMethod",
#endif // COPASI_TSS
"SensitivitiesMethod",
#ifdef COPASI_SSA
"SSAMethod",
#endif // COPASI_SSA
#ifdef COPASI_EXTREMECURRENTS
"ExtremeCurrentCalculator",
#endif // COPASI_EXTREMECURRENTS
"EFMAlgorithm",
NULL
};
// std::string mType;
CCopasiMethod::SubType CCopasiMethod::TypeNameToEnum(const std::string & subTypeName)
{
unsigned C_INT32 i = 0;
while (SubTypeName[i] != subTypeName && SubTypeName[i] != "")
i++;
if (CCopasiMethod::SubTypeName[i] != "") return (CCopasiMethod::SubType) i;
else return CCopasiMethod::unset;
}
CCopasiMethod::CCopasiMethod():
CCopasiParameterGroup("NoName", NULL, "Method"),
mType(CCopasiTask::unset),
mSubType(unset),
mpCallBack(NULL)
//mpReport(NULL)
{setObjectName(SubTypeName[mType]);}
CCopasiMethod::CCopasiMethod(const CCopasiTask::Type & type,
const CCopasiMethod::SubType & subType,
const CCopasiContainer * pParent):
CCopasiParameterGroup(CCopasiTask::TypeName[type], pParent, "Method"),
mType(type),
mSubType(subType),
mpCallBack(NULL)
//mpReport(NULL)
{setObjectName(SubTypeName[mSubType]);}
CCopasiMethod::CCopasiMethod(const CCopasiMethod & src,
const CCopasiContainer * pParent):
CCopasiParameterGroup(src, pParent),
mType(src.mType),
mSubType(src.mSubType),
mpCallBack(src.mpCallBack)
//mpReport(src.mpReport)
{}
CCopasiMethod::~CCopasiMethod() {}
bool CCopasiMethod::setCallBack(CProcessReport * pCallBack)
{
mpCallBack = pCallBack;
return true;
}
const CCopasiTask::Type & CCopasiMethod::getType() const {return mType;}
// void CCopasiMethod::setType(const CCopasiTask::Type & type) {mType = type;}
const CCopasiMethod::SubType & CCopasiMethod::getSubType() const
{return mSubType;}
// void CCopasiMethod::setSubType(const CCopasiMethod::SubType & subType)
// {mSubType = subType;}
//virtual
bool CCopasiMethod::isValidProblem(const CCopasiProblem * pProblem)
{
if (!pProblem)
{
//no problem
CCopasiMessage(CCopasiMessage::EXCEPTION, MCCopasiMethod + 2);
return false;
}
if (! pProblem->getModel())
{
//no model
CCopasiMessage(CCopasiMessage::EXCEPTION, MCCopasiMethod + 3);
return false;
}
return true;
}
void CCopasiMethod::load(CReadConfig & /* configBuffer */,
CReadConfig::Mode /* mode */)
{fatalError();}
void CCopasiMethod::print(std::ostream * ostream) const
{*ostream << *this;}
std::ostream &operator<<(std::ostream &os, const CCopasiMethod & o)
{
os << "Method: " << o.getObjectName() << std::endl;
CCopasiParameterGroup::parameterGroup::const_iterator it =
o.CCopasiParameter::getValue().pGROUP->begin();
CCopasiParameterGroup::parameterGroup::const_iterator end =
o.CCopasiParameter::getValue().pGROUP->end();
for (; it != end; ++it)
{
(*it)->print(&os);
os << std::endl;
}
return os;
}
<commit_msg>Added missing XMLType.<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CCopasiMethod.cpp,v $
// $Revision: 1.47 $
// $Name: $
// $Author: shoops $
// $Date: 2007/11/27 00:43:45 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
/**
* CCopasiMethod class.
* This class is used to describe a task in COPASI. This class is
* intended to be used as the parent class for all methods whithin COPASI.
*
* Created for Copasi by Stefan Hoops 2003
*/
#include "copasi.h"
#include "CCopasiMethod.h"
#include "CCopasiMessage.h"
#include "CCopasiProblem.h"
const std::string CCopasiMethod::SubTypeName[] =
{
"Not set",
"Random Search",
"Random Search (PVM)",
"Simulated Annealing",
"Genetic Algorithm",
"Evolutionary Programming",
"Steepest Descent",
"Hybrid GA/SA",
"Genetic Algorithm SR",
"Hooke & Jeeves",
"Levenberg - Marquardt",
"Nelder - Mead",
"Evolution Strategy (SRES)",
"Current Solution Statistics",
"Particle Swarm",
"Praxis",
"Truncated Newton",
"Enhanced Newton",
"Deterministic (LSODA)",
"Deterministic (LSODAR)",
"Stochastic (Gibson + Bruck)",
"Hybrid (Runge-Kutta)",
"Hybrid (LSODA)",
#ifdef COPASI_TSSA
"ILDM (LSODA)",
"CSP (LSODA)",
#endif // COPASI_TSSA
"Stochastic (\xcf\x84-Leap)",
"MCA Method (Reder)",
"Scan Framework",
"Wolf Method",
#ifdef COPASI_TSS
"Time Scale Separation Method",
#endif // COPASI_TSS
"Sensitivities Method",
#ifdef COPASI_SSA
"Stoichiometric Stability Analysis Method",
#endif // COPASI_SSA
#ifdef COPASI_EXTREMECURRENTS
"Extreme Current Calculator",
#endif // COPAISI_EXTREMECURRENTS
"EFM Algorithm",
""
};
const char* CCopasiMethod::XMLSubType[] =
{
"NotSet",
"RandomSearch",
"RandomSearch(PVM)",
"SimulatedAnnealing",
"GeneticAlgorithm",
"EvolutionaryProgram",
"SteepestDescent",
"HybridGASA",
"GeneticAlgorithmSR",
"HookeJeeves",
"LevenbergMarquardt",
"NelderMead",
"EvolutionaryStrategySR",
"CurrentSolutionStatistics",
"ParticleSwarm",
"Praxis",
"TruncatedNewton",
"EnhancedNewton",
"Deterministic(LSODA)",
"Deterministic(LSODAR)",
"Stochastic",
"Hybrid",
"Hybrid (LSODA)",
#ifdef COPASI_DEBUG
"TimeScaleSeparation(ILDM)",
"TimeScaleSeparation(CSP)",
#endif // COPASI_DEBUG
"TauLeap",
"MCAMethod(Reder)",
"ScanFramework",
"WolfMethod",
#ifdef COPASI_TSS
"TimeScaleSeparationMethod",
#endif // COPASI_TSS
"SensitivitiesMethod",
#ifdef COPASI_SSA
"SSAMethod",
#endif // COPASI_SSA
#ifdef COPASI_EXTREMECURRENTS
"ExtremeCurrentCalculator",
#endif // COPASI_EXTREMECURRENTS
"EFMAlgorithm",
NULL
};
// std::string mType;
CCopasiMethod::SubType CCopasiMethod::TypeNameToEnum(const std::string & subTypeName)
{
unsigned C_INT32 i = 0;
while (SubTypeName[i] != subTypeName && SubTypeName[i] != "")
i++;
if (CCopasiMethod::SubTypeName[i] != "") return (CCopasiMethod::SubType) i;
else return CCopasiMethod::unset;
}
CCopasiMethod::CCopasiMethod():
CCopasiParameterGroup("NoName", NULL, "Method"),
mType(CCopasiTask::unset),
mSubType(unset),
mpCallBack(NULL)
//mpReport(NULL)
{setObjectName(SubTypeName[mType]);}
CCopasiMethod::CCopasiMethod(const CCopasiTask::Type & type,
const CCopasiMethod::SubType & subType,
const CCopasiContainer * pParent):
CCopasiParameterGroup(CCopasiTask::TypeName[type], pParent, "Method"),
mType(type),
mSubType(subType),
mpCallBack(NULL)
//mpReport(NULL)
{setObjectName(SubTypeName[mSubType]);}
CCopasiMethod::CCopasiMethod(const CCopasiMethod & src,
const CCopasiContainer * pParent):
CCopasiParameterGroup(src, pParent),
mType(src.mType),
mSubType(src.mSubType),
mpCallBack(src.mpCallBack)
//mpReport(src.mpReport)
{}
CCopasiMethod::~CCopasiMethod() {}
bool CCopasiMethod::setCallBack(CProcessReport * pCallBack)
{
mpCallBack = pCallBack;
return true;
}
const CCopasiTask::Type & CCopasiMethod::getType() const {return mType;}
// void CCopasiMethod::setType(const CCopasiTask::Type & type) {mType = type;}
const CCopasiMethod::SubType & CCopasiMethod::getSubType() const
{return mSubType;}
// void CCopasiMethod::setSubType(const CCopasiMethod::SubType & subType)
// {mSubType = subType;}
//virtual
bool CCopasiMethod::isValidProblem(const CCopasiProblem * pProblem)
{
if (!pProblem)
{
//no problem
CCopasiMessage(CCopasiMessage::EXCEPTION, MCCopasiMethod + 2);
return false;
}
if (! pProblem->getModel())
{
//no model
CCopasiMessage(CCopasiMessage::EXCEPTION, MCCopasiMethod + 3);
return false;
}
return true;
}
void CCopasiMethod::load(CReadConfig & /* configBuffer */,
CReadConfig::Mode /* mode */)
{fatalError();}
void CCopasiMethod::print(std::ostream * ostream) const
{*ostream << *this;}
std::ostream &operator<<(std::ostream &os, const CCopasiMethod & o)
{
os << "Method: " << o.getObjectName() << std::endl;
CCopasiParameterGroup::parameterGroup::const_iterator it =
o.CCopasiParameter::getValue().pGROUP->begin();
CCopasiParameterGroup::parameterGroup::const_iterator end =
o.CCopasiParameter::getValue().pGROUP->end();
for (; it != end; ++it)
{
(*it)->print(&os);
os << std::endl;
}
return os;
}
<|endoftext|> |
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NConnection.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-12-14 09:40:56 $
*
* 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_EVOAB_CONNECTION_HXX_
#define _CONNECTIVITY_EVOAB_CONNECTION_HXX_
#ifndef _CONNECTIVITY_EVOAB_DRIVER_HXX_
#include "NDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_
#include "OSubComponent.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _CONNECTIVITY_EVOAB_EVOLUTION_API_HXX_
#include "EApi.h"
#endif
namespace connectivity
{
namespace evoab
{
namespace SDBCAddress {
typedef enum {
Unknown = 0,
EVO_LOCAL = 1,
EVO_LDAP = 2,
EVO_GWISE = 3
} sdbc_address_type;
}
typedef connectivity::OMetaConnection OConnection_BASE; // implements basics and text encoding
class OEvoabConnection : public OConnection_BASE,
public connectivity::OSubComponent<OEvoabConnection, OConnection_BASE>
{
friend class connectivity::OSubComponent<OEvoabConnection, OConnection_BASE>;
private:
OEvoabDriver *m_pDriver;
::rtl::OUString m_pCurrentTableName;
SDBCAddress::sdbc_address_type m_eSDBCAddressType;
protected:
::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier> m_xCatalog;
::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
rtl::OString m_aPassword;
connectivity::OWeakRefArray m_aStatements; // vector containing a list
// of all the Statement objects
// for this Connection
public:
OEvoabConnection(OEvoabDriver* _pDriver);
virtual ~OEvoabConnection();
virtual void construct(const ::rtl::OUString& _rUrl,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo ) throw( ::com::sun::star::sdbc::SQLException);
inline rtl::OString getPassword() { return m_aPassword; }
inline void setPassword( rtl::OString aStr ) { m_aPassword = aStr; }
inline rtl::OUString& getCurrentTableName() {return m_pCurrentTableName;}
inline void setCurrentTableName(::rtl::OUString _name) {m_pCurrentTableName=_name;}
// own methods
inline const OEvoabDriver* getDriver() const { return static_cast< const OEvoabDriver* >( m_pDriver ); }
SDBCAddress::sdbc_address_type getSDBCAddressType() const { return m_eSDBCAddressType;}
void setSDBCAddressType(SDBCAddress::sdbc_address_type _eSDBCAddressType) {m_eSDBCAddressType = _eSDBCAddressType;}
// OComponentHelper
virtual void SAL_CALL disposing(void);
// XInterface
virtual void SAL_CALL release() throw();
// XServiceInfo
DECLARE_SERVICE_INFO();
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XWarningsSupplier
virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_EVOAB_CONNECTION_HXX_
<commit_msg>INTEGRATION: CWS dba24d (1.4.286); FILE MERGED 2007/11/21 12:43:22 oj 1.4.286.1: #i68854# impl TypeSettingInfo for Oracle and some clean up<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NConnection.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2008-01-30 07:51:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_EVOAB_CONNECTION_HXX_
#define _CONNECTIVITY_EVOAB_CONNECTION_HXX_
#ifndef _CONNECTIVITY_EVOAB_DRIVER_HXX_
#include "NDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_
#include "OSubComponent.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _CONNECTIVITY_EVOAB_EVOLUTION_API_HXX_
#include "EApi.h"
#endif
namespace connectivity
{
namespace evoab
{
namespace SDBCAddress {
typedef enum {
Unknown = 0,
EVO_LOCAL = 1,
EVO_LDAP = 2,
EVO_GWISE = 3
} sdbc_address_type;
}
typedef connectivity::OMetaConnection OConnection_BASE; // implements basics and text encoding
class OEvoabConnection : public OConnection_BASE,
public connectivity::OSubComponent<OEvoabConnection, OConnection_BASE>
{
friend class connectivity::OSubComponent<OEvoabConnection, OConnection_BASE>;
private:
OEvoabDriver *m_pDriver;
::rtl::OUString m_pCurrentTableName;
SDBCAddress::sdbc_address_type m_eSDBCAddressType;
protected:
::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier> m_xCatalog;
rtl::OString m_aPassword;
public:
OEvoabConnection(OEvoabDriver* _pDriver);
virtual ~OEvoabConnection();
virtual void construct(const ::rtl::OUString& _rUrl,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo ) throw( ::com::sun::star::sdbc::SQLException);
inline rtl::OString getPassword() { return m_aPassword; }
inline void setPassword( rtl::OString aStr ) { m_aPassword = aStr; }
inline rtl::OUString& getCurrentTableName() {return m_pCurrentTableName;}
inline void setCurrentTableName(::rtl::OUString _name) {m_pCurrentTableName=_name;}
// own methods
inline const OEvoabDriver* getDriver() const { return static_cast< const OEvoabDriver* >( m_pDriver ); }
SDBCAddress::sdbc_address_type getSDBCAddressType() const { return m_eSDBCAddressType;}
void setSDBCAddressType(SDBCAddress::sdbc_address_type _eSDBCAddressType) {m_eSDBCAddressType = _eSDBCAddressType;}
// OComponentHelper
virtual void SAL_CALL disposing(void);
// XInterface
virtual void SAL_CALL release() throw();
// XServiceInfo
DECLARE_SERVICE_INFO();
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XWarningsSupplier
virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_EVOAB_CONNECTION_HXX_
<|endoftext|> |
<commit_before>/** creative_filters.cc -*- C++ -*-
Rémi Attab, 09 Aug 2013
Copyright (c) 2013 Datacratic. All rights reserved.
Registry and implementation of the creative filters.
*/
#include "creative_filters.h"
using namespace std;
using namespace ML;
namespace RTBKIT {
void
CreativeSegmentsFilter::filter(FilterState& state) const
{
unordered_set<string> toCheck = excludeIfNotPresent;
for (const auto& segment : state.request.segments) {
toCheck.erase(segment.first);
auto it = data.find(segment.first);
if (it == data.end()) continue;
CreativeMatrix result = it->second.ie.filter(*segment.second);
state.narrowAllCreatives(result);
if (state.configs().empty()) return;
}
for (const auto& segment : toCheck) {
auto it = data.find(segment);
if (it == data.end()) continue;
CreativeMatrix result = it->second.excludeIfNotPresent.negate();
state.narrowAllCreatives(result);
if (state.configs().empty()) return;
}
}
void CreativeSegmentsFilter::setCreative(unsigned configIndex,
unsigned crIndex, const Creative& creative, bool value)
{
for (const auto& entry : creative.segments) {
auto& segment = data[entry.first];
segment.ie.addInclude(configIndex, crIndex, entry.second.include);
segment.ie.addExclude(configIndex, crIndex, entry.second.exclude);
if (entry.second.excludeIfNotPresent) {
if (value && segment.excludeIfNotPresent.empty())
excludeIfNotPresent.insert(entry.first);
segment.excludeIfNotPresent.set(crIndex, configIndex, value);
if (!value && segment.excludeIfNotPresent.empty())
excludeIfNotPresent.erase(entry.first);
}
}
}
/******************************************************************************/
/* INIT FILTERS */
/******************************************************************************/
namespace {
struct InitFilters
{
InitFilters()
{
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeFormatFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeLanguageFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeLocationFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeExchangeNameFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeExchangeFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeSegmentsFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativePMPFilter>();
}
} initFilters;
} // namespace anonymous
} // namepsace RTBKIT
<commit_msg>creative segment filter now properly deregisters configs.<commit_after>/** creative_filters.cc -*- C++ -*-
Rémi Attab, 09 Aug 2013
Copyright (c) 2013 Datacratic. All rights reserved.
Registry and implementation of the creative filters.
*/
#include "creative_filters.h"
using namespace std;
using namespace ML;
namespace RTBKIT {
/******************************************************************************/
/* CREATIVE SEGMENTS FILTER */
/******************************************************************************/
void
CreativeSegmentsFilter::
filter(FilterState& state) const
{
unordered_set<string> toCheck = excludeIfNotPresent;
for (const auto& segment : state.request.segments) {
toCheck.erase(segment.first);
auto it = data.find(segment.first);
if (it == data.end()) continue;
CreativeMatrix result = it->second.ie.filter(*segment.second);
state.narrowAllCreatives(result);
if (state.configs().empty()) return;
}
for (const auto& segment : toCheck) {
auto it = data.find(segment);
if (it == data.end()) continue;
CreativeMatrix result = it->second.excludeIfNotPresent.negate();
state.narrowAllCreatives(result);
if (state.configs().empty()) return;
}
}
void
CreativeSegmentsFilter::
setCreative(unsigned configIndex, unsigned crIndex, const Creative& creative, bool value)
{
for (const auto& entry : creative.segments) {
auto& segment = data[entry.first];
segment.ie.setInclude(configIndex, crIndex, value, entry.second.include);
segment.ie.setExclude(configIndex, crIndex, value, entry.second.exclude);
if (entry.second.excludeIfNotPresent) {
if (value && segment.excludeIfNotPresent.empty())
excludeIfNotPresent.insert(entry.first);
segment.excludeIfNotPresent.set(crIndex, configIndex, value);
if (!value && segment.excludeIfNotPresent.empty())
excludeIfNotPresent.erase(entry.first);
}
}
}
/******************************************************************************/
/* INIT FILTERS */
/******************************************************************************/
namespace {
struct InitFilters
{
InitFilters()
{
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeFormatFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeLanguageFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeLocationFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeExchangeNameFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeExchangeFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativeSegmentsFilter>();
RTBKIT::FilterRegistry::registerFilter<RTBKIT::CreativePMPFilter>();
}
} initFilters;
} // namespace anonymous
} // namepsace RTBKIT
<|endoftext|> |
<commit_before>/** analytics_endpoint.cc -*- C++ -*-
Michael Burkat, 22 Oct 2014
Copyright (c) 2014 Datacratic. All rights reserved.
Analytics endpoint used to log events on different channels.
*/
#include <iostream>
#include <functional>
#include "analytics_endpoint.h"
#include "soa/service/message_loop.h"
#include "soa/service/http_client.h"
#include "soa/service/rest_request_binding.h"
#include "soa/jsoncpp/reader.h"
#include "jml/arch/timers.h"
using namespace std;
using namespace Datacratic;
/********************************************************************************/
/* ANALYTICS REST ENDPOINT */
/********************************************************************************/
AnalyticsRestEndpoint::
AnalyticsRestEndpoint(shared_ptr<ServiceProxies> proxies,
const std::string & serviceName)
: ServiceBase(serviceName, proxies),
RestServiceEndpoint(proxies->zmqContext)
{
httpEndpoint.allowAllOrigins();
}
void
AnalyticsRestEndpoint::
initChannels(unordered_map<string, bool> & channels)
{
channelFilter = channels;
}
void
AnalyticsRestEndpoint::
init()
{
// last param in init is threads increase it accordingly to needs.
RestServiceEndpoint::init(getServices()->config, serviceName(), 0.005, 1);
onHandleRequest = router.requestHandler();
registerServiceProvider(serviceName(), { "analytics" });
router.description = "Analytics REST API";
router.addHelpRoute("/", "GET");
RestRequestRouter::OnProcessRequest pingRoute
= [=] (const RestServiceEndpoint::ConnectionId & connection,
const RestRequest & request,
const RestRequestParsingContext & context) {
recordHit("beat");
connection.sendResponse(200, "beat");
return RestRequestRouter::MR_YES;
};
router.addRoute("/heartbeat", "GET", "availability request", pingRoute,
Json::Value());
auto & versionNode = router.addSubRouter("/v1", "version 1 of API");
addRouteSyncReturn(versionNode,
"/event",
{"POST","PUT"},
"Add an event to the logs.",
"Returns a success notice.",
[] (const string & r) {
Json::Value response(Json::stringValue);
response = r;
return response;
},
&AnalyticsRestEndpoint::addEvent,
this,
JsonParam<string>("channel", "channel to use for event"),
JsonParam<string>("event", "event to publish")
);
addRouteSyncReturn(versionNode,
"/channels",
{"GET"},
"Gets the list of available channels",
"Returns a list of channels and their status.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::listChannels,
this
);
addRouteSyncReturn(versionNode,
"/enable",
{"POST", "PUT"},
"Start logging a certain channel of event.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::enableChannel,
this,
RestParamDefault<string>("channel", "event channel to enable", "")
);
addRouteSyncReturn(versionNode,
"/disable",
{"POST", "PUT"},
"Stop logging a certain channel of event.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::disableChannel,
this,
RestParamDefault<string>("channel", "event channel to disable", "")
);
addRouteSyncReturn(versionNode,
"/enableAll",
{"POST", "PUT"},
"Start logging on all known channels of events.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::enableAllChannels,
this
);
addRouteSyncReturn(versionNode,
"/disableAll",
{"POST", "PUT"},
"Stop logging on all channels of events.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::disableAllChannels,
this
);
}
string
AnalyticsRestEndpoint::
print(const string & channel, const string & event) const
{
cout << channel << " " << event << endl;
return "success";
}
string
AnalyticsRestEndpoint::
addEvent(const string & channel, const string & event) const
{
boost::shared_lock<boost::shared_mutex> lock(access);
auto it = channelFilter.find(channel);
if (it == channelFilter.end() || !it->second)
return "channel not found or not enabled";
return print(channel, event);
}
Json::Value
AnalyticsRestEndpoint::
listChannels() const
{
boost::shared_lock<boost::shared_mutex> lock(access);
Json::Value response(Json::objectValue);
for (const auto & channel : channelFilter)
response[channel.first] = channel.second;
return response;
}
Json::Value
AnalyticsRestEndpoint::
enableChannel(const string & channel)
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
if (!channel.empty() && !channelFilter[channel])
channelFilter[channel] = true;
}
return listChannels();
}
Json::Value
AnalyticsRestEndpoint::
enableAllChannels()
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
for (auto & channel : channelFilter)
channel.second = true;
}
return listChannels();
}
Json::Value
AnalyticsRestEndpoint::
disableAllChannels()
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
for (auto & channel : channelFilter)
channel.second = false;
}
return listChannels();
}
Json::Value
AnalyticsRestEndpoint::
disableChannel(const string & channel)
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
if (!channel.empty() && channelFilter[channel])
channelFilter[channel] = false;
}
return listChannels();
}
pair<string, string>
AnalyticsRestEndpoint::
bindTcp(int port)
{
pair<string, string> location;
if (port)
location = RestServiceEndpoint::bindTcp(PortRange(), PortRange(port));
else
location = RestServiceEndpoint::bindTcp(PortRange(), getServices()->ports->getRange("analytics"));
cout << "Analytics listening on http port: " << location.second << endl;
return location;
}
void
AnalyticsRestEndpoint::
start()
{
RestServiceEndpoint::start();
}
void
AnalyticsRestEndpoint::
shutdown()
{
RestServiceEndpoint::shutdown();
}
<commit_msg>added a graphite key to make a perf comparison<commit_after>/** analytics_endpoint.cc -*- C++ -*-
Michael Burkat, 22 Oct 2014
Copyright (c) 2014 Datacratic. All rights reserved.
Analytics endpoint used to log events on different channels.
*/
#include <iostream>
#include <functional>
#include "analytics_endpoint.h"
#include "soa/service/message_loop.h"
#include "soa/service/http_client.h"
#include "soa/service/rest_request_binding.h"
#include "soa/jsoncpp/reader.h"
#include "jml/arch/timers.h"
using namespace std;
using namespace Datacratic;
/********************************************************************************/
/* ANALYTICS REST ENDPOINT */
/********************************************************************************/
AnalyticsRestEndpoint::
AnalyticsRestEndpoint(shared_ptr<ServiceProxies> proxies,
const std::string & serviceName)
: ServiceBase(serviceName, proxies),
RestServiceEndpoint(proxies->zmqContext)
{
httpEndpoint.allowAllOrigins();
}
void
AnalyticsRestEndpoint::
initChannels(unordered_map<string, bool> & channels)
{
channelFilter = channels;
}
void
AnalyticsRestEndpoint::
init()
{
// last param in init is threads increase it accordingly to needs.
RestServiceEndpoint::init(getServices()->config, serviceName(), 0.005, 1);
onHandleRequest = router.requestHandler();
registerServiceProvider(serviceName(), { "analytics" });
router.description = "Analytics REST API";
router.addHelpRoute("/", "GET");
RestRequestRouter::OnProcessRequest pingRoute
= [=] (const RestServiceEndpoint::ConnectionId & connection,
const RestRequest & request,
const RestRequestParsingContext & context) {
recordHit("beat");
connection.sendResponse(200, "beat");
return RestRequestRouter::MR_YES;
};
router.addRoute("/heartbeat", "GET", "availability request", pingRoute,
Json::Value());
auto & versionNode = router.addSubRouter("/v1", "version 1 of API");
addRouteSyncReturn(versionNode,
"/event",
{"POST","PUT"},
"Add an event to the logs.",
"Returns a success notice.",
[] (const string & r) {
Json::Value response(Json::stringValue);
response = r;
return response;
},
&AnalyticsRestEndpoint::addEvent,
this,
JsonParam<string>("channel", "channel to use for event"),
JsonParam<string>("event", "event to publish")
);
addRouteSyncReturn(versionNode,
"/channels",
{"GET"},
"Gets the list of available channels",
"Returns a list of channels and their status.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::listChannels,
this
);
addRouteSyncReturn(versionNode,
"/enable",
{"POST", "PUT"},
"Start logging a certain channel of event.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::enableChannel,
this,
RestParamDefault<string>("channel", "event channel to enable", "")
);
addRouteSyncReturn(versionNode,
"/disable",
{"POST", "PUT"},
"Stop logging a certain channel of event.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::disableChannel,
this,
RestParamDefault<string>("channel", "event channel to disable", "")
);
addRouteSyncReturn(versionNode,
"/enableAll",
{"POST", "PUT"},
"Start logging on all known channels of events.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::enableAllChannels,
this
);
addRouteSyncReturn(versionNode,
"/disableAll",
{"POST", "PUT"},
"Stop logging on all channels of events.",
"Returns a list of channels.",
[] (const Json::Value & lst) {
return lst;
},
&AnalyticsRestEndpoint::disableAllChannels,
this
);
}
string
AnalyticsRestEndpoint::
print(const string & channel, const string & event) const
{
recordHit("channel." + channel);
cout << channel << " " << event << endl;
return "success";
}
string
AnalyticsRestEndpoint::
addEvent(const string & channel, const string & event) const
{
boost::shared_lock<boost::shared_mutex> lock(access);
auto it = channelFilter.find(channel);
if (it == channelFilter.end() || !it->second)
return "channel not found or not enabled";
return print(channel, event);
}
Json::Value
AnalyticsRestEndpoint::
listChannels() const
{
boost::shared_lock<boost::shared_mutex> lock(access);
Json::Value response(Json::objectValue);
for (const auto & channel : channelFilter)
response[channel.first] = channel.second;
return response;
}
Json::Value
AnalyticsRestEndpoint::
enableChannel(const string & channel)
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
if (!channel.empty() && !channelFilter[channel])
channelFilter[channel] = true;
}
return listChannels();
}
Json::Value
AnalyticsRestEndpoint::
enableAllChannels()
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
for (auto & channel : channelFilter)
channel.second = true;
}
return listChannels();
}
Json::Value
AnalyticsRestEndpoint::
disableAllChannels()
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
for (auto & channel : channelFilter)
channel.second = false;
}
return listChannels();
}
Json::Value
AnalyticsRestEndpoint::
disableChannel(const string & channel)
{
{
boost::lock_guard<boost::shared_mutex> guard(access);
if (!channel.empty() && channelFilter[channel])
channelFilter[channel] = false;
}
return listChannels();
}
pair<string, string>
AnalyticsRestEndpoint::
bindTcp(int port)
{
pair<string, string> location;
if (port)
location = RestServiceEndpoint::bindTcp(PortRange(), PortRange(port));
else
location = RestServiceEndpoint::bindTcp(PortRange(), getServices()->ports->getRange("analytics"));
cout << "Analytics listening on http port: " << location.second << endl;
return location;
}
void
AnalyticsRestEndpoint::
start()
{
RestServiceEndpoint::start();
}
void
AnalyticsRestEndpoint::
shutdown()
{
RestServiceEndpoint::shutdown();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _GLOBNAME_HXX
#define _GLOBNAME_HXX
#include "tools/toolsdllapi.h"
#include <com/sun/star/uno/Sequence.hxx>
#include <tools/string.hxx>
#include <tools/list.hxx>
/*************************************************************************
*************************************************************************/
struct ImpSvGlobalName
{
sal_Int8 szData[ 16 ];
sal_uInt16 nRefCount;
ImpSvGlobalName()
{
nRefCount = 0;
}
ImpSvGlobalName( const ImpSvGlobalName & rObj );
ImpSvGlobalName( int );
sal_Bool operator == ( const ImpSvGlobalName & rObj ) const;
};
#ifdef WNT
struct _GUID;
typedef struct _GUID GUID;
#else
struct GUID;
#endif
typedef GUID CLSID;
class SvStream;
class SvGlobalNameList;
class TOOLS_DLLPUBLIC SvGlobalName
{
friend class SvGlobalNameList;
ImpSvGlobalName * pImp;
void NewImp();
public:
SvGlobalName();
SvGlobalName( const SvGlobalName & rObj )
{
pImp = rObj.pImp;
pImp->nRefCount++;
}
SvGlobalName( ImpSvGlobalName * pImpP )
{
pImp = pImpP;
pImp->nRefCount++;
}
SvGlobalName( sal_uInt32 n1, sal_uInt16 n2, sal_uInt16 n3,
sal_Int8 b8, sal_Int8 b9, sal_Int8 b10, sal_Int8 b11,
sal_Int8 b12, sal_Int8 b13, sal_Int8 b14, sal_Int8 b15 );
// create SvGlobalName from a platform independent representation
SvGlobalName( const ::com::sun::star::uno::Sequence< sal_Int8 >& aSeq );
SvGlobalName & operator = ( const SvGlobalName & rObj );
~SvGlobalName();
TOOLS_DLLPUBLIC friend SvStream & operator >> ( SvStream &, SvGlobalName & );
TOOLS_DLLPUBLIC friend SvStream & operator << ( SvStream &, const SvGlobalName & );
sal_Bool operator < ( const SvGlobalName & rObj ) const;
SvGlobalName & operator += ( sal_uInt32 );
SvGlobalName & operator ++ () { return operator += ( 1 ); }
sal_Bool operator == ( const SvGlobalName & rObj ) const;
sal_Bool operator != ( const SvGlobalName & rObj ) const
{ return !(*this == rObj); }
void MakeFromMemory( void * pData );
sal_Bool MakeId( const String & rId );
String GetctorName() const;
String GetHexName() const;
String GetRegDbName() const
{
String a = '{';
a += GetHexName();
a += '}';
return a;
}
SvGlobalName( const CLSID & rId );
const CLSID & GetCLSID() const { return *(CLSID *)pImp->szData; }
const sal_Int8* GetBytes() const { return pImp->szData; }
// platform independent representation of a "GlobalName"
// maybe transported remotely
com::sun::star::uno::Sequence < sal_Int8 > GetByteSequence() const;
};
class SvGlobalNameList
{
List aList;
public:
SvGlobalNameList();
~SvGlobalNameList();
void Append( const SvGlobalName & );
SvGlobalName GetObject( sal_uInt32 );
sal_Bool IsEntry( const SvGlobalName & rName );
sal_uInt32 Count() const { return aList.Count(); }
private:
// nicht erlaubt
SvGlobalNameList( const SvGlobalNameList & );
SvGlobalNameList & operator = ( const SvGlobalNameList & );
};
#endif // _GLOBNAME_HXX
<commit_msg>removetooltypes01: #i112600# replace BYTE with sal_uInt8<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _GLOBNAME_HXX
#define _GLOBNAME_HXX
#include "tools/toolsdllapi.h"
#include <com/sun/star/uno/Sequence.hxx>
#include <tools/string.hxx>
#include <tools/list.hxx>
/*************************************************************************
*************************************************************************/
struct ImpSvGlobalName
{
sal_Int8 szData[ 16 ];
sal_uInt16 nRefCount;
ImpSvGlobalName()
{
nRefCount = 0;
}
ImpSvGlobalName( const ImpSvGlobalName & rObj );
ImpSvGlobalName( int );
sal_Bool operator == ( const ImpSvGlobalName & rObj ) const;
};
#ifdef WNT
struct _GUID;
typedef struct _GUID GUID;
#else
struct GUID;
#endif
typedef GUID CLSID;
class SvStream;
class SvGlobalNameList;
class TOOLS_DLLPUBLIC SvGlobalName
{
friend class SvGlobalNameList;
ImpSvGlobalName * pImp;
void NewImp();
public:
SvGlobalName();
SvGlobalName( const SvGlobalName & rObj )
{
pImp = rObj.pImp;
pImp->nRefCount++;
}
SvGlobalName( ImpSvGlobalName * pImpP )
{
pImp = pImpP;
pImp->nRefCount++;
}
SvGlobalName( sal_uInt32 n1, sal_uInt16 n2, sal_uInt16 n3,
sal_uInt8 b8, sal_uInt8 b9, sal_uInt8 b10, sal_uInt8 b11,
sal_uInt8 b12, sal_uInt8 b13, sal_uInt8 b14, sal_uInt8 b15 );
// create SvGlobalName from a platform independent representation
SvGlobalName( const ::com::sun::star::uno::Sequence< sal_Int8 >& aSeq );
SvGlobalName & operator = ( const SvGlobalName & rObj );
~SvGlobalName();
TOOLS_DLLPUBLIC friend SvStream & operator >> ( SvStream &, SvGlobalName & );
TOOLS_DLLPUBLIC friend SvStream & operator << ( SvStream &, const SvGlobalName & );
sal_Bool operator < ( const SvGlobalName & rObj ) const;
SvGlobalName & operator += ( sal_uInt32 );
SvGlobalName & operator ++ () { return operator += ( 1 ); }
sal_Bool operator == ( const SvGlobalName & rObj ) const;
sal_Bool operator != ( const SvGlobalName & rObj ) const
{ return !(*this == rObj); }
void MakeFromMemory( void * pData );
sal_Bool MakeId( const String & rId );
String GetctorName() const;
String GetHexName() const;
String GetRegDbName() const
{
String a = '{';
a += GetHexName();
a += '}';
return a;
}
SvGlobalName( const CLSID & rId );
const CLSID & GetCLSID() const { return *(CLSID *)pImp->szData; }
const sal_Int8* GetBytes() const { return pImp->szData; }
// platform independent representation of a "GlobalName"
// maybe transported remotely
com::sun::star::uno::Sequence < sal_Int8 > GetByteSequence() const;
};
class SvGlobalNameList
{
List aList;
public:
SvGlobalNameList();
~SvGlobalNameList();
void Append( const SvGlobalName & );
SvGlobalName GetObject( sal_uInt32 );
sal_Bool IsEntry( const SvGlobalName & rName );
sal_uInt32 Count() const { return aList.Count(); }
private:
// nicht erlaubt
SvGlobalNameList( const SvGlobalNameList & );
SvGlobalNameList & operator = ( const SvGlobalNameList & );
};
#endif // _GLOBNAME_HXX
<|endoftext|> |
<commit_before>#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QDoubleSpinBox>
#include <QSpinBox>
#include <QPushButton>
#include <QMessageBox>
#include <QFuture>
#include <QtConcurrentRun>
#include <QWidget>
#include <QTabWidget>
#include <QDebug>
#include <QLabel>
#include <QRadioButton>
#include <QLineEdit>
#include <QFileDialog>
#include <string>
#include <iostream>
#include "fanuc_grinding_rviz_plugin.h"
namespace fanuc_grinding_rviz_plugin
{
FanucGrindingRvizPlugin::FanucGrindingRvizPlugin(QWidget* parent) :
rviz::Panel(parent)
{
// Create Tabs
tab_widget_ = new QTabWidget();
scanning_widget_ = new ScanningWidget();
alignment_widget_ = new AlignmentWidget();
comparison_widget_ = new ComparisonWidget();
path_planning_widget_ = new PathPlanningWidget();
post_processor_widget_ = new PostProcessorWidget();
tab_widget_->addTab(scanning_widget_, "Scanning");
tab_widget_->addTab(alignment_widget_, "Alignment");
tab_widget_->addTab(comparison_widget_, "Comparison");
tab_widget_->addTab(path_planning_widget_, "Path planning");
tab_widget_->addTab(post_processor_widget_, "Post processor");
tab_widget_->setTabEnabled(0, true);
tab_widget_->setTabEnabled(1, false);
tab_widget_->setTabEnabled(2, false);
tab_widget_->setTabEnabled(3, false);
tab_widget_->setTabEnabled(4, false);
// Bottom status layout
QVBoxLayout *status_layout_ = new QVBoxLayout;
status_layout_->addWidget(new QLabel("Status:"));
// Global Layout
QVBoxLayout *global_layout_ = new QVBoxLayout;
global_layout_->addWidget(tab_widget_);
global_layout_->addLayout(status_layout_);
status_label_ = new QLabel;
global_layout_->addWidget(status_label_);
setLayout(global_layout_);
// Connect handlers
// SCANNING
// Will display a status in general status label ( from scanning widget )
connect(scanning_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(scanning_widget_, SIGNAL(sendMsgBox(QString, QString , QString)),
this, SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that scanning_widget_ is modified
connect(scanning_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable AlignementPanel when scanning_widget_ will send the SIGNAL
connect(scanning_widget_, SIGNAL(enablePanelAlignment()), this, SLOT(enablePanelAlignmentHandler()));
// Enable general panel when scanning_widget_ send the SIGNAL
connect(scanning_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Will send information about cad and scan in the other widgets
connect(scanning_widget_, SIGNAL(sendCADDatas(QString, QString)),
this, SLOT(setCADDatas(QString, QString)));
connect(scanning_widget_, SIGNAL(sendScanDatas(QString, QString)),
this, SLOT(setScanDatas(QString, QString)));
// For the demonstrator, we will skip alignment and comparison parts for the moment
connect(scanning_widget_, SIGNAL(enablePanelPathPlanning()), this, SLOT(enablePanelPathPlanningHandler()));
//ALIGNMENT
// Will display a status in general status label ( from alignment widget )
connect(alignment_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(alignment_widget_, SIGNAL(sendMsgBox(QString, QString , QString)),
this, SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that alignment_widget_ is modified
connect(alignment_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable compoarison_panel when alignment_widget_ will send the SIGNAL
connect(alignment_widget_,SIGNAL(enablePanelComparison()), this, SLOT(enablePanelComparisonHandler()));
// Enable general panel when alignment_widget_ send the SIGNAL
connect(alignment_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Received a signal from alignment widget in order to get CAD and scan params
connect(alignment_widget_, SIGNAL(getCADAndScanParams()), this, SLOT(sendCADAndScanDatasSlot()));
// Send a signal to alignment widget in order to give CAD and scan params
connect(this , SIGNAL(sendCADAndScanDatas(const QString, const QString, const QString, const QString)),
alignment_widget_, SLOT(setCADAndScanParams(const QString, const QString, const QString, const QString)));
//COMPARISON
// Will display a status in general status label ( from comparison widget )
connect(comparison_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(comparison_widget_, SIGNAL(sendMsgBox(QString, QString , QString)),
this, SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that comparison_widget_ is modified
connect(comparison_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable path_planning_widget when comparison_widget_ will send the SIGNAL
connect(comparison_widget_,SIGNAL(enablePanelPathPlanning()), this, SLOT(enablePanelPathPlanningHandler()));
// Enable general panel when comparison_widget_ send the SIGNAL
connect(comparison_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Received a signal from comparison widget in order to get CAD and scan params
connect(comparison_widget_, SIGNAL(getCADAndScanParams()), this, SLOT(sendCADAndScanDatasSlot()));
// Send a signal to comparison widget in order to give CAD and scan params
connect(this , SIGNAL(sendCADAndScanDatas(const QString, const QString, const QString, const QString)),
comparison_widget_, SLOT(setCADAndScanParams(const QString, const QString, const QString, const QString)));
//PATH PLANNING
// Will display a status in general status label ( from path_planning widget )
connect(path_planning_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(path_planning_widget_, SIGNAL(sendMsgBox(QString, QString , QString)),
this, SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that path_planning_widget is modified
connect(path_planning_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable path_planning_widget when comparison_widget_ will send the SIGNAL
connect(path_planning_widget_, SIGNAL(enablePanelPostProcessor()), this, SLOT(enablePanelPostProcessorHandler()));
// Enable general panel when path_planning send the SIGNAL
connect(path_planning_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Received a signal from comparison widget in order to get CAD and scan params
connect(path_planning_widget_, SIGNAL(getCADAndScanParams()), this, SLOT(sendCADAndScanDatasSlot()));
// Send a signal to comparison widget in order to give CAD and scan params
connect(this , SIGNAL(sendCADAndScanDatas(const QString, const QString, const QString, const QString)),
path_planning_widget_, SLOT(setCADAndScanParams(const QString, const QString, const QString, const QString)));
//POST_PROCESSOR
// Will display a status in general status label ( from post_processor widget )
connect(post_processor_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(post_processor_widget_, SIGNAL(sendMsgBox(QString, QString, QString)),
this, SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that post_processor_widget is modified
connect(post_processor_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable general panel when post_processor send the SIGNAL
connect(post_processor_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Receive a signal from post processor widget in order to send robot poses data
connect(post_processor_widget_, SIGNAL(getRobotTrajectoryData()), this, SLOT(setRobotTrajectoryData()));
connect(this, SIGNAL(displayStatus(const QString)), this, SLOT(displayStatusHandler(const QString)));
}
FanucGrindingRvizPlugin::~FanucGrindingRvizPlugin()
{}
void FanucGrindingRvizPlugin::enablePanelAlignmentHandler()
{
tab_widget_->setTabEnabled(1, true);
}
void FanucGrindingRvizPlugin::enablePanelComparisonHandler()
{
tab_widget_->setTabEnabled(2, true);
}
void FanucGrindingRvizPlugin::enablePanelPathPlanningHandler()
{
tab_widget_->setTabEnabled(3, true);
}
void FanucGrindingRvizPlugin::enablePanelPostProcessorHandler()
{
tab_widget_->setTabEnabled(4, true);
}
void FanucGrindingRvizPlugin::enablePanelHandler(bool status)
{
setEnabled(status);
}
void FanucGrindingRvizPlugin::displayStatusHandler(const QString message)
{
status_label_->setText(message);
}
void FanucGrindingRvizPlugin::displayMsgBoxHandler(const QString title, const QString msg, const QString info_msg)
{
enablePanelHandler(false);
QMessageBox msg_box;
msg_box.setWindowTitle(title);
msg_box.setText(msg);
msg_box.setInformativeText(info_msg);
msg_box.setIcon(QMessageBox::Critical);
msg_box.setStandardButtons(QMessageBox::Ok);
msg_box.exec();
enablePanelHandler(true);
}
void FanucGrindingRvizPlugin::triggerSave()
{
Q_EMIT configChanged();
}
void FanucGrindingRvizPlugin::setCADDatas(const QString cad_filename, const QString cad_marker_name)
{
cad_filename_ = cad_filename;
cad_marker_name_ = cad_marker_name;
}
void FanucGrindingRvizPlugin::setScanDatas(const QString scan_filename, const QString scan_marker_name)
{
scan_filename_ = scan_filename;
scan_marker_name_ = scan_marker_name;
}
void FanucGrindingRvizPlugin::setRobotTrajectoryData()
{
post_processor_widget_->setRobotPoses(path_planning_widget_->getRobotPoses());
post_processor_widget_->setPointColorViz(path_planning_widget_->getPointColorViz());
post_processor_widget_->setIndexVector(path_planning_widget_->getIndexVector());
}
void FanucGrindingRvizPlugin::sendCADAndScanDatasSlot()
{
Q_EMIT sendCADAndScanDatas(cad_filename_, cad_marker_name_, scan_filename_, scan_marker_name_);
}
// Save all configuration data from this panel to the given Config object
void FanucGrindingRvizPlugin::save(rviz::Config config) const
{
rviz::Panel::save(config);
scanning_widget_->save(config);
alignment_widget_->save(config);
comparison_widget_->save(config);
path_planning_widget_->save(config);
post_processor_widget_->save(config);
}
// Load all configuration data for this panel from the given Config object.
void FanucGrindingRvizPlugin::load(const rviz::Config& config)
{
rviz::Panel::load(config);
scanning_widget_->load(config);
alignment_widget_->load(config);
comparison_widget_->load(config);
path_planning_widget_->load(config);
post_processor_widget_->load(config);
}
} // end namespace
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(fanuc_grinding_rviz_plugin::FanucGrindingRvizPlugin, rviz::Panel)
<commit_msg>Eclipse auto format on connect calls<commit_after>#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QDoubleSpinBox>
#include <QSpinBox>
#include <QPushButton>
#include <QMessageBox>
#include <QFuture>
#include <QtConcurrentRun>
#include <QWidget>
#include <QTabWidget>
#include <QDebug>
#include <QLabel>
#include <QRadioButton>
#include <QLineEdit>
#include <QFileDialog>
#include <string>
#include <iostream>
#include "fanuc_grinding_rviz_plugin.h"
namespace fanuc_grinding_rviz_plugin
{
FanucGrindingRvizPlugin::FanucGrindingRvizPlugin(QWidget* parent) :
rviz::Panel(parent)
{
// Create Tabs
tab_widget_ = new QTabWidget();
scanning_widget_ = new ScanningWidget();
alignment_widget_ = new AlignmentWidget();
comparison_widget_ = new ComparisonWidget();
path_planning_widget_ = new PathPlanningWidget();
post_processor_widget_ = new PostProcessorWidget();
tab_widget_->addTab(scanning_widget_, "Scanning");
tab_widget_->addTab(alignment_widget_, "Alignment");
tab_widget_->addTab(comparison_widget_, "Comparison");
tab_widget_->addTab(path_planning_widget_, "Path planning");
tab_widget_->addTab(post_processor_widget_, "Post processor");
tab_widget_->setTabEnabled(0, true);
tab_widget_->setTabEnabled(1, false);
tab_widget_->setTabEnabled(2, false);
tab_widget_->setTabEnabled(3, false);
tab_widget_->setTabEnabled(4, false);
// Bottom status layout
QVBoxLayout *status_layout_ = new QVBoxLayout;
status_layout_->addWidget(new QLabel("Status:"));
// Global Layout
QVBoxLayout *global_layout_ = new QVBoxLayout;
global_layout_->addWidget(tab_widget_);
global_layout_->addLayout(status_layout_);
status_label_ = new QLabel;
global_layout_->addWidget(status_label_);
setLayout(global_layout_);
// Connect handlers
// SCANNING
// Will display a status in general status label ( from scanning widget )
connect(scanning_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(scanning_widget_, SIGNAL(sendMsgBox(QString, QString , QString)), this,
SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that scanning_widget_ is modified
connect(scanning_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable AlignementPanel when scanning_widget_ will send the SIGNAL
connect(scanning_widget_, SIGNAL(enablePanelAlignment()), this, SLOT(enablePanelAlignmentHandler()));
// Enable general panel when scanning_widget_ send the SIGNAL
connect(scanning_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Will send information about cad and scan in the other widgets
connect(scanning_widget_, SIGNAL(sendCADDatas(QString, QString)), this, SLOT(setCADDatas(QString, QString)));
connect(scanning_widget_, SIGNAL(sendScanDatas(QString, QString)), this, SLOT(setScanDatas(QString, QString)));
// For the demonstrator, we will skip alignment and comparison parts for the moment
connect(scanning_widget_, SIGNAL(enablePanelPathPlanning()), this, SLOT(enablePanelPathPlanningHandler()));
//ALIGNMENT
// Will display a status in general status label ( from alignment widget )
connect(alignment_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(alignment_widget_, SIGNAL(sendMsgBox(QString, QString , QString)), this,
SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that alignment_widget_ is modified
connect(alignment_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable compoarison_panel when alignment_widget_ will send the SIGNAL
connect(alignment_widget_, SIGNAL(enablePanelComparison()), this, SLOT(enablePanelComparisonHandler()));
// Enable general panel when alignment_widget_ send the SIGNAL
connect(alignment_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Received a signal from alignment widget in order to get CAD and scan params
connect(alignment_widget_, SIGNAL(getCADAndScanParams()), this, SLOT(sendCADAndScanDatasSlot()));
// Send a signal to alignment widget in order to give CAD and scan params
connect(this, SIGNAL(sendCADAndScanDatas(const QString, const QString, const QString, const QString)),
alignment_widget_, SLOT(setCADAndScanParams(const QString, const QString, const QString, const QString)));
//COMPARISON
// Will display a status in general status label ( from comparison widget )
connect(comparison_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(comparison_widget_, SIGNAL(sendMsgBox(QString, QString , QString)), this,
SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that comparison_widget_ is modified
connect(comparison_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable path_planning_widget when comparison_widget_ will send the SIGNAL
connect(comparison_widget_, SIGNAL(enablePanelPathPlanning()), this, SLOT(enablePanelPathPlanningHandler()));
// Enable general panel when comparison_widget_ send the SIGNAL
connect(comparison_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Received a signal from comparison widget in order to get CAD and scan params
connect(comparison_widget_, SIGNAL(getCADAndScanParams()), this, SLOT(sendCADAndScanDatasSlot()));
// Send a signal to comparison widget in order to give CAD and scan params
connect(this, SIGNAL(sendCADAndScanDatas(const QString, const QString, const QString, const QString)),
comparison_widget_, SLOT(setCADAndScanParams(const QString, const QString, const QString, const QString)));
//PATH PLANNING
// Will display a status in general status label ( from path_planning widget )
connect(path_planning_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(path_planning_widget_, SIGNAL(sendMsgBox(QString, QString , QString)), this,
SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that path_planning_widget is modified
connect(path_planning_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable path_planning_widget when comparison_widget_ will send the SIGNAL
connect(path_planning_widget_, SIGNAL(enablePanelPostProcessor()), this, SLOT(enablePanelPostProcessorHandler()));
// Enable general panel when path_planning send the SIGNAL
connect(path_planning_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Received a signal from comparison widget in order to get CAD and scan params
connect(path_planning_widget_, SIGNAL(getCADAndScanParams()), this, SLOT(sendCADAndScanDatasSlot()));
// Send a signal to comparison widget in order to give CAD and scan params
connect(this, SIGNAL(sendCADAndScanDatas(const QString, const QString, const QString, const QString)),
path_planning_widget_, SLOT(setCADAndScanParams(const QString, const QString, const QString, const QString)));
//POST_PROCESSOR
// Will display a status in general status label ( from post_processor widget )
connect(post_processor_widget_, SIGNAL(sendStatus(QString)), this, SLOT(displayStatusHandler(QString)));
connect(post_processor_widget_, SIGNAL(sendMsgBox(QString, QString, QString)), this,
SLOT(displayMsgBoxHandler(QString, QString, QString)));
// Call configChanged at each time that post_processor_widget is modified
connect(post_processor_widget_, SIGNAL(GUIChanged()), this, SLOT(triggerSave()));
// Enable general panel when post_processor send the SIGNAL
connect(post_processor_widget_, SIGNAL(enablePanel(bool)), this, SLOT(enablePanelHandler(bool)));
// Receive a signal from post processor widget in order to send robot poses data
connect(post_processor_widget_, SIGNAL(getRobotTrajectoryData()), this, SLOT(setRobotTrajectoryData()));
connect(this, SIGNAL(displayStatus(const QString)), this, SLOT(displayStatusHandler(const QString)));
}
FanucGrindingRvizPlugin::~FanucGrindingRvizPlugin()
{}
void FanucGrindingRvizPlugin::enablePanelAlignmentHandler()
{
tab_widget_->setTabEnabled(1, true);
}
void FanucGrindingRvizPlugin::enablePanelComparisonHandler()
{
tab_widget_->setTabEnabled(2, true);
}
void FanucGrindingRvizPlugin::enablePanelPathPlanningHandler()
{
tab_widget_->setTabEnabled(3, true);
}
void FanucGrindingRvizPlugin::enablePanelPostProcessorHandler()
{
tab_widget_->setTabEnabled(4, true);
}
void FanucGrindingRvizPlugin::enablePanelHandler(bool status)
{
setEnabled(status);
}
void FanucGrindingRvizPlugin::displayStatusHandler(const QString message)
{
status_label_->setText(message);
}
void FanucGrindingRvizPlugin::displayMsgBoxHandler(const QString title, const QString msg, const QString info_msg)
{
enablePanelHandler(false);
QMessageBox msg_box;
msg_box.setWindowTitle(title);
msg_box.setText(msg);
msg_box.setInformativeText(info_msg);
msg_box.setIcon(QMessageBox::Critical);
msg_box.setStandardButtons(QMessageBox::Ok);
msg_box.exec();
enablePanelHandler(true);
}
void FanucGrindingRvizPlugin::triggerSave()
{
Q_EMIT configChanged();
}
void FanucGrindingRvizPlugin::setCADDatas(const QString cad_filename, const QString cad_marker_name)
{
cad_filename_ = cad_filename;
cad_marker_name_ = cad_marker_name;
}
void FanucGrindingRvizPlugin::setScanDatas(const QString scan_filename, const QString scan_marker_name)
{
scan_filename_ = scan_filename;
scan_marker_name_ = scan_marker_name;
}
void FanucGrindingRvizPlugin::setRobotTrajectoryData()
{
post_processor_widget_->setRobotPoses(path_planning_widget_->getRobotPoses());
post_processor_widget_->setPointColorViz(path_planning_widget_->getPointColorViz());
post_processor_widget_->setIndexVector(path_planning_widget_->getIndexVector());
}
void FanucGrindingRvizPlugin::sendCADAndScanDatasSlot()
{
Q_EMIT sendCADAndScanDatas(cad_filename_, cad_marker_name_, scan_filename_, scan_marker_name_);
}
// Save all configuration data from this panel to the given Config object
void FanucGrindingRvizPlugin::save(rviz::Config config) const
{
rviz::Panel::save(config);
scanning_widget_->save(config);
alignment_widget_->save(config);
comparison_widget_->save(config);
path_planning_widget_->save(config);
post_processor_widget_->save(config);
}
// Load all configuration data for this panel from the given Config object.
void FanucGrindingRvizPlugin::load(const rviz::Config& config)
{
rviz::Panel::load(config);
scanning_widget_->load(config);
alignment_widget_->load(config);
comparison_widget_->load(config);
path_planning_widget_->load(config);
post_processor_widget_->load(config);
}
} // end namespace
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(fanuc_grinding_rviz_plugin::FanucGrindingRvizPlugin, rviz::Panel)
<|endoftext|> |
<commit_before>// NBNBNBNBNBNBNBNBNBNBNBNBNBNBNBNB
// Any subscriptions/construction with Model Client must
// be before typical user subscriptions - if the same LCM object
// is used. Otherwise it won't be received before handling them
// NBNBNBNBNBNBNBNBNBNBNBNBNBNBNBNB
#include <stdio.h>
#include <sys/time.h>
#include <iostream>
#include <lcm/lcm-cpp.hpp>
#include "model-client.hpp"
/**
* lcm_sleep:
* @lcm: The lcm_t object.
* @sleeptime max time to wait in seconds
*
* Waits for up to @sleeptime seconds for an LCM message to arrive.
* It handles the first message if one arrives.
*
*/
static inline void lcm_sleep(lcm_t * lcm, double sleeptime)
{ //
int lcm_fileno = lcm_get_fileno(lcm);
fd_set rfds;
int retval;
FD_ZERO(&rfds);
FD_SET(lcm_fileno, &rfds);
struct timeval tv;
tv.tv_sec = (int) sleeptime;
tv.tv_usec = (int) ((sleeptime - tv.tv_sec) * 1.0e6);
retval = select(lcm_fileno + 1, &rfds, NULL, NULL, &tv);
if (retval == -1) {
fprintf(stderr, "bot_lcm_poll: select() failed!\n");
return;
}
if (retval) {
if (FD_ISSET(lcm_fileno, &rfds)) {
lcm_handle(lcm);
}
}
}
static inline int64_t _timestamp_now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (int64_t) tv.tv_sec * 1000000 + tv.tv_usec;
}
void ModelClient::doModelClient(){
model_pub_robot_urdf_t_subscription_t * sub = model_pub_robot_urdf_t_subscribe(lcm_, model_channel_.c_str(), robot_urdf_handler_aux, this);
//TODO: is there a way to be sure nothing else is subscribed???
int64_t utime_start = _timestamp_now();
int64_t last_print_utime = -1;
while ((_timestamp_now() - utime_start) < 2.5e6) {
//bot_param_request_t req;
//req.utime = _timestamp_now();
//bot_param_request_t_publish(lcm, request_channel, &req);
lcm_sleep(lcm_, .25);
if (urdf_parsed_)
break;
int64_t now = _timestamp_now();
if (now - utime_start > 5e5) {
if (last_print_utime < 0) {
fprintf(stderr, "ModelClient waiting to get model from robot_model_publisher...");
last_print_utime = now;
}
else if (now - last_print_utime > 5e5) {
fprintf(stderr, ".");
last_print_utime = now;
}
}
}
if (last_print_utime > 0) {
fprintf(stderr, "\n");
}
if (!urdf_parsed_) {
fprintf(stderr,
"WARNING: ModelClient could not get model from the robot_model_publisher!\n Did you forget to start one?\n");
exit(-1);
return;
}
if (!keep_updated_) {
//unsubscribe from urdf messages
model_pub_robot_urdf_t_unsubscribe(lcm_, sub);
// param->server_id = -1;
}
}
ModelClient::ModelClient(lcm_t* lcm_, int keep_updated_):
urdf_parsed_(false),lcm_(lcm_), keep_updated_(keep_updated_){
model_channel_ = "ROBOT_MODEL";
doModelClient( );
}
// TODO implement update
ModelClient::ModelClient(lcm_t* lcm_, std::string model_channel_, int keep_updated_):
urdf_parsed_(false),lcm_(lcm_),
model_channel_(model_channel_), keep_updated_(keep_updated_){
file_read_success_ = false; // file wasn't read, book keeping
doModelClient();
}
ModelClient::ModelClient(std::string urdf_filename){
// Received robot urdf string. Store it internally and get all available joints.
file_read_success_ = readURDFFromFile(urdf_filename);
if (file_read_success_){
std::cout<< "Read urdf_xml_string of robot ["
<< robot_name_ << "] from file, storing it internally as a param" << std::endl;
parseURDFString();
}else{
std::cout<< urdf_filename << " could not be read. exiting" << std::endl;
exit(-1);
}
}
void ModelClient::robot_urdf_handler(const char* channel, const model_pub_robot_urdf_t *msg){
// Received robot urdf string. Store it internally and get all available joints.
robot_name_ = msg->robot_name;
urdf_xml_string_ = msg->urdf_xml_string;
std::cout<< "Received urdf_xml_string of robot ["
<< msg->robot_name << "], storing it internally as a param" << std::endl;
parseURDFString();
}
void ModelClient::parseURDFString(){
// Get a urdf Model from the xml string and get all the joint names.
urdf::Model robot_model;
if (!robot_model.initString( urdf_xml_string_ ))
{
std::cerr << "ERROR: Could not generate robot model" << std::endl;
}
typedef std::map<std::string, boost::shared_ptr<urdf::Joint> > joints_mapType;
for( joints_mapType::const_iterator it = robot_model.joints_.begin(); it!=robot_model.joints_.end(); it++)
{
if(it->second->type!=6) // All joints that not of the type FIXED.
joint_names_.push_back(it->first);
}
links_map_ = robot_model.links_;
std::cout<< "Number of Joints: " << joint_names_.size() <<std::endl;
setHandConfiguration();
urdf_parsed_ = true;
}
bool ModelClient::readURDFFromFile(std::string urdf_file){
// get the entire file
std::string xml_string;
std::fstream xml_file(urdf_file.c_str(), std::fstream::in);
if (xml_file.is_open())
{
while ( xml_file.good() )
{
std::string line;
std::getline( xml_file, line);
xml_string += (line + "\n");
}
xml_file.close();
std::cout << "File ["<< urdf_file << "] parsed successfully.\n";
}
else
{
std::cout << "ERROR: Could not open file ["<< urdf_file << "] for parsing.\n";
return false;
}
// Get a urdf Model from the xml string and get all the joint names.
urdf::Model robot_model;
if (!robot_model.initString( xml_string ))
{
std::cerr << "ERROR: Model Parsing the xml failed" << std::endl;
}
// Set the member variable:
urdf_xml_string_ = xml_string;
robot_name_ = robot_model.getName();
}
void ModelClient::setHandConfiguration(){
if(find(joint_names_.begin(), joint_names_.end(), "left_f0_j0" ) != joint_names_.end()){
std::cout << "Robot fitted with left Sandia hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_SANDIA; //drc::robot_urdf_t::LEFT_SANDIA;
}else if(find(joint_names_.begin(), joint_names_.end(), "left_finger[0]/joint_base" ) != joint_names_.end()){
std::cout << "Robot fitted with left iRobot hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_IROBOT; //drc::robot_urdf_t::LEFT_IROBOT;
}else if(find(joint_names_.begin(), joint_names_.end(), "left_finger_1_joint_1" ) != joint_names_.end()){
std::cout << "Robot fitted with left Robotiq hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_ROBOTIQ; //drc::robot_urdf_t::LEFT_ROBOTIQ;
}else{
std::cout << "Robot has no left hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_NONE; //drc::robot_urdf_t::LEFT_NONE;
}
if(find(joint_names_.begin(), joint_names_.end(), "right_f0_j0" ) != joint_names_.end()){
std::cout << "Robot fitted with right Sandia hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_SANDIA;//drc::robot_urdf_t::RIGHT_SANDIA;
}else if(find(joint_names_.begin(), joint_names_.end(), "right_finger[0]/joint_base" ) != joint_names_.end()){
std::cout << "Robot fitted with right iRobot hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_IROBOT;//drc::robot_urdf_t::RIGHT_IROBOT;
}else if(find(joint_names_.begin(), joint_names_.end(), "right_finger_1_joint_1" ) != joint_names_.end()){
std::cout << "Robot fitted with right Robotiq hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_ROBOTIQ;//drc::robot_urdf_t::RIGHT_ROBOTIQ;
}else{
std::cout << "Robot has no right hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_NONE;//drc::robot_urdf_t::RIGHT_NONE;
}
}
<commit_msg>Support l_finger in addition to left_finger to identify robotiq grippers<commit_after>// NBNBNBNBNBNBNBNBNBNBNBNBNBNBNBNB
// Any subscriptions/construction with Model Client must
// be before typical user subscriptions - if the same LCM object
// is used. Otherwise it won't be received before handling them
// NBNBNBNBNBNBNBNBNBNBNBNBNBNBNBNB
#include <stdio.h>
#include <sys/time.h>
#include <iostream>
#include <lcm/lcm-cpp.hpp>
#include "model-client.hpp"
/**
* lcm_sleep:
* @lcm: The lcm_t object.
* @sleeptime max time to wait in seconds
*
* Waits for up to @sleeptime seconds for an LCM message to arrive.
* It handles the first message if one arrives.
*
*/
static inline void lcm_sleep(lcm_t * lcm, double sleeptime)
{ //
int lcm_fileno = lcm_get_fileno(lcm);
fd_set rfds;
int retval;
FD_ZERO(&rfds);
FD_SET(lcm_fileno, &rfds);
struct timeval tv;
tv.tv_sec = (int) sleeptime;
tv.tv_usec = (int) ((sleeptime - tv.tv_sec) * 1.0e6);
retval = select(lcm_fileno + 1, &rfds, NULL, NULL, &tv);
if (retval == -1) {
fprintf(stderr, "bot_lcm_poll: select() failed!\n");
return;
}
if (retval) {
if (FD_ISSET(lcm_fileno, &rfds)) {
lcm_handle(lcm);
}
}
}
static inline int64_t _timestamp_now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (int64_t) tv.tv_sec * 1000000 + tv.tv_usec;
}
void ModelClient::doModelClient(){
model_pub_robot_urdf_t_subscription_t * sub = model_pub_robot_urdf_t_subscribe(lcm_, model_channel_.c_str(), robot_urdf_handler_aux, this);
//TODO: is there a way to be sure nothing else is subscribed???
int64_t utime_start = _timestamp_now();
int64_t last_print_utime = -1;
while ((_timestamp_now() - utime_start) < 2.5e6) {
//bot_param_request_t req;
//req.utime = _timestamp_now();
//bot_param_request_t_publish(lcm, request_channel, &req);
lcm_sleep(lcm_, .25);
if (urdf_parsed_)
break;
int64_t now = _timestamp_now();
if (now - utime_start > 5e5) {
if (last_print_utime < 0) {
fprintf(stderr, "ModelClient waiting to get model from robot_model_publisher...");
last_print_utime = now;
}
else if (now - last_print_utime > 5e5) {
fprintf(stderr, ".");
last_print_utime = now;
}
}
}
if (last_print_utime > 0) {
fprintf(stderr, "\n");
}
if (!urdf_parsed_) {
fprintf(stderr,
"WARNING: ModelClient could not get model from the robot_model_publisher!\n Did you forget to start one?\n");
exit(-1);
return;
}
if (!keep_updated_) {
//unsubscribe from urdf messages
model_pub_robot_urdf_t_unsubscribe(lcm_, sub);
// param->server_id = -1;
}
}
ModelClient::ModelClient(lcm_t* lcm_, int keep_updated_):
urdf_parsed_(false),lcm_(lcm_), keep_updated_(keep_updated_){
model_channel_ = "ROBOT_MODEL";
doModelClient( );
}
// TODO implement update
ModelClient::ModelClient(lcm_t* lcm_, std::string model_channel_, int keep_updated_):
urdf_parsed_(false),lcm_(lcm_),
model_channel_(model_channel_), keep_updated_(keep_updated_){
file_read_success_ = false; // file wasn't read, book keeping
doModelClient();
}
ModelClient::ModelClient(std::string urdf_filename){
// Received robot urdf string. Store it internally and get all available joints.
file_read_success_ = readURDFFromFile(urdf_filename);
if (file_read_success_){
std::cout<< "Read urdf_xml_string of robot ["
<< robot_name_ << "] from file, storing it internally as a param" << std::endl;
parseURDFString();
}else{
std::cout<< urdf_filename << " could not be read. exiting" << std::endl;
exit(-1);
}
}
void ModelClient::robot_urdf_handler(const char* channel, const model_pub_robot_urdf_t *msg){
// Received robot urdf string. Store it internally and get all available joints.
robot_name_ = msg->robot_name;
urdf_xml_string_ = msg->urdf_xml_string;
std::cout<< "Received urdf_xml_string of robot ["
<< msg->robot_name << "], storing it internally as a param" << std::endl;
parseURDFString();
}
void ModelClient::parseURDFString(){
// Get a urdf Model from the xml string and get all the joint names.
urdf::Model robot_model;
if (!robot_model.initString( urdf_xml_string_ ))
{
std::cerr << "ERROR: Could not generate robot model" << std::endl;
}
typedef std::map<std::string, boost::shared_ptr<urdf::Joint> > joints_mapType;
for( joints_mapType::const_iterator it = robot_model.joints_.begin(); it!=robot_model.joints_.end(); it++)
{
if(it->second->type!=6) // All joints that not of the type FIXED.
joint_names_.push_back(it->first);
}
links_map_ = robot_model.links_;
std::cout<< "Number of Joints: " << joint_names_.size() <<std::endl;
setHandConfiguration();
urdf_parsed_ = true;
}
bool ModelClient::readURDFFromFile(std::string urdf_file){
// get the entire file
std::string xml_string;
std::fstream xml_file(urdf_file.c_str(), std::fstream::in);
if (xml_file.is_open())
{
while ( xml_file.good() )
{
std::string line;
std::getline( xml_file, line);
xml_string += (line + "\n");
}
xml_file.close();
std::cout << "File ["<< urdf_file << "] parsed successfully.\n";
}
else
{
std::cout << "ERROR: Could not open file ["<< urdf_file << "] for parsing.\n";
return false;
}
// Get a urdf Model from the xml string and get all the joint names.
urdf::Model robot_model;
if (!robot_model.initString( xml_string ))
{
std::cerr << "ERROR: Model Parsing the xml failed" << std::endl;
}
// Set the member variable:
urdf_xml_string_ = xml_string;
robot_name_ = robot_model.getName();
}
void ModelClient::setHandConfiguration() {
if (find(joint_names_.begin(), joint_names_.end(), "left_f0_j0") !=
joint_names_.end()) {
std::cout << "Robot fitted with left Sandia hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_SANDIA;
} else if (find(joint_names_.begin(), joint_names_.end(),
"left_finger[0]/joint_base") != joint_names_.end()) {
std::cout << "Robot fitted with left iRobot hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_IROBOT;
} else if (find(joint_names_.begin(), joint_names_.end(),
"left_finger_1_joint_1") != joint_names_.end() ||
find(joint_names_.begin(), joint_names_.end(),
"l_finger_1_joint_1") != joint_names_.end()) {
std::cout << "Robot fitted with left Robotiq hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_ROBOTIQ;
} else {
std::cout << "Robot has no left hand\n";
left_hand_ = MODEL_PUB_ROBOT_URDF_T_LEFT_NONE;
}
if (find(joint_names_.begin(), joint_names_.end(), "right_f0_j0") !=
joint_names_.end()) {
std::cout << "Robot fitted with right Sandia hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_SANDIA;
} else if (find(joint_names_.begin(), joint_names_.end(),
"right_finger[0]/joint_base") != joint_names_.end()) {
std::cout << "Robot fitted with right iRobot hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_IROBOT;
} else if (find(joint_names_.begin(), joint_names_.end(),
"right_finger_1_joint_1") != joint_names_.end() ||
find(joint_names_.begin(), joint_names_.end(),
"r_finger_1_joint_1") != joint_names_.end()) {
std::cout << "Robot fitted with right Robotiq hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_ROBOTIQ;
} else {
std::cout << "Robot has no right hand\n";
right_hand_ = MODEL_PUB_ROBOT_URDF_T_RIGHT_NONE;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtk/gtk.h>
#include "build/build_config.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/compiler_specific.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/page_info_window.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
namespace {
enum {
RESPONSE_SHOW_CERT_INFO = 0,
};
class PageInfoWindowGtk : public PageInfoModel::PageInfoModelObserver {
public:
PageInfoWindowGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history);
~PageInfoWindowGtk();
// PageInfoModelObserver implementation:
virtual void ModelChanged();
// Shows the page info window.
void Show();
// Shows the certificate info window.
void ShowCertDialog();
GtkWidget* widget() { return dialog_; }
private:
// Layouts the different sections retrieved from the model.
void InitContents();
// Returns a widget that contains the UI for the passed |section|.
GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);
// The model containing the different sections to display.
PageInfoModel model_;
// The page info dialog.
GtkWidget* dialog_;
// The url for this dialog. Should be unique among active dialogs.
GURL url_;
// The virtual box containing the sections.
GtkWidget* contents_;
// The id of the certificate for this page.
int cert_id_;
DISALLOW_COPY_AND_ASSIGN(PageInfoWindowGtk);
};
// We only show one page info per URL (keyed on url.spec()).
typedef std::map<std::string, PageInfoWindowGtk*> PageInfoWindowMap;
PageInfoWindowMap g_page_info_window_map;
// Button callbacks.
void OnDialogResponse(GtkDialog* dialog, gint response_id,
PageInfoWindowGtk* page_info) {
if (response_id == RESPONSE_SHOW_CERT_INFO) {
page_info->ShowCertDialog();
} else {
// "Close" was clicked.
gtk_widget_destroy(GTK_WIDGET(dialog));
}
}
void OnDestroy(GtkDialog* dialog, PageInfoWindowGtk* page_info) {
delete page_info;
}
////////////////////////////////////////////////////////////////////////////////
// PageInfoWindowGtk, public:
PageInfoWindowGtk::PageInfoWindowGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
url_(url),
contents_(NULL),
cert_id_(ssl.cert_id()) {
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_PAGEINFO_WINDOW_TITLE).c_str(),
parent,
// Non-modal.
GTK_DIALOG_NO_SEPARATOR,
NULL);
if (cert_id_) {
gtk_dialog_add_button(
GTK_DIALOG(dialog_),
l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str(),
RESPONSE_SHOW_CERT_INFO);
}
gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_CLOSE,
GTK_RESPONSE_CLOSE);
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),
gtk_util::kContentAreaSpacing);
g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponse), this);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnDestroy), this);
InitContents();
g_page_info_window_map[url.spec()] = this;
}
PageInfoWindowGtk::~PageInfoWindowGtk() {
g_page_info_window_map.erase(url_.spec());
}
void PageInfoWindowGtk::ModelChanged() {
InitContents();
}
GtkWidget* PageInfoWindowGtk::CreateSection(
const PageInfoModel::SectionInfo& section) {
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.title).c_str());
PangoAttrList* attributes = pango_attr_list_new();
pango_attr_list_insert(attributes,
pango_attr_weight_new(PANGO_WEIGHT_BOLD));
gtk_label_set_attributes(GTK_LABEL(label), attributes);
pango_attr_list_unref(attributes);
gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
GtkWidget* section_box = gtk_hbox_new(FALSE, 0);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
GtkWidget* image = gtk_image_new_from_pixbuf(
section.state == PageInfoModel::SECTION_STATE_OK ?
rb.GetPixbufNamed(IDR_PAGEINFO_GOOD) :
rb.GetPixbufNamed(IDR_PAGEINFO_BAD));
gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE,
gtk_util::kControlSpacing);
gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
GtkWidget* text_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
if (!section.headline.empty()) {
label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());
gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);
}
label = gtk_label_new(UTF16ToUTF8(section.description).c_str());
gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);
gtk_widget_set_size_request(label, 400, -1);
gtk_box_pack_start(GTK_BOX(section_box), text_box, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), section_box, TRUE, TRUE, 0);
return vbox;
}
void PageInfoWindowGtk::InitContents() {
if (contents_)
gtk_widget_destroy(contents_);
contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);
for (int i = 0; i < model_.GetSectionCount(); i++) {
gtk_box_pack_start(GTK_BOX(contents_),
CreateSection(model_.GetSectionInfo(i)),
FALSE, FALSE, 0);
}
gtk_widget_show_all(contents_);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), contents_);
}
void PageInfoWindowGtk::Show() {
gtk_widget_show(dialog_);
}
void PageInfoWindowGtk::ShowCertDialog() {
ShowCertificateViewerByID(GTK_WINDOW(dialog_), cert_id_);
}
} // namespace
namespace browser {
void ShowPageInfo(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
PageInfoWindowMap::iterator iter =
g_page_info_window_map.find(url.spec());
if (iter != g_page_info_window_map.end()) {
gtk_window_present(GTK_WINDOW(iter->second->widget()));
return;
}
PageInfoWindowGtk* page_info_window =
new PageInfoWindowGtk(parent, profile, url, ssl, show_history);
page_info_window->Show();
}
} // namespace browser
<commit_msg>[gtk] Update page-info icons to match behavior in page_info_window_view.cc.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtk/gtk.h>
#include "build/build_config.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/compiler_specific.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/page_info_window.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
namespace {
enum {
RESPONSE_SHOW_CERT_INFO = 0,
};
class PageInfoWindowGtk : public PageInfoModel::PageInfoModelObserver {
public:
PageInfoWindowGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history);
~PageInfoWindowGtk();
// PageInfoModelObserver implementation:
virtual void ModelChanged();
// Shows the page info window.
void Show();
// Shows the certificate info window.
void ShowCertDialog();
GtkWidget* widget() { return dialog_; }
private:
// Layouts the different sections retrieved from the model.
void InitContents();
// Returns a widget that contains the UI for the passed |section|.
GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);
// The model containing the different sections to display.
PageInfoModel model_;
// The page info dialog.
GtkWidget* dialog_;
// The url for this dialog. Should be unique among active dialogs.
GURL url_;
// The virtual box containing the sections.
GtkWidget* contents_;
// The id of the certificate for this page.
int cert_id_;
DISALLOW_COPY_AND_ASSIGN(PageInfoWindowGtk);
};
// We only show one page info per URL (keyed on url.spec()).
typedef std::map<std::string, PageInfoWindowGtk*> PageInfoWindowMap;
PageInfoWindowMap g_page_info_window_map;
// Button callbacks.
void OnDialogResponse(GtkDialog* dialog, gint response_id,
PageInfoWindowGtk* page_info) {
if (response_id == RESPONSE_SHOW_CERT_INFO) {
page_info->ShowCertDialog();
} else {
// "Close" was clicked.
gtk_widget_destroy(GTK_WIDGET(dialog));
}
}
void OnDestroy(GtkDialog* dialog, PageInfoWindowGtk* page_info) {
delete page_info;
}
////////////////////////////////////////////////////////////////////////////////
// PageInfoWindowGtk, public:
PageInfoWindowGtk::PageInfoWindowGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
url_(url),
contents_(NULL),
cert_id_(ssl.cert_id()) {
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_PAGEINFO_WINDOW_TITLE).c_str(),
parent,
// Non-modal.
GTK_DIALOG_NO_SEPARATOR,
NULL);
if (cert_id_) {
gtk_dialog_add_button(
GTK_DIALOG(dialog_),
l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str(),
RESPONSE_SHOW_CERT_INFO);
}
gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_CLOSE,
GTK_RESPONSE_CLOSE);
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),
gtk_util::kContentAreaSpacing);
g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponse), this);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnDestroy), this);
InitContents();
g_page_info_window_map[url.spec()] = this;
}
PageInfoWindowGtk::~PageInfoWindowGtk() {
g_page_info_window_map.erase(url_.spec());
}
void PageInfoWindowGtk::ModelChanged() {
InitContents();
}
GtkWidget* PageInfoWindowGtk::CreateSection(
const PageInfoModel::SectionInfo& section) {
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.title).c_str());
PangoAttrList* attributes = pango_attr_list_new();
pango_attr_list_insert(attributes,
pango_attr_weight_new(PANGO_WEIGHT_BOLD));
gtk_label_set_attributes(GTK_LABEL(label), attributes);
pango_attr_list_unref(attributes);
gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
GtkWidget* section_box = gtk_hbox_new(FALSE, 0);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
GtkWidget* image = gtk_image_new_from_pixbuf(
section.state == PageInfoModel::SECTION_STATE_OK ?
rb.GetPixbufNamed(IDR_PAGEINFO_GOOD) :
rb.GetPixbufNamed(IDR_PAGEINFO_WARNING_MAJOR));
gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE,
gtk_util::kControlSpacing);
gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
GtkWidget* text_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
if (!section.headline.empty()) {
label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());
gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);
}
label = gtk_label_new(UTF16ToUTF8(section.description).c_str());
gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);
gtk_widget_set_size_request(label, 400, -1);
gtk_box_pack_start(GTK_BOX(section_box), text_box, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), section_box, TRUE, TRUE, 0);
return vbox;
}
void PageInfoWindowGtk::InitContents() {
if (contents_)
gtk_widget_destroy(contents_);
contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);
for (int i = 0; i < model_.GetSectionCount(); i++) {
gtk_box_pack_start(GTK_BOX(contents_),
CreateSection(model_.GetSectionInfo(i)),
FALSE, FALSE, 0);
}
gtk_widget_show_all(contents_);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), contents_);
}
void PageInfoWindowGtk::Show() {
gtk_widget_show(dialog_);
}
void PageInfoWindowGtk::ShowCertDialog() {
ShowCertificateViewerByID(GTK_WINDOW(dialog_), cert_id_);
}
} // namespace
namespace browser {
void ShowPageInfo(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
PageInfoWindowMap::iterator iter =
g_page_info_window_map.find(url.spec());
if (iter != g_page_info_window_map.end()) {
gtk_window_present(GTK_WINDOW(iter->second->widget()));
return;
}
PageInfoWindowGtk* page_info_window =
new PageInfoWindowGtk(parent, profile, url, ssl, show_history);
page_info_window->Show();
}
} // namespace browser
<|endoftext|> |
<commit_before>#include "rigidBodyManipulatorMexFunctions.h"
#include "RigidBodyManipulator.h"
#include "standardMexConversions.h"
#include <typeinfo>
using namespace std;
using namespace Eigen;
/**
* fromMex specializations
*/
RigidBodyManipulator &fromMex(const mxArray *source, RigidBodyManipulator *) {
return *static_cast<RigidBodyManipulator *>(getDrakeMexPointer(source));
}
std::set<int> fromMex(const mxArray *source, std::set<int> *) {
// for robotnum. this is kind of a weird one, but OK for now
std::set<int> robotnum_set;
int num_robot = static_cast<int>(mxGetNumberOfElements(source));
double *robotnum = mxGetPrSafe(source);
for (int i = 0; i < num_robot; i++) {
robotnum_set.insert((int) robotnum[i] - 1);
}
return robotnum_set;
}
template<typename Scalar>
KinematicsCache<Scalar> &fromMex(const mxArray *mex, KinematicsCache<Scalar> *) {
if (!mxIsClass(mex, "DrakeMexPointer")) {
throw MexToCppConversionError("Expected DrakeMexPointer containing KinematicsCache");
}
auto name = mxGetStdString(mxGetPropertySafe(mex, "name"));
if (name != typeid(KinematicsCache<Scalar>).name()) {
ostringstream buf;
buf << "Expected KinematicsCache of type " << typeid(KinematicsCache<Scalar>).name() << ", but got " << name;
throw MexToCppConversionError(buf.str());
}
return *static_cast<KinematicsCache<Scalar> *>(getDrakeMexPointer(mex));
}
/**
* toMex specializations
*/
void toMex(const KinematicPath &path, mxArray *dest[], int nlhs) {
if (nlhs > 0) {
dest[0] = stdVectorToMatlab(path.body_path);
}
if (nlhs > 1) {
dest[1] = stdVectorToMatlab(path.joint_path);
}
if (nlhs > 2) {
dest[2] = stdVectorToMatlab(path.joint_direction_signs);
}
}
typedef AutoDiffScalar<VectorXd> AutoDiffDynamicSize;
//typedef AutoDiffScalar<Matrix<double, Dynamic, 1, 0, 72, 1> AutoDiffFixedMaxSize;
/**
* Mex function implementations
*/
void centerOfMassJacobianDotTimesVmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, SPACE_DIMENSION, 1>(const RigidBodyManipulator &, KinematicsCache<double> &, int, const std::set<int> &)> func_double = mem_fn(
&RigidBodyManipulator::centerOfMassJacobianDotTimesV<double>);
function<GradientVar<AutoDiffDynamicSize, SPACE_DIMENSION, 1>(const RigidBodyManipulator &, KinematicsCache<AutoDiffDynamicSize> &, int, const std::set<int> &)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::centerOfMassJacobianDotTimesV<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centerOfMassmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<Matrix<double, SPACE_DIMENSION, 1>(const RigidBodyManipulator &, KinematicsCache<double> &, const std::set<int> &)> func_double = mem_fn(&RigidBodyManipulator::centerOfMass<double>);
function<Matrix<AutoDiffDynamicSize, SPACE_DIMENSION, 1>(const RigidBodyManipulator &, KinematicsCache<AutoDiffDynamicSize> &, const std::set<int> &)> func_autodiff_dynamic = mem_fn(&RigidBodyManipulator::centerOfMass<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centerOfMassJacobianmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, SPACE_DIMENSION, Dynamic>(const RigidBodyManipulator &, KinematicsCache<double> &, int, const std::set<int> &, bool)> func_double = mem_fn(
&RigidBodyManipulator::centerOfMassJacobian<double>);
function<GradientVar<AutoDiffDynamicSize, SPACE_DIMENSION, Dynamic>(const RigidBodyManipulator &, KinematicsCache<AutoDiffDynamicSize> &, int, const std::set<int> &, bool)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::centerOfMassJacobian<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centroidalMomentumMatrixDotTimesvmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, TWIST_SIZE, 1>(const RigidBodyManipulator &, KinematicsCache<double> &, int, const std::set<int> &)> func_double = mem_fn(
&RigidBodyManipulator::centroidalMomentumMatrixDotTimesV<double>);
function<GradientVar<AutoDiffDynamicSize, TWIST_SIZE, 1>
(const RigidBodyManipulator &, KinematicsCache<AutoDiffDynamicSize> &, int, const std::set<int> &)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::centroidalMomentumMatrixDotTimesV<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centroidalMomentumMatrixmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, TWIST_SIZE, Dynamic> const(RigidBodyManipulator &, KinematicsCache<double> &, int, const std::set<int> &, bool)> func_double = mem_fn(
&RigidBodyManipulator::centroidalMomentumMatrix<double>);
function<GradientVar<AutoDiffDynamicSize, TWIST_SIZE, Dynamic> const(RigidBodyManipulator &, KinematicsCache<AutoDiffDynamicSize> &, int, const std::set<int> &, bool)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::centroidalMomentumMatrix<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
template <typename DerivedQ, typename DerivedV>
void doKinematicsTemp(const RigidBodyManipulator &model, KinematicsCache<typename DerivedQ::Scalar> &cache, const MatrixBase<DerivedQ> &q, const MatrixBase<DerivedV> &v, bool compute_JdotV) {
// temporary solution. Explicit doKinematics calls will not be necessary in the near future.
if (v.size() == 0 && model.num_velocities != 0)
cache.initialize(q);
else
cache.initialize(q, v);
model.doKinematics(cache, compute_JdotV);
}
void doKinematicsmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Matrix<AutoDiffScalar<VectorXd>, Dynamic, 1> VectorXAutoDiff;
function<void(const RigidBodyManipulator &, KinematicsCache<double> &, const MatrixBase<Map<const VectorXd>> &, const MatrixBase<Map<const VectorXd>> &, bool)> func_double = &doKinematicsTemp<Map<const VectorXd>, Map<const VectorXd>>;
function<void(const RigidBodyManipulator &, KinematicsCache<typename VectorXAutoDiff::Scalar> &, const MatrixBase<VectorXAutoDiff> &, const MatrixBase<VectorXAutoDiff> &, bool)> func_autodiff_dynamic = &doKinematicsTemp<VectorXAutoDiff, VectorXAutoDiff>;
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void findKinematicPathmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<KinematicPath(const RigidBodyManipulator &, int, int)> func = mem_fn(&RigidBodyManipulator::findKinematicPath);
mexCallFunction(func, nlhs, plhs, nrhs, prhs);
}
void forwardJacDotTimesVmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Map<const Matrix3Xd> DerivedPointsDouble;
function<GradientVar<typename DerivedPointsDouble::Scalar, Dynamic, 1>(const RigidBodyManipulator &, const KinematicsCache<typename DerivedPointsDouble::Scalar> &, const MatrixBase<DerivedPointsDouble> &, int, int, int, int)> func_double = mem_fn(
&RigidBodyManipulator::forwardJacDotTimesV<DerivedPointsDouble>);
typedef Matrix<AutoDiffDynamicSize, 3, Dynamic> DerivedPointsAutoDiff;
function<GradientVar<typename DerivedPointsAutoDiff::Scalar, Dynamic, 1>(const RigidBodyManipulator &, const KinematicsCache<typename DerivedPointsAutoDiff::Scalar> &, const MatrixBase<DerivedPointsAutoDiff> &, int, int, int, int)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::forwardJacDotTimesV<DerivedPointsAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void forwardKinmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Map<const Matrix3Xd> DerivedPointsDouble;
function<Matrix<typename DerivedPointsDouble::Scalar, Dynamic, DerivedPointsDouble::ColsAtCompileTime>(RigidBodyManipulator &, const KinematicsCache<typename DerivedPointsDouble::Scalar> &, const MatrixBase<DerivedPointsDouble> &, int, int, int)> func_double = mem_fn(
&RigidBodyManipulator::forwardKin<DerivedPointsDouble>);
typedef Matrix<AutoDiffDynamicSize, 3, Dynamic> DerivedPointsAutoDiff;
function<Matrix<typename DerivedPointsAutoDiff::Scalar, Dynamic, DerivedPointsAutoDiff::ColsAtCompileTime>(RigidBodyManipulator &, const KinematicsCache<typename DerivedPointsAutoDiff::Scalar> &, const MatrixBase<DerivedPointsAutoDiff> &, int, int, int)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::forwardKin<DerivedPointsAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void forwardKinJacobianmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Map<const Matrix3Xd> DerivedPointsDouble;
function<GradientVar<typename DerivedPointsDouble::Scalar, Dynamic, Dynamic>(const RigidBodyManipulator &, const KinematicsCache<typename DerivedPointsDouble::Scalar> &, const MatrixBase<DerivedPointsDouble> &, int, int, int, bool, int)> func_double = mem_fn(
&RigidBodyManipulator::forwardKinJacobian<DerivedPointsDouble>);
typedef Matrix<AutoDiffDynamicSize, 3, Dynamic> DerivedPointsAutoDiff;
function<GradientVar<typename DerivedPointsAutoDiff::Scalar, Dynamic, Dynamic>(const RigidBodyManipulator &, const KinematicsCache<typename DerivedPointsAutoDiff::Scalar> &, const MatrixBase<DerivedPointsAutoDiff> &, int, int, int, bool, int)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::forwardKinJacobian<DerivedPointsAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void forwardKinPositionGradientmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, Dynamic, Dynamic>(const RigidBodyManipulator &, const KinematicsCache<double> &, int, int, int, int)> func_double = mem_fn(
&RigidBodyManipulator::forwardKinPositionGradient<double>);
function<GradientVar<AutoDiffDynamicSize, Dynamic, Dynamic>(const RigidBodyManipulator &, const KinematicsCache<AutoDiffDynamicSize> &, int, int, int, int)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::forwardKinPositionGradient<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void geometricJacobianDotTimesVmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
std::function<GradientVar<double, TWIST_SIZE, 1>(const RigidBodyManipulator &, const KinematicsCache<double> &, int, int, int, int)> func_double = mem_fn(
&RigidBodyManipulator::geometricJacobianDotTimesV<double>);
std::function<GradientVar<AutoDiffDynamicSize, TWIST_SIZE, 1>(const RigidBodyManipulator &, const KinematicsCache<AutoDiffDynamicSize> &, int, int, int, int)> func_autodiff_dynamic = mem_fn(
&RigidBodyManipulator::geometricJacobianDotTimesV<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
template <typename Scalar>
GradientVar<Scalar, TWIST_SIZE, Eigen::Dynamic> geometricJacobianTemp(const RigidBodyManipulator &model, const KinematicsCache<Scalar> &cache, int base_body_or_frame_ind, int end_effector_body_or_frame_ind, int expressed_in_body_or_frame_ind, int gradient_order, bool in_terms_of_qdot) {
// temporary solution. Gross v_or_qdot_indices pointer will be gone soon.
return model.geometricJacobian(cache, base_body_or_frame_ind, end_effector_body_or_frame_ind, expressed_in_body_or_frame_ind, gradient_order, in_terms_of_qdot, nullptr);
};
void geometricJacobianmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, TWIST_SIZE, Dynamic>(const RigidBodyManipulator &, const KinematicsCache<double> &, int, int, int, int, bool)> func_double = &geometricJacobianTemp<double>;
function<GradientVar<AutoDiffDynamicSize, TWIST_SIZE, Dynamic>(const RigidBodyManipulator &, const KinematicsCache<AutoDiffDynamicSize> &, int, int, int, int, bool)> func_autodiff_dynamic = &geometricJacobianTemp<AutoDiffDynamicSize>;
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void massMatrixmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, Dynamic, Dynamic>(const RigidBodyManipulator &, KinematicsCache<double> &, int)> func_double = mem_fn(&RigidBodyManipulator::massMatrix<double>);
function<GradientVar<AutoDiffScalar<VectorXd>, Dynamic, Dynamic>(const RigidBodyManipulator &, KinematicsCache<AutoDiffScalar<VectorXd>> &, int)> func_autodiff_dynamic = mem_fn(&RigidBodyManipulator::massMatrix<AutoDiffScalar<VectorXd>>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
template <typename Scalar, typename DerivedF, typename DerivedDF>
GradientVar<Scalar, Eigen::Dynamic, 1> dynamicsBiasTermTemp(const RigidBodyManipulator &model, KinematicsCache<Scalar> &cache, const MatrixBase<DerivedF> &f_ext_value, const MatrixBase<DerivedDF> &f_ext_gradient, int gradient_order) {
// temporary solution. GradientVar will disappear, obviating the need for the extra argument. integer body indices will be handled differently.
unordered_map<const RigidBody *, GradientVar<Scalar, 6, 1> > f_ext;
if (f_ext_value.size() > 0) {
assert(f_ext_value.cols() == model.bodies.size());
if (gradient_order > 0) {
assert(f_ext_gradient.rows() == f_ext_value.size());
assert(f_ext_gradient.cols() == model.num_positions + model.num_velocities);
}
for (DenseIndex i = 0; i < f_ext_value.cols(); i++) {
GradientVar<Scalar, TWIST_SIZE, 1> f_ext_gradientvar(TWIST_SIZE, 1, model.num_positions + model.num_velocities, gradient_order);
f_ext_gradientvar.value() = f_ext_value.col(i);
if (gradient_order > 0) {
f_ext_gradientvar.gradient().value() = f_ext_gradient.template middleRows<TWIST_SIZE>(TWIST_SIZE * i);
}
f_ext.insert({model.bodies[i].get(), f_ext_gradientvar});
}
}
return model.dynamicsBiasTerm(cache, f_ext, gradient_order);
};
void dynamicsBiasTermmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
function<GradientVar<double, Eigen::Dynamic, 1>(const RigidBodyManipulator &, KinematicsCache<double> &, const MatrixBase<Map<const Matrix<double, 6, Dynamic> > > &, const MatrixBase<Map<const Matrix<double, Dynamic, Dynamic> > >&, int)> func_double = &dynamicsBiasTermTemp<double, Map<const Matrix<double, 6, Dynamic> >, Map<const Matrix<double, Dynamic, Dynamic> > >;
function<GradientVar<AutoDiffDynamicSize, Eigen::Dynamic, 1>(const RigidBodyManipulator &, KinematicsCache<AutoDiffDynamicSize> &, const MatrixBase<Matrix<AutoDiffDynamicSize, 6, Dynamic>> &, const MatrixBase<Matrix<AutoDiffDynamicSize, Dynamic, Dynamic>> &, int)> func_autodiff_dynamic = &dynamicsBiasTermTemp<AutoDiffDynamicSize, Matrix<AutoDiffDynamicSize, 6, Dynamic>, Matrix<AutoDiffDynamicSize, Dynamic, Dynamic> >;
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
<commit_msg>Clean things up by adding a make_function implementation. Creating a fully general make_function isn't possible, but this works in our cases.<commit_after>#include "rigidBodyManipulatorMexFunctions.h"
#include "RigidBodyManipulator.h"
#include "standardMexConversions.h"
#include <typeinfo>
using namespace std;
using namespace Eigen;
/**
* fromMex specializations
*/
RigidBodyManipulator &fromMex(const mxArray *source, RigidBodyManipulator *) {
return *static_cast<RigidBodyManipulator *>(getDrakeMexPointer(source));
}
std::set<int> fromMex(const mxArray *source, std::set<int> *) {
// for robotnum. this is kind of a weird one, but OK for now
std::set<int> robotnum_set;
int num_robot = static_cast<int>(mxGetNumberOfElements(source));
double *robotnum = mxGetPrSafe(source);
for (int i = 0; i < num_robot; i++) {
robotnum_set.insert((int) robotnum[i] - 1);
}
return robotnum_set;
}
template<typename Scalar>
KinematicsCache<Scalar> &fromMex(const mxArray *mex, KinematicsCache<Scalar> *) {
if (!mxIsClass(mex, "DrakeMexPointer")) {
throw MexToCppConversionError("Expected DrakeMexPointer containing KinematicsCache");
}
auto name = mxGetStdString(mxGetPropertySafe(mex, "name"));
if (name != typeid(KinematicsCache<Scalar>).name()) {
ostringstream buf;
buf << "Expected KinematicsCache of type " << typeid(KinematicsCache<Scalar>).name() << ", but got " << name;
throw MexToCppConversionError(buf.str());
}
return *static_cast<KinematicsCache<Scalar> *>(getDrakeMexPointer(mex));
}
/**
* toMex specializations
*/
void toMex(const KinematicPath &path, mxArray *dest[], int nlhs) {
if (nlhs > 0) {
dest[0] = stdVectorToMatlab(path.body_path);
}
if (nlhs > 1) {
dest[1] = stdVectorToMatlab(path.joint_path);
}
if (nlhs > 2) {
dest[2] = stdVectorToMatlab(path.joint_direction_signs);
}
}
/**
* make_function
* Note that a completely general make_function implementation is not possible due to ambiguities, but this works for all of the cases in this file
* Inspired by from http://stackoverflow.com/a/21740143/2228557
*/
//plain function pointers
template<typename... Args, typename ReturnType>
auto make_function(ReturnType(*p)(Args...))
-> std::function<ReturnType(Args...)> { return {p}; }
//nonconst member function pointers
template<typename... Args, typename ReturnType, typename ClassType>
auto make_function(ReturnType(ClassType::*p)(Args...))
-> std::function<ReturnType(ClassType&, Args...)> { return {p}; }
//const member function pointers
template<typename... Args, typename ReturnType, typename ClassType>
auto make_function(ReturnType(ClassType::*p)(Args...) const)
-> std::function<ReturnType(const ClassType&, Args...)> { return {p}; }
typedef AutoDiffScalar<VectorXd> AutoDiffDynamicSize;
//typedef AutoDiffScalar<Matrix<double, Dynamic, 1, 0, 72, 1> AutoDiffFixedMaxSize;
/**
* Mex function implementations
*/
void centerOfMassJacobianDotTimesVmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::centerOfMassJacobianDotTimesV<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::centerOfMassJacobianDotTimesV<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centerOfMassmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::centerOfMass<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::centerOfMass<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centerOfMassJacobianmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::centerOfMassJacobian<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::centerOfMassJacobian<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centroidalMomentumMatrixDotTimesvmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::centroidalMomentumMatrixDotTimesV<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::centroidalMomentumMatrixDotTimesV<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void centroidalMomentumMatrixmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::centroidalMomentumMatrix<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::centroidalMomentumMatrix<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
template <typename DerivedQ, typename DerivedV>
void doKinematicsTemp(const RigidBodyManipulator &model, KinematicsCache<typename DerivedQ::Scalar> &cache, const MatrixBase<DerivedQ> &q, const MatrixBase<DerivedV> &v, bool compute_JdotV) {
// temporary solution. Explicit doKinematics calls will not be necessary in the near future.
if (v.size() == 0 && model.num_velocities != 0)
cache.initialize(q);
else
cache.initialize(q, v);
model.doKinematics(cache, compute_JdotV);
}
void doKinematicsmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Matrix<AutoDiffScalar<VectorXd>, Dynamic, 1> VectorXAutoDiff;
auto func_double = make_function(&doKinematicsTemp<Map<const VectorXd>, Map<const VectorXd>>);
auto func_autodiff_dynamic = make_function(&doKinematicsTemp<VectorXAutoDiff, VectorXAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void findKinematicPathmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func = make_function(&RigidBodyManipulator::findKinematicPath);
mexCallFunction(func, nlhs, plhs, nrhs, prhs);
}
void forwardJacDotTimesVmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Map<const Matrix3Xd> DerivedPointsDouble;
auto func_double = make_function(&RigidBodyManipulator::forwardJacDotTimesV<DerivedPointsDouble>);
typedef Matrix<AutoDiffDynamicSize, 3, Dynamic> DerivedPointsAutoDiff;
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::forwardJacDotTimesV<DerivedPointsAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void forwardKinmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Map<const Matrix3Xd> DerivedPointsDouble;
auto func_double = make_function(&RigidBodyManipulator::forwardKin<DerivedPointsDouble>);
typedef Matrix<AutoDiffDynamicSize, 3, Dynamic> DerivedPointsAutoDiff;
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::forwardKin<DerivedPointsAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void forwardKinJacobianmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
typedef Map<const Matrix3Xd> DerivedPointsDouble;
auto func_double = make_function(&RigidBodyManipulator::forwardKinJacobian<DerivedPointsDouble>);
typedef Matrix<AutoDiffDynamicSize, 3, Dynamic> DerivedPointsAutoDiff;
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::forwardKinJacobian<DerivedPointsAutoDiff>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void forwardKinPositionGradientmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::forwardKinPositionGradient<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::forwardKinPositionGradient<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void geometricJacobianDotTimesVmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::geometricJacobianDotTimesV<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::geometricJacobianDotTimesV<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
template <typename Scalar>
GradientVar<Scalar, TWIST_SIZE, Eigen::Dynamic> geometricJacobianTemp(const RigidBodyManipulator &model, const KinematicsCache<Scalar> &cache, int base_body_or_frame_ind, int end_effector_body_or_frame_ind, int expressed_in_body_or_frame_ind, int gradient_order, bool in_terms_of_qdot) {
// temporary solution. Gross v_or_qdot_indices pointer will be gone soon.
return model.geometricJacobian(cache, base_body_or_frame_ind, end_effector_body_or_frame_ind, expressed_in_body_or_frame_ind, gradient_order, in_terms_of_qdot, nullptr);
};
void geometricJacobianmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&geometricJacobianTemp<double>);
auto func_autodiff_dynamic = make_function(&geometricJacobianTemp<AutoDiffDynamicSize>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
void massMatrixmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&RigidBodyManipulator::massMatrix<double>);
auto func_autodiff_dynamic = make_function(&RigidBodyManipulator::massMatrix<AutoDiffScalar<VectorXd>>);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
template <typename Scalar, typename DerivedF, typename DerivedDF>
GradientVar<Scalar, Eigen::Dynamic, 1> dynamicsBiasTermTemp(const RigidBodyManipulator &model, KinematicsCache<Scalar> &cache, const MatrixBase<DerivedF> &f_ext_value, const MatrixBase<DerivedDF> &f_ext_gradient, int gradient_order) {
// temporary solution. GradientVar will disappear, obviating the need for the extra argument. integer body indices will be handled differently.
unordered_map<const RigidBody *, GradientVar<Scalar, 6, 1> > f_ext;
if (f_ext_value.size() > 0) {
assert(f_ext_value.cols() == model.bodies.size());
if (gradient_order > 0) {
assert(f_ext_gradient.rows() == f_ext_value.size());
assert(f_ext_gradient.cols() == model.num_positions + model.num_velocities);
}
for (DenseIndex i = 0; i < f_ext_value.cols(); i++) {
GradientVar<Scalar, TWIST_SIZE, 1> f_ext_gradientvar(TWIST_SIZE, 1, model.num_positions + model.num_velocities, gradient_order);
f_ext_gradientvar.value() = f_ext_value.col(i);
if (gradient_order > 0) {
f_ext_gradientvar.gradient().value() = f_ext_gradient.template middleRows<TWIST_SIZE>(TWIST_SIZE * i);
}
f_ext.insert({model.bodies[i].get(), f_ext_gradientvar});
}
}
return model.dynamicsBiasTerm(cache, f_ext, gradient_order);
};
void dynamicsBiasTermmex(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto func_double = make_function(&dynamicsBiasTermTemp<double, Map<const Matrix<double, 6, Dynamic> >, Map<const Matrix<double, Dynamic, Dynamic> > >);
auto func_autodiff_dynamic = make_function(&dynamicsBiasTermTemp<AutoDiffDynamicSize, Matrix<AutoDiffDynamicSize, 6, Dynamic>, Matrix<AutoDiffDynamicSize, Dynamic, Dynamic> >);
mexTryToCallFunctions(nlhs, plhs, nrhs, prhs, func_double, func_autodiff_dynamic);
}
<|endoftext|> |
<commit_before>/*!
* \page LFSTestSuite_cpp Command-Line Test to Demonstrate How To Test the SimLFS Project
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE LFSTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// SimLFS
#include <simlfs/SIMLFS_Service.hpp>
#include <simlfs/config/simlfs-paths.hpp>
namespace boost_utf = boost::unit_test;
// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("LFSTestSuite_utfresults.xml");
/**
* Configuration for the Boost Unit Test Framework (UTF)
*/
struct UnitTestConfig {
/** Constructor. */
UnitTestConfig() {
boost_utf::unit_test_log.set_stream (utfReportStream);
boost_utf::unit_test_log.set_format (boost_utf::XML);
boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
//boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
}
/** Destructor. */
~UnitTestConfig() {
}
};
// /////////////// Main: Unit Test Suite //////////////
// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);
// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)
/**
* Test a simple price quotation
*/
BOOST_AUTO_TEST_CASE (simlfs_simple_pricing_test) {
// Schedule input filename
const stdair::Filename_T lScheduleInputFilename (STDAIR_SAMPLE_DIR
"/rds01/schedule.csv");
// O&D input filename
const stdair::Filename_T lOnDInputFilename (STDAIR_SAMPLE_DIR "/ond01.csv");
// Fare input file name
const stdair::Filename_T lFareInputFilename (STDAIR_SAMPLE_DIR "/rds01/fare.csv");
SIMFQT::FareFilePath lFareFilePath (lFareInputFilename);
// Yield input file name
const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/rds01/yield.csv");
const AIRRAC::YieldFilePath lYieldFilePath (lYieldInputFilename);
// Check that the file path given as input corresponds to an actual file
bool doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lScheduleInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lScheduleInputFilename
<< "' input file can not be open and read");
// Check that the file path given as input corresponds to an actual file
doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lOnDInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lOnDInputFilename
<< "' input file can not be open and read");
// Check that the file path given as input corresponds to an actual file
doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lFareInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lFareInputFilename
<< "' input file can not be open and read");
// Check that the file path given as input corresponds to an actual file
doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lYieldInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lYieldInputFilename
<< "' input file can not be open and read");
// Output log File
const stdair::Filename_T lLogFilename ("LFSTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the list of classes/buckets
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
SIMLFS::SIMLFS_Service simlfsService (lLogParams, lScheduleInputFilename,
lOnDInputFilename, lFareFilePath,
lYieldFilePath);
// Create an empty booking request structure
// TODO: fill the booking request structure from the input parameters
const stdair::AirportCode_T lOrigin ("SIN");
const stdair::AirportCode_T lDestination ("BKK");
const stdair::AirportCode_T lPOS ("SIN");
const stdair::Date_T lPreferredDepartureDate(2010, boost::gregorian::Jan, 30);
const stdair::Date_T lRequestDate (2010, boost::gregorian::Jan, 22);
const stdair::Duration_T lRequestTime (boost::posix_time::hours(10));
const stdair::DateTime_T lRequestDateTime (lRequestDate, lRequestTime);
const stdair::CabinCode_T lPreferredCabin ("Eco");
const stdair::PartySize_T lPartySize (3);
const stdair::ChannelLabel_T lChannel ("IN");
const stdair::TripType_T lTripType ("RI");
const stdair::DayDuration_T lStayDuration (7);
const stdair::FrequentFlyer_T lFrequentFlyerType ("M");
const stdair::Duration_T lPreferredDepartureTime (boost::posix_time::hours(10));
const stdair::WTP_T lWTP (1000.0);
const stdair::PriceValue_T lValueOfTime (100.0);
const stdair::BookingRequestStruct lBookingRequest (lOrigin, lDestination,
lPOS,
lPreferredDepartureDate,
lRequestDateTime,
lPreferredCabin,
lPartySize, lChannel,
lTripType, lStayDuration,
lFrequentFlyerType,
lPreferredDepartureTime,
lWTP, lValueOfTime);
// TODO: build a hand-made segment-path (as AirSched service is not
// available from here
/*
const stdair::SegmentPathList_T lSegmentPath =
simlfsService.calculateSegmentPathList (lBookingRequest);
// Price the travel solution
stdair::TravelSolutionList_T lTravelSolutionList =
simlfsService.fareQuote (lBookingRequest, lSegmentPath);
//
const unsigned int lNbOfTravelSolutions = lTravelSolutionList.size();
// TODO: change the expected number of travel solutions to the actual number
const unsigned int lExpectedNbOfTravelSolutions = 2;
// DEBUG
STDAIR_LOG_DEBUG ("Number of travel solutions for the booking request '"
<< lBookingRequest.describe() << "': "
<< lNbOfTravelSolutions << ". It is expected to be "
<< lExpectedNbOfTravelSolutions);
BOOST_CHECK_EQUAL (lNbOfTravelSolutions, lExpectedNbOfTravelSolutions);
BOOST_CHECK_MESSAGE(lNbOfTravelSolutions == lExpectedNbOfTravelSolutions,
"The number of travel solutions for the booking request '"
<< lBookingRequest.describe() << "' is equal to "
<< lNbOfTravelSolutions << ", but it should be equal to "
<< lExpectedNbOfTravelSolutions);
//
const stdair::TravelSolutionStruct& lTravelSolution =
lTravelSolutionList.front();
//
const unsigned int lExpectedPrice = 2000;
// DEBUG
STDAIR_LOG_DEBUG ("The price given by the fare quoter for '"
<< lTravelSolution.describe() << "' is: "
<< lTravelSolution.getFare() << " Euros, and should be "
<< lExpectedPrice);
BOOST_CHECK_EQUAL (std::floor (lTravelSolution.getFare() + 0.5),
lExpectedPrice);
BOOST_CHECK_MESSAGE (std::floor (lTravelSolution.getFare() + 0.5)
== lExpectedPrice,
"The price given by the fare quoter for '"
<< lTravelSolution.describe() << "' is: "
<< lTravelSolution.getFare() << " Euros, and should be "
<< lExpectedPrice);
*/
// Close the log file
logOutputFile.close();
}
// End the test suite
BOOST_AUTO_TEST_SUITE_END()
/*!
* \endcode
*/
<commit_msg>[Test] Altered the CSV input files so that the test can pass.<commit_after>/*!
* \page LFSTestSuite_cpp Command-Line Test to Demonstrate How To Test the SimLFS Project
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE LFSTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// SimLFS
#include <simlfs/SIMLFS_Service.hpp>
#include <simlfs/config/simlfs-paths.hpp>
namespace boost_utf = boost::unit_test;
// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("LFSTestSuite_utfresults.xml");
/**
* Configuration for the Boost Unit Test Framework (UTF)
*/
struct UnitTestConfig {
/** Constructor. */
UnitTestConfig() {
boost_utf::unit_test_log.set_stream (utfReportStream);
boost_utf::unit_test_log.set_format (boost_utf::XML);
boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
//boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
}
/** Destructor. */
~UnitTestConfig() {
}
};
// /////////////// Main: Unit Test Suite //////////////
// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);
// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)
/**
* Test a simple price quotation
*/
BOOST_AUTO_TEST_CASE (simlfs_simple_pricing_test) {
// Schedule input filename
const stdair::Filename_T lScheduleInputFilename (STDAIR_SAMPLE_DIR
"/schedule01.csv");
// O&D input filename
const stdair::Filename_T lOnDInputFilename (STDAIR_SAMPLE_DIR "/ond01.csv");
// Fare input file name
const stdair::Filename_T lFareInputFilename (STDAIR_SAMPLE_DIR "/rds01/fare.csv");
SIMFQT::FareFilePath lFareFilePath (lFareInputFilename);
// Yield input file name
const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/yieldstore01.csv");
const AIRRAC::YieldFilePath lYieldFilePath (lYieldInputFilename);
// Check that the file path given as input corresponds to an actual file
bool doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lScheduleInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lScheduleInputFilename
<< "' input file can not be open and read");
// Check that the file path given as input corresponds to an actual file
doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lOnDInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lOnDInputFilename
<< "' input file can not be open and read");
// Check that the file path given as input corresponds to an actual file
doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lFareInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lFareInputFilename
<< "' input file can not be open and read");
// Check that the file path given as input corresponds to an actual file
doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lYieldInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lYieldInputFilename
<< "' input file can not be open and read");
// Output log File
const stdair::Filename_T lLogFilename ("LFSTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the list of classes/buckets
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
SIMLFS::SIMLFS_Service simlfsService (lLogParams, lScheduleInputFilename,
lOnDInputFilename, lFareFilePath,
lYieldFilePath);
// Create an empty booking request structure
// TODO: fill the booking request structure from the input parameters
const stdair::AirportCode_T lOrigin ("SIN");
const stdair::AirportCode_T lDestination ("BKK");
const stdair::AirportCode_T lPOS ("SIN");
const stdair::Date_T lPreferredDepartureDate(2010, boost::gregorian::Jan, 30);
const stdair::Date_T lRequestDate (2010, boost::gregorian::Jan, 22);
const stdair::Duration_T lRequestTime (boost::posix_time::hours(10));
const stdair::DateTime_T lRequestDateTime (lRequestDate, lRequestTime);
const stdair::CabinCode_T lPreferredCabin ("Eco");
const stdair::PartySize_T lPartySize (3);
const stdair::ChannelLabel_T lChannel ("IN");
const stdair::TripType_T lTripType ("RI");
const stdair::DayDuration_T lStayDuration (7);
const stdair::FrequentFlyer_T lFrequentFlyerType ("M");
const stdair::Duration_T lPreferredDepartureTime (boost::posix_time::hours(10));
const stdair::WTP_T lWTP (1000.0);
const stdair::PriceValue_T lValueOfTime (100.0);
const stdair::BookingRequestStruct lBookingRequest (lOrigin, lDestination,
lPOS,
lPreferredDepartureDate,
lRequestDateTime,
lPreferredCabin,
lPartySize, lChannel,
lTripType, lStayDuration,
lFrequentFlyerType,
lPreferredDepartureTime,
lWTP, lValueOfTime);
// TODO: build a hand-made segment-path (as AirSched service is not
// available from here
/*
const stdair::SegmentPathList_T lSegmentPath =
simlfsService.calculateSegmentPathList (lBookingRequest);
// Price the travel solution
stdair::TravelSolutionList_T lTravelSolutionList =
simlfsService.fareQuote (lBookingRequest, lSegmentPath);
//
const unsigned int lNbOfTravelSolutions = lTravelSolutionList.size();
// TODO: change the expected number of travel solutions to the actual number
const unsigned int lExpectedNbOfTravelSolutions = 2;
// DEBUG
STDAIR_LOG_DEBUG ("Number of travel solutions for the booking request '"
<< lBookingRequest.describe() << "': "
<< lNbOfTravelSolutions << ". It is expected to be "
<< lExpectedNbOfTravelSolutions);
BOOST_CHECK_EQUAL (lNbOfTravelSolutions, lExpectedNbOfTravelSolutions);
BOOST_CHECK_MESSAGE(lNbOfTravelSolutions == lExpectedNbOfTravelSolutions,
"The number of travel solutions for the booking request '"
<< lBookingRequest.describe() << "' is equal to "
<< lNbOfTravelSolutions << ", but it should be equal to "
<< lExpectedNbOfTravelSolutions);
//
const stdair::TravelSolutionStruct& lTravelSolution =
lTravelSolutionList.front();
//
const unsigned int lExpectedPrice = 2000;
// DEBUG
STDAIR_LOG_DEBUG ("The price given by the fare quoter for '"
<< lTravelSolution.describe() << "' is: "
<< lTravelSolution.getFare() << " Euros, and should be "
<< lExpectedPrice);
BOOST_CHECK_EQUAL (std::floor (lTravelSolution.getFare() + 0.5),
lExpectedPrice);
BOOST_CHECK_MESSAGE (std::floor (lTravelSolution.getFare() + 0.5)
== lExpectedPrice,
"The price given by the fare quoter for '"
<< lTravelSolution.describe() << "' is: "
<< lTravelSolution.getFare() << " Euros, and should be "
<< lExpectedPrice);
*/
// Close the log file
logOutputFile.close();
}
// End the test suite
BOOST_AUTO_TEST_SUITE_END()
/*!
* \endcode
*/
<|endoftext|> |
<commit_before>#include <node.h>
#include <v8.h>
#include <string>
#include <iostream>
#include "steamworks-sdk/public/steam/steam_api.h"
#include "steamworks-sdk/public/steam/steam_gameserver.h"
#include "steamworks-sdk/public/steam/isteamremotestorage.h"
using namespace v8;
using namespace std;
struct FileIOAsync {
Persistent<Function> errorCallback;
Persistent<Function> successCallback;
string sFilename;
string sContent;
string sError;
bool bSuccess;
};
struct CloudQuota {
Persistent<Function> errorCallback;
Persistent<Function> successCallback;
int nTotalBytes;
int nAvailableBytes;
bool bSuccess;
};
struct Achievement {
Persistent<Function> errorCallback;
Persistent<Function> successCallback;
string sAchievementId;
bool bSuccess;
};
class Greenworks : node::ObjectWrap {
private:
static void steamWriteToFile(uv_work_t *req) {
FileIOAsync *writeData = (FileIOAsync*)req->data;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
// Checking quota (in the future we may need it)
int nTotal = -1, nAvailable = -1;
if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
writeData->sError = "Error getting Cloud quota";
writeData->bSuccess = false;
return;
}
writeData->bSuccess = pSteamRemoteStorage->FileWrite(writeData->sFilename.c_str(), writeData->sContent.c_str(), (int)strlen(writeData->sContent.c_str()));
if (!writeData->bSuccess)
writeData->sError = "Error writing to file. ";
return;
}
static void steamReadFromFile(uv_work_t *req) {
FileIOAsync *readData = (FileIOAsync*)req->data;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
// Check if file exists
if (!pSteamRemoteStorage->FileExists(readData->sFilename.c_str())) {
readData->bSuccess = false;
readData->sError = "File doesn't exist";
return;
}
int32 nFileSize = pSteamRemoteStorage->GetFileSize(readData->sFilename.c_str());
char *sFileContents = new char[nFileSize+1];
int32 cubRead = pSteamRemoteStorage->FileRead( readData->sFilename.c_str(), sFileContents, nFileSize );
sFileContents[cubRead] = 0; // null-terminate
if (cubRead == 0 && nFileSize > 0) {
readData->bSuccess = false;
readData->sError = "Error loading file";
}
else {
readData->bSuccess = true;
readData->sContent = sFileContents;
}
delete sFileContents;
return;
}
static void steamGetCloudQuota(uv_work_t *req) {
CloudQuota *quotaData = (CloudQuota*)req->data;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
int nTotal = -1, nAvailable = -1;
if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
quotaData->bSuccess = false;
return;
}
quotaData->bSuccess = true;
quotaData->nTotalBytes = nTotal;
quotaData->nAvailableBytes = nAvailable;
return;
}
static void steamSetAchievement(uv_work_t *req) {
Achievement *achievementData = (Achievement*)req->data;
ISteamUserStats *pSteamUserStats = SteamUserStats();
pSteamUserStats->SetAchievement(achievementData->sAchievementId.c_str());
achievementData->bSuccess = pSteamUserStats->StoreStats();
return;
}
static void fileWrote(uv_work_t *req) {
FileIOAsync *writeData = (FileIOAsync*)req->data;
// Calling callback here
Handle<Value> callbackResultArgs[1];
if (writeData->bSuccess) {
callbackResultArgs[0] = Undefined();
writeData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
else {
callbackResultArgs[0] = String::New(writeData->sError.c_str());
writeData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
return;
}
static void fileLoaded(uv_work_t *req) {
FileIOAsync *readData = (FileIOAsync*)req->data;
// Calling callback here
Handle<Value> callbackResultArgs[1];
if (readData->bSuccess) {
callbackResultArgs[0] = String::New(readData->sContent.c_str());
readData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
else {
callbackResultArgs[0] = String::New(readData->sError.c_str());
readData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
}
static void gotQuota(uv_work_t *req) {
CloudQuota *quotaData = (CloudQuota*)req->data;
Handle<Value> callbackResultArgs[2];
if (quotaData->bSuccess) {
callbackResultArgs[0] = Integer::New(quotaData->nTotalBytes);
callbackResultArgs[1] = Integer::New(quotaData->nAvailableBytes);
quotaData->successCallback->Call(Context::GetCurrent()->Global(), 2, callbackResultArgs);
}
else {
callbackResultArgs[0] = Undefined();
quotaData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
}
static void achievementStored(uv_work_t *req) {
Achievement *achievementData = (Achievement*)req->data;
Handle<Value> callbackResultArgs[1];
callbackResultArgs[0] = Undefined();
if (achievementData->bSuccess) {
achievementData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
else {
achievementData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
}
public:
GreenheartGames() {}
~GreenheartGames() {}
static Handle<Value> initAPI(const Arguments& args) {
HandleScope scope;
// Initializing Steam API
bool bSuccess = SteamAPI_Init();
if (bSuccess) {
ISteamUserStats *pSteamUserStats = SteamUserStats();
pSteamUserStats->RequestCurrentStats();
}
return scope.Close(Boolean::New(bSuccess));
}
static Handle<Value> getCloudQuota(const Arguments& args) {
HandleScope scope;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
Local<Function>successCallback = Local<Function>::Cast(args[0]);
Local<Function>errorCallback = Local<Function>::Cast(args[1]);
CloudQuota *quotaData = new CloudQuota;
quotaData->successCallback = Persistent<Function>::New(successCallback);
quotaData->errorCallback = Persistent<Function>::New(errorCallback);
uv_work_t *req = new uv_work_t;
req->data = quotaData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamGetCloudQuota, (uv_after_work_cb)gotQuota);
return scope.Close(Undefined());
}
static Handle<Value> saveTextToFile(const Arguments& args) {
HandleScope scope;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
// Convert passed string arguments directly to std::string
string sFilename(*String::Utf8Value(args[0]));
string sContent(*String::Utf8Value(args[1]));
Local<Function>successCallback = Local<Function>::Cast(args[2]);
Local<Function>errorCallback = Local<Function>::Cast(args[3]);
FileIOAsync *writeData = new FileIOAsync;
writeData->successCallback = Persistent<Function>::New(successCallback);
writeData->errorCallback = Persistent<Function>::New(errorCallback);
writeData->sFilename = sFilename;
writeData->sContent = sContent;
// Preparing separate thread work call
uv_work_t *req = new uv_work_t;
req->data = writeData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamWriteToFile, (uv_after_work_cb)fileWrote);
return scope.Close(Undefined());
}
static Handle<Value> readTextFromFile(const Arguments& args) {
HandleScope scope;
// Convert passed string arguments directly to std::string
string sFilename(*String::Utf8Value(args[0]));
Local<Function>successCallback = Local<Function>::Cast(args[1]);
Local<Function>errorCallback = Local<Function>::Cast(args[2]);
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
FileIOAsync *readData = new FileIOAsync;
readData->successCallback = Persistent<Function>::New(successCallback);
readData->errorCallback = Persistent<Function>::New(errorCallback);
readData->sFilename = sFilename;
// Preparing separate thread work call
uv_work_t *req = new uv_work_t;
req->data = readData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamReadFromFile, (uv_after_work_cb)fileLoaded);
return scope.Close(Undefined());
}
static Handle<Value> activateAchievement(const Arguments& args) {
HandleScope scope;
string sAchievementId(*String::Utf8Value(args[0]));
Local<Function>successCallback = Local<Function>::Cast(args[1]);
Local<Function>errorCallback = Local<Function>::Cast(args[2]);
Achievement *achievementData = new Achievement;
achievementData->successCallback = Persistent<Function>::New(successCallback);
achievementData->errorCallback = Persistent<Function>::New(errorCallback);
achievementData->sAchievementId = sAchievementId;
// Preparing separate thread work call
uv_work_t *req = new uv_work_t;
req->data = achievementData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamSetAchievement, (uv_after_work_cb)achievementStored);
return scope.Close(Undefined());
}
};
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("initAPI"), FunctionTemplate::New(GreenheartGames::initAPI)->GetFunction());
exports->Set(String::NewSymbol("getCloudQuota"), FunctionTemplate::New(GreenheartGames::getCloudQuota)->GetFunction());
exports->Set(String::NewSymbol("saveTextToFile"), FunctionTemplate::New(GreenheartGames::saveTextToFile)->GetFunction());
exports->Set(String::NewSymbol("readTextFromFile"), FunctionTemplate::New(GreenheartGames::readTextFromFile)->GetFunction());
exports->Set(String::NewSymbol("activateAchievement"), FunctionTemplate::New(GreenheartGames::activateAchievement)->GetFunction());
}
#ifdef _WIN32
NODE_MODULE(greenworks_win, init)
#elif __APPLE__
NODE_MODULE(greenworks_osx, init)
#elif __linux__
NODE_MODULE(greenworks_linux, init)
#endif
<commit_msg>corrected constructors/destructors and references<commit_after>#include <node.h>
#include <v8.h>
#include <string>
#include <iostream>
#include "steamworks-sdk/public/steam/steam_api.h"
#include "steamworks-sdk/public/steam/steam_gameserver.h"
#include "steamworks-sdk/public/steam/isteamremotestorage.h"
using namespace v8;
using namespace std;
struct FileIOAsync {
Persistent<Function> errorCallback;
Persistent<Function> successCallback;
string sFilename;
string sContent;
string sError;
bool bSuccess;
};
struct CloudQuota {
Persistent<Function> errorCallback;
Persistent<Function> successCallback;
int nTotalBytes;
int nAvailableBytes;
bool bSuccess;
};
struct Achievement {
Persistent<Function> errorCallback;
Persistent<Function> successCallback;
string sAchievementId;
bool bSuccess;
};
class Greenworks : node::ObjectWrap {
private:
static void steamWriteToFile(uv_work_t *req) {
FileIOAsync *writeData = (FileIOAsync*)req->data;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
// Checking quota (in the future we may need it)
int nTotal = -1, nAvailable = -1;
if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
writeData->sError = "Error getting Cloud quota";
writeData->bSuccess = false;
return;
}
writeData->bSuccess = pSteamRemoteStorage->FileWrite(writeData->sFilename.c_str(), writeData->sContent.c_str(), (int)strlen(writeData->sContent.c_str()));
if (!writeData->bSuccess)
writeData->sError = "Error writing to file. ";
return;
}
static void steamReadFromFile(uv_work_t *req) {
FileIOAsync *readData = (FileIOAsync*)req->data;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
// Check if file exists
if (!pSteamRemoteStorage->FileExists(readData->sFilename.c_str())) {
readData->bSuccess = false;
readData->sError = "File doesn't exist";
return;
}
int32 nFileSize = pSteamRemoteStorage->GetFileSize(readData->sFilename.c_str());
char *sFileContents = new char[nFileSize+1];
int32 cubRead = pSteamRemoteStorage->FileRead( readData->sFilename.c_str(), sFileContents, nFileSize );
sFileContents[cubRead] = 0; // null-terminate
if (cubRead == 0 && nFileSize > 0) {
readData->bSuccess = false;
readData->sError = "Error loading file";
}
else {
readData->bSuccess = true;
readData->sContent = sFileContents;
}
delete sFileContents;
return;
}
static void steamGetCloudQuota(uv_work_t *req) {
CloudQuota *quotaData = (CloudQuota*)req->data;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
int nTotal = -1, nAvailable = -1;
if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
quotaData->bSuccess = false;
return;
}
quotaData->bSuccess = true;
quotaData->nTotalBytes = nTotal;
quotaData->nAvailableBytes = nAvailable;
return;
}
static void steamSetAchievement(uv_work_t *req) {
Achievement *achievementData = (Achievement*)req->data;
ISteamUserStats *pSteamUserStats = SteamUserStats();
pSteamUserStats->SetAchievement(achievementData->sAchievementId.c_str());
achievementData->bSuccess = pSteamUserStats->StoreStats();
return;
}
static void fileWrote(uv_work_t *req) {
FileIOAsync *writeData = (FileIOAsync*)req->data;
// Calling callback here
Handle<Value> callbackResultArgs[1];
if (writeData->bSuccess) {
callbackResultArgs[0] = Undefined();
writeData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
else {
callbackResultArgs[0] = String::New(writeData->sError.c_str());
writeData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
return;
}
static void fileLoaded(uv_work_t *req) {
FileIOAsync *readData = (FileIOAsync*)req->data;
// Calling callback here
Handle<Value> callbackResultArgs[1];
if (readData->bSuccess) {
callbackResultArgs[0] = String::New(readData->sContent.c_str());
readData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
else {
callbackResultArgs[0] = String::New(readData->sError.c_str());
readData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
}
static void gotQuota(uv_work_t *req) {
CloudQuota *quotaData = (CloudQuota*)req->data;
Handle<Value> callbackResultArgs[2];
if (quotaData->bSuccess) {
callbackResultArgs[0] = Integer::New(quotaData->nTotalBytes);
callbackResultArgs[1] = Integer::New(quotaData->nAvailableBytes);
quotaData->successCallback->Call(Context::GetCurrent()->Global(), 2, callbackResultArgs);
}
else {
callbackResultArgs[0] = Undefined();
quotaData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
}
static void achievementStored(uv_work_t *req) {
Achievement *achievementData = (Achievement*)req->data;
Handle<Value> callbackResultArgs[1];
callbackResultArgs[0] = Undefined();
if (achievementData->bSuccess) {
achievementData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
else {
achievementData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
}
}
public:
Greenworks() {}
~Greenworks() {}
static Handle<Value> initAPI(const Arguments& args) {
HandleScope scope;
// Initializing Steam API
bool bSuccess = SteamAPI_Init();
if (bSuccess) {
ISteamUserStats *pSteamUserStats = SteamUserStats();
pSteamUserStats->RequestCurrentStats();
}
return scope.Close(Boolean::New(bSuccess));
}
static Handle<Value> getCloudQuota(const Arguments& args) {
HandleScope scope;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
Local<Function>successCallback = Local<Function>::Cast(args[0]);
Local<Function>errorCallback = Local<Function>::Cast(args[1]);
CloudQuota *quotaData = new CloudQuota;
quotaData->successCallback = Persistent<Function>::New(successCallback);
quotaData->errorCallback = Persistent<Function>::New(errorCallback);
uv_work_t *req = new uv_work_t;
req->data = quotaData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamGetCloudQuota, (uv_after_work_cb)gotQuota);
return scope.Close(Undefined());
}
static Handle<Value> saveTextToFile(const Arguments& args) {
HandleScope scope;
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
// Convert passed string arguments directly to std::string
string sFilename(*String::Utf8Value(args[0]));
string sContent(*String::Utf8Value(args[1]));
Local<Function>successCallback = Local<Function>::Cast(args[2]);
Local<Function>errorCallback = Local<Function>::Cast(args[3]);
FileIOAsync *writeData = new FileIOAsync;
writeData->successCallback = Persistent<Function>::New(successCallback);
writeData->errorCallback = Persistent<Function>::New(errorCallback);
writeData->sFilename = sFilename;
writeData->sContent = sContent;
// Preparing separate thread work call
uv_work_t *req = new uv_work_t;
req->data = writeData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamWriteToFile, (uv_after_work_cb)fileWrote);
return scope.Close(Undefined());
}
static Handle<Value> readTextFromFile(const Arguments& args) {
HandleScope scope;
// Convert passed string arguments directly to std::string
string sFilename(*String::Utf8Value(args[0]));
Local<Function>successCallback = Local<Function>::Cast(args[1]);
Local<Function>errorCallback = Local<Function>::Cast(args[2]);
ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
FileIOAsync *readData = new FileIOAsync;
readData->successCallback = Persistent<Function>::New(successCallback);
readData->errorCallback = Persistent<Function>::New(errorCallback);
readData->sFilename = sFilename;
// Preparing separate thread work call
uv_work_t *req = new uv_work_t;
req->data = readData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamReadFromFile, (uv_after_work_cb)fileLoaded);
return scope.Close(Undefined());
}
static Handle<Value> activateAchievement(const Arguments& args) {
HandleScope scope;
string sAchievementId(*String::Utf8Value(args[0]));
Local<Function>successCallback = Local<Function>::Cast(args[1]);
Local<Function>errorCallback = Local<Function>::Cast(args[2]);
Achievement *achievementData = new Achievement;
achievementData->successCallback = Persistent<Function>::New(successCallback);
achievementData->errorCallback = Persistent<Function>::New(errorCallback);
achievementData->sAchievementId = sAchievementId;
// Preparing separate thread work call
uv_work_t *req = new uv_work_t;
req->data = achievementData;
// Call separate thread work
uv_queue_work(uv_default_loop(), req, steamSetAchievement, (uv_after_work_cb)achievementStored);
return scope.Close(Undefined());
}
};
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("initAPI"), FunctionTemplate::New(Greenworks::initAPI)->GetFunction());
exports->Set(String::NewSymbol("getCloudQuota"), FunctionTemplate::New(Greenworks::getCloudQuota)->GetFunction());
exports->Set(String::NewSymbol("saveTextToFile"), FunctionTemplate::New(Greenworks::saveTextToFile)->GetFunction());
exports->Set(String::NewSymbol("readTextFromFile"), FunctionTemplate::New(Greenworks::readTextFromFile)->GetFunction());
exports->Set(String::NewSymbol("activateAchievement"), FunctionTemplate::New(Greenworks::activateAchievement)->GetFunction());
}
#ifdef _WIN32
NODE_MODULE(greenworks_win, init)
#elif __APPLE__
NODE_MODULE(greenworks_osx, init)
#elif __linux__
NODE_MODULE(greenworks_linux, init)
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "tests/test-utils.hh"
#include "sstable_test.hh"
using namespace sstables;
static future<> broken_sst(sstring dir, unsigned long generation) {
// Using an empty schema for this function, which is only about loading
// a malformed component and checking that it fails.
auto s = make_lw_shared(schema({}, "ks", "cf", {}, {}, {}, {}, utf8_type));
auto sst = std::make_unique<sstable>(s, dir, generation, la, big);
auto fut = sst->load();
return std::move(fut).then_wrapped([sst = std::move(sst)] (future<> f) mutable {
try {
f.get();
BOOST_FAIL("expecting exception");
} catch (malformed_sstable_exception& e) {
// ok
}
return make_ready_future<>();
});
}
SEASTAR_TEST_CASE(empty_toc) {
return broken_sst("tests/sstables/badtoc", 1);
}
SEASTAR_TEST_CASE(alien_toc) {
return broken_sst("tests/sstables/badtoc", 2);
}
SEASTAR_TEST_CASE(truncated_toc) {
return broken_sst("tests/sstables/badtoc", 3);
}
SEASTAR_TEST_CASE(wrong_format_toc) {
return broken_sst("tests/sstables/badtoc", 4);
}
SEASTAR_TEST_CASE(compression_truncated) {
return broken_sst("tests/sstables/badcompression", 1);
}
SEASTAR_TEST_CASE(compression_bytes_flipped) {
return broken_sst("tests/sstables/badcompression", 2);
}
<commit_msg>Check the exception message.<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "tests/test-utils.hh"
#include "sstable_test.hh"
using namespace sstables;
static future<> broken_sst(sstring dir, unsigned long generation, sstring msg) {
// Using an empty schema for this function, which is only about loading
// a malformed component and checking that it fails.
auto s = make_lw_shared(schema({}, "ks", "cf", {}, {}, {}, {}, utf8_type));
auto sst = std::make_unique<sstable>(s, dir, generation, la, big);
auto fut = sst->load();
return std::move(fut).then_wrapped([sst = std::move(sst), msg = std::move(msg)] (future<> f) mutable {
try {
f.get();
BOOST_FAIL("expecting exception");
} catch (malformed_sstable_exception& e) {
BOOST_REQUIRE_EQUAL(sstring(e.what()), msg);
}
return make_ready_future<>();
});
}
SEASTAR_TEST_CASE(empty_toc) {
return broken_sst("tests/sstables/badtoc", 1,
"Empty TOC in sstable tests/sstables/badtoc/la-1-big-TOC.txt");
}
SEASTAR_TEST_CASE(alien_toc) {
return broken_sst("tests/sstables/badtoc", 2,
"tests/sstables/badtoc/la-2-big-Statistics.db: file not found");
}
SEASTAR_TEST_CASE(truncated_toc) {
return broken_sst("tests/sstables/badtoc", 3,
"tests/sstables/badtoc/la-3-big-Statistics.db: file not found");
}
SEASTAR_TEST_CASE(wrong_format_toc) {
return broken_sst("tests/sstables/badtoc", 4,
"tests/sstables/badtoc/la-4-big-TOC.txt: file not found");
}
SEASTAR_TEST_CASE(compression_truncated) {
return broken_sst("tests/sstables/badcompression", 1,
"tests/sstables/badcompression/la-1-big-Statistics.db: file not found");
}
SEASTAR_TEST_CASE(compression_bytes_flipped) {
return broken_sst("tests/sstables/badcompression", 2,
"tests/sstables/badcompression/la-2-big-Statistics.db: file not found");
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h"
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
#include "Adafruit_MAX31856.h"
#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288
#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10
#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 100;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Adafruit_MAX31856 tc1 = Adafruit_MAX31856(TC1_CS);
Adafruit_MAX31856 tc2 = Adafruit_MAX31856(TC2_CS);
Adafruit_MAX31856 tc3 = Adafruit_MAX31856(TC3_CS);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data locally (12 bytes)
struct Data {
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
uint32_t timestamp;
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
Payload thePayload;
struct Measurement {
uint32_t time;
int16_t tc1;
int16_t tc2;
int16_t tc3;
};
uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
uint32_t saved_time = 0;
uint16_t interval = 1000;
struct Mem {
long one;
long two;
long three;
long four;
long five;
};
Mem thisMem;
void setup()
{
#ifdef SERIAL_EN
Serial.begin(SERIAL_BAUD);
#endif
randomSeed(analogRead(A4)); //set random seed
NETWORKID += setAddress();
radio.initialize(FREQUENCY,NODEID,NETWORKID);
radio.setHighPower();
radio.encrypt(null);
radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
pinMode(LED, OUTPUT);
// Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
digitalWrite(LED, HIGH); //write LED high to signal attempting connection
while(!getTime()) { //this saves time to the struct which holds the time globally
radio.sleep();
DEBUGFlush();
delay(10000);
}
digitalWrite(LED, LOW); //write low to signal success
DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");
tc1.begin(); tc2.begin(); tc3.begin();
tc1.setThermocoupleType(MAX31856_TCTYPE_E);
tc2.setThermocoupleType(MAX31856_TCTYPE_E);
tc3.setThermocoupleType(MAX31856_TCTYPE_E);
DEBUGln("--Thermocouples are engaged");
DEBUG("--Flash Mem: ");
flash.begin();
uint16_t _name = flash.getChipName();
uint32_t capacity = flash.getCapacity();
DEBUG("W25X"); DEBUG(_name); DEBUG("** ");
DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
DEBUGln("Erasing Chip!"); flash.eraseChip();
}
void loop()
{
current_time = millis();
if(saved_time + interval < current_time) {
thisMem.one = random(0, 1000);
thisMem.two = random(0, 1000);
thisMem.three = random(0, 1000);
thisMem.four = random(0, 1000);
thisMem.five = random(0, 1000);
flash.writeAnything(FLASH_ADDR, thisMem);
Mem newMem;
if(flash.readAnything(FLASH_ADDR, newMem)) {
DEBUGln(newMem.one);
DEBUGln(newMem.two);
DEBUGln(newMem.three);
DEBUGln(newMem.four);
DEBUGln(newMem.five);
DEBUGln();
FLASH_ADDR += sizeof(thisMem);
}
saved_time = current_time;
}
}
/**
* [getTime description]
* @return [description]
*/
bool getTime()
{
LED_STATE = true;
digitalWrite(LED, LED_STATE);
//Get the current timestamp from the datalogger
bool TIME_RECIEVED = false;
if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
DEBUGln("failed . . . no ack");
return false; //if there is no response, returns false and exits function
}
}
while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp);
DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
DEBUGln();
TIME_RECIEVED = true;
LED_STATE = false;
digitalWrite(LED, LED_STATE);
}
if (radio.ACKRequested()) radio.sendACK();
}
}
HANDSHAKE_SENT = false;
return true;
}
/**
* [Blink description]
* @param t [description]
*/
void Blink(uint8_t t) {
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
}
/**
* [setAddress description]
* @return [description]
*/
uint8_t setAddress() {
//sets network address based on which solder jumpers are closed
uint8_t addr01, addr02, addr03;
pinMode(N_SEL_1, INPUT_PULLUP);
pinMode(N_SEL_2, INPUT_PULLUP);
pinMode(N_SEL_4, INPUT_PULLUP);
addr01 = !digitalRead(N_SEL_1);
addr02 = !digitalRead(N_SEL_2) * 2;
addr03 = !digitalRead(N_SEL_4) * 4;
pinMode(N_SEL_1, OUTPUT);
pinMode(N_SEL_2, OUTPUT);
pinMode(N_SEL_4, OUTPUT);
digitalWrite(N_SEL_1, HIGH);
digitalWrite(N_SEL_2, HIGH);
digitalWrite(N_SEL_4, HIGH);
uint8_t addr = addr01 | addr02 | addr03;
return addr;
}
<commit_msg>not fucked yet<commit_after>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h"
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
#include "Adafruit_MAX31856.h"
#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288
#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10
#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 100;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Adafruit_MAX31856 tc1 = Adafruit_MAX31856(TC1_CS);
Adafruit_MAX31856 tc2 = Adafruit_MAX31856(TC2_CS);
Adafruit_MAX31856 tc3 = Adafruit_MAX31856(TC3_CS);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data locally (12 bytes)
struct Data {
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
uint32_t timestamp;
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
Payload thePayload;
uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
uint32_t saved_time = 0;
uint16_t interval = 1000;
void setup()
{
#ifdef SERIAL_EN
Serial.begin(SERIAL_BAUD);
#endif
randomSeed(analogRead(A4)); //set random seed
NETWORKID += setAddress();
radio.initialize(FREQUENCY,NODEID,NETWORKID);
radio.setHighPower();
radio.encrypt(null);
radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
pinMode(LED, OUTPUT);
// Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
digitalWrite(LED, HIGH); //write LED high to signal attempting connection
while(!getTime()) { //this saves time to the struct which holds the time globally
radio.sleep();
DEBUGFlush();
delay(10000);
}
digitalWrite(LED, LOW); //write low to signal success
DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");
tc1.begin(); tc2.begin(); tc3.begin();
tc1.setThermocoupleType(MAX31856_TCTYPE_E);
tc2.setThermocoupleType(MAX31856_TCTYPE_E);
tc3.setThermocoupleType(MAX31856_TCTYPE_E);
DEBUGln("--Thermocouples are engaged");
DEBUG("--Flash Mem: ");
flash.begin();
uint16_t _name = flash.getChipName();
uint32_t capacity = flash.getCapacity();
DEBUG("W25X"); DEBUG(_name); DEBUG("** ");
DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
DEBUGln("Erasing Chip!"); flash.eraseChip();
}
void loop()
{
}
/**
* [getTime description]
* @return [description]
*/
bool getTime()
{
LED_STATE = true;
digitalWrite(LED, LED_STATE);
//Get the current timestamp from the datalogger
bool TIME_RECIEVED = false;
if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
DEBUGln("failed . . . no ack");
return false; //if there is no response, returns false and exits function
}
}
while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp);
DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
DEBUGln();
TIME_RECIEVED = true;
LED_STATE = false;
digitalWrite(LED, LED_STATE);
}
if (radio.ACKRequested()) radio.sendACK();
}
}
HANDSHAKE_SENT = false;
return true;
}
/**
* [Blink description]
* @param t [description]
*/
void Blink(uint8_t t) {
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
}
/**
* [setAddress description]
* @return [description]
*/
uint8_t setAddress() {
//sets network address based on which solder jumpers are closed
uint8_t addr01, addr02, addr03;
pinMode(N_SEL_1, INPUT_PULLUP);
pinMode(N_SEL_2, INPUT_PULLUP);
pinMode(N_SEL_4, INPUT_PULLUP);
addr01 = !digitalRead(N_SEL_1);
addr02 = !digitalRead(N_SEL_2) * 2;
addr03 = !digitalRead(N_SEL_4) * 4;
pinMode(N_SEL_1, OUTPUT);
pinMode(N_SEL_2, OUTPUT);
pinMode(N_SEL_4, OUTPUT);
digitalWrite(N_SEL_1, HIGH);
digitalWrite(N_SEL_2, HIGH);
digitalWrite(N_SEL_4, HIGH);
uint8_t addr = addr01 | addr02 | addr03;
return addr;
}
<|endoftext|> |
<commit_before>#include "BAMap.h"
#include <Arduboy.h>
#include "BAGlobal.h"
#include "ABMapSprites.h"
void drawMapAtPosition(BAPlayer *player, ABPoint position, bool showShips){
// flip for watrer animation
bool waterAnimationStepped = arduboy.everyXFrames(30);
for(byte mapPosY = 0; mapPosY < GAME_BOARD_SIZE_HEIGHT; mapPosY++){
for(byte mapPosX = 0; mapPosX < GAME_BOARD_SIZE_WIDTH; mapPosX++){
int currentMapIndex = player->playerBoard[mapPosY][mapPosX];
//=======================================
// If it's a ship
if(currentMapIndex >= 0 && showShips){
// get actual ship from player
BAShip currentShip = player->shipAtIndex(currentMapIndex);
ABPoint shipPosition = currentShip.position;
shipPosition.x = shipPosition.x*8 + MENU_WIDTH + position.x;
shipPosition.y = shipPosition.y*8 + position.y;
if(currentShip.horizontal)
drawHorizontalShip(shipPosition, currentShip.fullLength, WHITE);
else
drawVerticalShip(shipPosition, currentShip.fullLength, WHITE);
}
//=======================================
// If it's a Mountain
else if(currentMapIndex == BAMapTileTypeMountain){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
}
//=======================================
// If it's a water sprite
else if(currentMapIndex == BAMapTileTypeWater1){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water1, 8, 8, WHITE);
if(waterAnimationStepped) // set to next frame
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater2;
}
else if(currentMapIndex == BAMapTileTypeWater2){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water2, 8, 8, WHITE);
if(waterAnimationStepped) // set to next frame
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater3;
}
else if(currentMapIndex == BAMapTileTypeWater3){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water3, 8, 8, WHITE);
if(waterAnimationStepped) // set to next frame
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater0;
}
//=======================================
// animate water
if(currentMapIndex == BAMapTileTypeWater0 && waterAnimationStepped){
// check probability for new water
if(random(100) < 1)
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater1;
}
//=======================================
// If it's a destroyed ship overdraw the field
if(currentMapIndex == BAMapTileTypeDestroyedShip){
arduboy.fillRect(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, 8, 8, BLACK);
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
}
}
}
}
void drawMap(BAPlayer *player, bool showShips){
drawMapAtPosition(player, ABPointMake(0,0), showShips);
}
<commit_msg>changed map iterration<commit_after>#include "BAMap.h"
#include <Arduboy.h>
#include "BAGlobal.h"
#include "ABMapSprites.h"
void drawMapAtPosition(BAPlayer *player, ABPoint position, bool showShips){
// flip for watrer animation
bool waterAnimationStepped = arduboy.everyXFrames(30);
for(int mapPosY = 0; mapPosY < GAME_BOARD_SIZE_HEIGHT; mapPosY++){
for(int mapPosX = 0; mapPosX < GAME_BOARD_SIZE_WIDTH; mapPosX++){
int currentMapIndex = player->playerBoard[mapPosY][mapPosX];
//=======================================
// If it's a ship
if(currentMapIndex >= 0 && showShips){
// get actual ship from player
BAShip currentShip = player->shipAtIndex(currentMapIndex);
ABPoint shipPosition = currentShip.position;
shipPosition.x = shipPosition.x*8 + MENU_WIDTH + position.x;
shipPosition.y = shipPosition.y*8 + position.y;
if(currentShip.horizontal)
drawHorizontalShip(shipPosition, currentShip.fullLength, WHITE);
else
drawVerticalShip(shipPosition, currentShip.fullLength, WHITE);
}
//=======================================
// If it's a Mountain
else if(currentMapIndex == BAMapTileTypeMountain){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
}
//=======================================
// If it's a water sprite
else if(currentMapIndex == BAMapTileTypeWater1){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water1, 8, 8, WHITE);
if(waterAnimationStepped) // set to next frame
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater2;
}
else if(currentMapIndex == BAMapTileTypeWater2){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water2, 8, 8, WHITE);
if(waterAnimationStepped) // set to next frame
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater3;
}
else if(currentMapIndex == BAMapTileTypeWater3){
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water3, 8, 8, WHITE);
if(waterAnimationStepped) // set to next frame
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater0;
}
//=======================================
// animate water
if(currentMapIndex == BAMapTileTypeWater0 && waterAnimationStepped){
// check probability for new water
if(random(100) < 1)
player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater1;
}
//=======================================
// If it's a destroyed ship overdraw the field
if(currentMapIndex == BAMapTileTypeDestroyedShip){
arduboy.fillRect(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, 8, 8, BLACK);
arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
}
}
}
}
void drawMap(BAPlayer *player, bool showShips){
drawMapAtPosition(player, ABPointMake(0,0), showShips);
}
<|endoftext|> |
<commit_before>//
// Created by iskakoff on 22/08/16.
//
#include <gtest/gtest.h>
#include "edlib/Hamiltonian.h"
#include "edlib/HubbardModel.h"
#include "edlib/Storage.h"
#include "edlib/EDParams.h"
#include "edlib/StaticObservables.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"
#ifdef USE_MPI
class HubbardModelTestEnv : public ::testing::Environment {
protected:
virtual void SetUp() {
char** argv;
int argc = 0;
int mpiError = MPI_Init(&argc, &argv);
}
virtual void TearDown() {
MPI_Finalize();
}
~HubbardModelTestEnv(){};
};
::testing::Environment* const foo_env = AddGlobalTestEnvironment(new HubbardModelTestEnv);
#endif
TEST(HubbardModelTest, ReferenceTest) {
alps::params p;
EDLib::define_parameters(p);
p["NSITES"]=4;
p["NSPINS"]=2;
p["INPUT_FILE"]="test/input/GF_Chi/input.h5";
p["arpack.SECTOR"]=false;
p["storage.MAX_SIZE"]=864;
p["storage.MAX_DIM"]=36;
p["storage.EIGENVALUES_ONLY"]=false;
p["storage.ORBITAL_NUMBER"]=1;
p["arpack.NEV"]=100;
p["lanc.BETA"]=20;
p["lanc.EMIN"]=-4.0;
p["lanc.EMAX"]=4.0;
p["lanc.NOMEGA"]=1000;
#ifdef USE_MPI
typedef EDLib::SRSHubbardHamiltonian HamType;
#else
typedef EDLib::SOCSRHubbardHamiltonian HamType;
#endif
HamType ham(p
#ifdef USE_MPI
, MPI_COMM_WORLD
#endif
);
ham.diag();
// Compute our GFs for the reference model.
EDLib::gf::GreensFunction < HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(p, ham,alps::gf::statistics::statistics_type::FERMIONIC);
greensFunction.compute();
auto G = greensFunction.G();
EDLib::StaticObservables<HamType> so(p);
std::map<std::string, std::vector<double>> observables = so.calculate_static_observables(ham);
EDLib::gf::ChiLoc<HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(p, ham, alps::gf::statistics::statistics_type::BOSONIC);
// compute average magnetic moment
double avg = 0.0;
for(auto x : observables[so._M_]) {
avg += x / (2.0*observables[so._M_].size());
}
// compute spin susceptibility
susc.compute<EDLib::gf::SzOperator<double>>(&avg);
auto ChiSz = susc.G();
// compute average occupancy moment
avg = 0.0;
for(auto x : observables[so._N_]) {
avg += x / double(observables[so._N_].size());
}
// Compute sharge susceptibility
susc.compute<EDLib::gf::NOperator<double>>(&avg);
auto ChiN = susc.G();
// Read in the reference GFs.
// FIXME Desperate kludges. Must take the indextypes from GFs instead.
auto G_file = G;
std::ifstream infile("test/input/GF_Chi/gom1.dat");
for(size_t ii = 0; ii < 200; ++ii){
double omega, real, imag;
infile >> omega >> real >> imag;
for(size_t is = 0; is < ham.model().spins(); ++is){
G_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0), alps::gf::generic_index<alps::gf::index_mesh>(is)) = std::complex<double>(real, imag);
}
}
infile.close();
auto ChiSz_file = ChiSz;
infile.open("test/input/GF_Chi/xiats.dat");
for(size_t ii = 0; ii < 200; ++ii){
double omega, real, imag;
infile >> omega >> real >> imag;
// S_z = 0.5 M, <S_z S_z> = 0.25 <M M>
ChiSz_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-0.25 * real, 0.0);
}
infile.close();
auto ChiN_file = ChiN;
infile.open("test/input/GF_Chi/xiatd.dat");
for(size_t ii = 0; ii < 200; ++ii){
double omega, real, imag;
infile >> omega >> real >> imag;
ChiN_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-real, 0.0);
}
infile.close();
// Subtract the reference GF from our result, the norm() is then the largest diff.
G -= G_file;
ASSERT_NEAR(G.norm(), 0.0, 1e-10);
ChiSz -= ChiSz_file;
ASSERT_NEAR(ChiSz.norm(), 0.0, 1e-9);
ChiN -= ChiN_file;
ASSERT_NEAR(ChiN.norm(), 0.0, 1e-9);
}
<commit_msg>Fix Lanczos_Test<commit_after>//
// Created by iskakoff on 22/08/16.
//
#include <gtest/gtest.h>
#include "edlib/Hamiltonian.h"
#include "edlib/HubbardModel.h"
#include "edlib/Storage.h"
#include "edlib/EDParams.h"
#include "edlib/StaticObservables.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"
#ifdef USE_MPI
class HubbardModelTestEnv : public ::testing::Environment {
protected:
virtual void SetUp() {
char** argv;
int argc = 0;
int mpiError = MPI_Init(&argc, &argv);
}
virtual void TearDown() {
MPI_Finalize();
}
~HubbardModelTestEnv(){};
};
::testing::Environment* const foo_env = AddGlobalTestEnvironment(new HubbardModelTestEnv);
#endif
TEST(HubbardModelTest, ReferenceTest) {
alps::params p;
EDLib::define_parameters(p);
p["NSITES"]=4;
p["NSPINS"]=2;
p["INPUT_FILE"]="test/input/GF_Chi/input.h5";
p["arpack.SECTOR"]=false;
p["storage.MAX_SIZE"]=864;
p["storage.MAX_DIM"]=36;
p["storage.EIGENVALUES_ONLY"]=0;
p["storage.ORBITAL_NUMBER"]=1;
p["arpack.NEV"]=100;
p["lanc.BETA"]=20;
p["lanc.EMIN"]=-4.0;
p["lanc.EMAX"]=4.0;
p["lanc.NOMEGA"]=1000;
#ifdef USE_MPI
typedef EDLib::SRSHubbardHamiltonian HamType;
#else
typedef EDLib::SOCSRHubbardHamiltonian HamType;
#endif
HamType ham(p
#ifdef USE_MPI
, MPI_COMM_WORLD
#endif
);
ham.diag();
// Compute our GFs for the reference model.
EDLib::gf::GreensFunction < HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(p, ham,alps::gf::statistics::statistics_type::FERMIONIC);
greensFunction.compute();
auto G = greensFunction.G();
EDLib::StaticObservables<HamType> so(p);
std::map<std::string, std::vector<double>> observables = so.calculate_static_observables(ham);
EDLib::gf::ChiLoc<HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(p, ham, alps::gf::statistics::statistics_type::BOSONIC);
// compute average magnetic moment
double avg = 0.0;
for(auto x : observables[so._M_]) {
avg += x / (2.0*observables[so._M_].size());
}
// compute spin susceptibility
susc.compute<EDLib::gf::SzOperator<double>>(&avg);
auto ChiSz = susc.G();
// compute average occupancy moment
avg = 0.0;
for(auto x : observables[so._N_]) {
avg += x / double(observables[so._N_].size());
}
// Compute sharge susceptibility
susc.compute<EDLib::gf::NOperator<double>>(&avg);
auto ChiN = susc.G();
// Read in the reference GFs.
// FIXME Desperate kludges. Must take the indextypes from GFs instead.
auto G_file = G;
std::ifstream infile("test/input/GF_Chi/gom1.dat");
for(size_t ii = 0; ii < 200; ++ii){
double omega, real, imag;
infile >> omega >> real >> imag;
for(size_t is = 0; is < ham.model().spins(); ++is){
G_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0), alps::gf::generic_index<alps::gf::index_mesh>(is)) = std::complex<double>(real, imag);
}
}
infile.close();
auto ChiSz_file = ChiSz;
infile.open("test/input/GF_Chi/xiats.dat");
for(size_t ii = 0; ii < 200; ++ii){
double omega, real, imag;
infile >> omega >> real >> imag;
// S_z = 0.5 M, <S_z S_z> = 0.25 <M M>
ChiSz_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-0.25 * real, 0.0);
}
infile.close();
auto ChiN_file = ChiN;
infile.open("test/input/GF_Chi/xiatd.dat");
for(size_t ii = 0; ii < 200; ++ii){
double omega, real, imag;
infile >> omega >> real >> imag;
ChiN_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-real, 0.0);
}
infile.close();
// Subtract the reference GF from our result, the norm() is then the largest diff.
G -= G_file;
ASSERT_NEAR(G.norm(), 0.0, 1e-10);
ChiSz -= ChiSz_file;
ASSERT_NEAR(ChiSz.norm(), 0.0, 1e-9);
ChiN -= ChiN_file;
ASSERT_NEAR(ChiN.norm(), 0.0, 1e-9);
}
<|endoftext|> |
<commit_before>#pragma once
#include <unordered_map>
namespace AGE
{
struct RenderPainter;
struct RenderPipeline
{
std::unordered_map<size_t, RenderPainter> keys;
};
}<commit_msg>culling old file removed<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2016, ROBOTIS CO., LTD.
* 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 ROBOTIS 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 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.
*******************************************************************************/
/* Author: Taehoon Lim (Darby) */
#include "dynamixel_workbench_controllers/velocity_control.h"
using namespace velocity_control;
VelocityControl::VelocityControl()
:node_handle_(""),
node_handle_priv_("~")
{
if (loadDynamixel())
{
checkLoadDynamixel();
}
else
{
ROS_ERROR("Cant' Load Dynamixel, Please check Parameter");
}
multi_driver_->initSyncWrite();
writeValue_ = new WriteValue;
writeValue_->torque.push_back(true);
writeValue_->torque.push_back(true);
multi_driver_->syncWriteTorque(writeValue_->torque);
initDynamixelStatePublisher();
initDynamixelInfoServer();
}
VelocityControl::~VelocityControl()
{
writeValue_->torque.clear();
writeValue_->torque.push_back(false);
writeValue_->torque.push_back(false);
multi_driver_->syncWriteTorque(writeValue_->torque);
ros::shutdown();
}
bool VelocityControl::loadDynamixel()
{
bool ret = false;
dynamixel_driver::DynamixelInfo *left_info = new dynamixel_driver::DynamixelInfo;
left_info->lode_info.device_name = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
left_info->lode_info.baud_rate = node_handle_.param<int>("baud_rate", 57600);
left_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);
left_info->model_id = node_handle_.param<int>("left_id", 1);
dynamixel_info_.push_back(left_info);
dynamixel_driver::DynamixelInfo *right_info = new dynamixel_driver::DynamixelInfo;
right_info->lode_info.device_name = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
right_info->lode_info.baud_rate = node_handle_.param<int>("baud_rate", 57600);
right_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);
right_info->model_id = node_handle_.param<int>("right_id", 1);
dynamixel_info_.push_back(right_info);
multi_driver_ = new dynamixel_multi_driver::DynamixelMultiDriver(dynamixel_info_[MOTOR]->lode_info.device_name,
dynamixel_info_[MOTOR]->lode_info.baud_rate,
dynamixel_info_[MOTOR]->lode_info.protocol_version);
ret = multi_driver_->loadDynamixel(dynamixel_info_);
return ret;
}
bool VelocityControl::setTorque(bool onoff)
{
writeValue_->torque.clear();
writeValue_->torque.push_back(onoff);
writeValue_->torque.push_back(onoff);
if (!multi_driver_->syncWriteTorque(writeValue_->torque))
{
ROS_ERROR("SyncWrite Torque Failed!");
return false;
}
return true;
}
bool VelocityControl::setVelocity(int32_t left_vel, int32_t right_vel)
{
writeValue_->vel.clear();
writeValue_->vel.push_back(left_vel);
writeValue_->vel.push_back(right_vel);
if (!multi_driver_->syncWriteVelocity(writeValue_->vel))
{
ROS_ERROR("SyncWrite Velocity Failed!");
return false;
}
return true;
}
bool VelocityControl::setMovingSpeed(uint16_t left_spd, uint16_t right_spd)
{
writeValue_->spd.clear();
writeValue_->spd.push_back(left_spd);
writeValue_->spd.push_back(right_spd);
if (!multi_driver_->syncWriteMovingSpeed(writeValue_->spd))
{
ROS_ERROR("SyncWrite Moving Speed Failed!");
return false;
}
return true;
}
bool VelocityControl::checkLoadDynamixel()
{
ROS_INFO("-----------------------------------------------------------------------");
ROS_INFO(" dynamixel_workbench controller; velocity control example ");
ROS_INFO("-----------------------------------------------------------------------");
ROS_INFO("PAN MOTOR INFO");
ROS_INFO("ID : %d", dynamixel_info_[LEFT]->model_id);
ROS_INFO("MODEL : %s", dynamixel_info_[LEFT]->model_name.c_str());
ROS_INFO(" ");
ROS_INFO("TILT MOTOR INFO");
ROS_INFO("ID : %d", dynamixel_info_[RIGHT]->model_id);
ROS_INFO("MODEL : %s", dynamixel_info_[RIGHT]->model_name.c_str());
ROS_INFO("-----------------------------------------------------------------------");
}
bool VelocityControl::initDynamixelStatePublisher()
{
dynamixel_state_list_pub_ = node_handle_.advertise<dynamixel_workbench_msgs::DynamixelStateList>("/velocity_control/dynamixel_state", 10);
}
bool VelocityControl::initDynamixelInfoServer()
{
wheel_command_server = node_handle_.advertiseService("/wheel_command", &VelocityControl::wheelCommandMsgCallback, this);
}
bool VelocityControl::readDynamixelState()
{
multi_driver_->readMultiRegister("torque_enable");
multi_driver_->readMultiRegister("present_position");
multi_driver_->readMultiRegister("goal_position");
multi_driver_->readMultiRegister("moving");
if (multi_driver_->getProtocolVersion() == 2.0)
{
if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
{
multi_driver_->readMultiRegister("goal_current");
multi_driver_->readMultiRegister("present_current");
}
multi_driver_->readMultiRegister("goal_velocity");
multi_driver_->readMultiRegister("present_velocity");
}
else
{
multi_driver_->readMultiRegister("moving_speed");
multi_driver_->readMultiRegister("present_speed");
}
}
bool VelocityControl::dynamixelStatePublish()
{
readDynamixelState();
dynamixel_workbench_msgs::DynamixelState dynamixel_state[multi_driver_->multi_dynamixel_.size()];
dynamixel_workbench_msgs::DynamixelStateList dynamixel_state_list;
for (std::vector<dynamixel_tool::DynamixelTool *>::size_type num = 0; num < multi_driver_->multi_dynamixel_.size(); ++num)
{
dynamixel_state[num].model_name = multi_driver_->multi_dynamixel_[num]->model_name_;
dynamixel_state[num].id = multi_driver_->multi_dynamixel_[num]->id_;
dynamixel_state[num].torque_enable = multi_driver_->read_value_["torque_enable"] ->at(num);
dynamixel_state[num].present_position = multi_driver_->read_value_["present_position"] ->at(num);
dynamixel_state[num].goal_position = multi_driver_->read_value_["goal_position"] ->at(num);
dynamixel_state[num].moving = multi_driver_->read_value_["moving"] ->at(num);
if (multi_driver_->getProtocolVersion() == 2.0)
{
if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
{
dynamixel_state[num].goal_current = multi_driver_->read_value_["goal_current"] ->at(num);
dynamixel_state[num].present_current = multi_driver_->read_value_["present_current"]->at(num);
}
dynamixel_state[num].goal_velocity = multi_driver_->read_value_["goal_velocity"]->at(num);
dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_velocity"]->at(num);
}
else
{
dynamixel_state[num].goal_velocity = multi_driver_->read_value_["moving_speed"]->at(num);
dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_speed"]->at(num);
}
dynamixel_state_list.dynamixel_state.push_back(dynamixel_state[num]);
}
dynamixel_state_list_pub_.publish(dynamixel_state_list);
}
int32_t VelocityControl::convertVelocity2Value(float velocity)
{
return (int32_t) (velocity * multi_driver_->multi_dynamixel_[MOTOR]->velocity_to_value_ratio_);
}
bool VelocityControl::controlLoop()
{
dynamixelStatePublish();
}
bool VelocityControl::wheelCommandMsgCallback(dynamixel_workbench_msgs::WheelCommand::Request &req,
dynamixel_workbench_msgs::WheelCommand::Response &res)
{
sleep(0.01);
static float right_vel = 0.0;
static float left_vel = 0.0;
if (req.right_vel == 0.0 && req.left_vel == 0.0)
{
right_vel = 0.0;
left_vel = 0.0;
}
else
{
right_vel += req.right_vel;
left_vel += req.left_vel;
}
if (multi_driver_->getProtocolVersion() == 2.0)
{
setVelocity(convertVelocity2Value(left_vel), convertVelocity2Value(right_vel));
}
else
{
if (right_vel < 0.0 && left_vel < 0.0)
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel * (-1))));
}
else if (right_vel < 0.0 && left_vel > 0.0)
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) * (-1));
}
else if (right_vel > 0.0 && left_vel < 0.0)
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
}
else
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
}
}
res.right_vel = right_vel;
res.left_vel = left_vel;
}
int main(int argc, char **argv)
{
// Init ROS node
ros::init(argc, argv, "velocity_control");
VelocityControl vel_ctrl;
ros::Rate loop_rate(250);
while (ros::ok())
{
vel_ctrl.controlLoop();
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<commit_msg>add pro condition<commit_after>/*******************************************************************************
* Copyright (c) 2016, ROBOTIS CO., LTD.
* 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 ROBOTIS 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 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.
*******************************************************************************/
/* Author: Taehoon Lim (Darby) */
#include "dynamixel_workbench_controllers/velocity_control.h"
using namespace velocity_control;
VelocityControl::VelocityControl()
:node_handle_(""),
node_handle_priv_("~")
{
if (loadDynamixel())
{
checkLoadDynamixel();
}
else
{
ROS_ERROR("Cant' Load Dynamixel, Please check Parameter");
}
multi_driver_->initSyncWrite();
writeValue_ = new WriteValue;
writeValue_->torque.push_back(true);
writeValue_->torque.push_back(true);
multi_driver_->syncWriteTorque(writeValue_->torque);
initDynamixelStatePublisher();
initDynamixelInfoServer();
}
VelocityControl::~VelocityControl()
{
writeValue_->torque.clear();
writeValue_->torque.push_back(false);
writeValue_->torque.push_back(false);
multi_driver_->syncWriteTorque(writeValue_->torque);
ros::shutdown();
}
bool VelocityControl::loadDynamixel()
{
bool ret = false;
dynamixel_driver::DynamixelInfo *left_info = new dynamixel_driver::DynamixelInfo;
left_info->lode_info.device_name = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
left_info->lode_info.baud_rate = node_handle_.param<int>("baud_rate", 57600);
left_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);
left_info->model_id = node_handle_.param<int>("left_id", 1);
dynamixel_info_.push_back(left_info);
dynamixel_driver::DynamixelInfo *right_info = new dynamixel_driver::DynamixelInfo;
right_info->lode_info.device_name = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
right_info->lode_info.baud_rate = node_handle_.param<int>("baud_rate", 57600);
right_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);
right_info->model_id = node_handle_.param<int>("right_id", 1);
dynamixel_info_.push_back(right_info);
multi_driver_ = new dynamixel_multi_driver::DynamixelMultiDriver(dynamixel_info_[MOTOR]->lode_info.device_name,
dynamixel_info_[MOTOR]->lode_info.baud_rate,
dynamixel_info_[MOTOR]->lode_info.protocol_version);
ret = multi_driver_->loadDynamixel(dynamixel_info_);
return ret;
}
bool VelocityControl::setTorque(bool onoff)
{
writeValue_->torque.clear();
writeValue_->torque.push_back(onoff);
writeValue_->torque.push_back(onoff);
if (!multi_driver_->syncWriteTorque(writeValue_->torque))
{
ROS_ERROR("SyncWrite Torque Failed!");
return false;
}
return true;
}
bool VelocityControl::setVelocity(int32_t left_vel, int32_t right_vel)
{
writeValue_->vel.clear();
writeValue_->vel.push_back(left_vel);
writeValue_->vel.push_back(right_vel);
if (!multi_driver_->syncWriteVelocity(writeValue_->vel))
{
ROS_ERROR("SyncWrite Velocity Failed!");
return false;
}
return true;
}
bool VelocityControl::setMovingSpeed(uint16_t left_spd, uint16_t right_spd)
{
writeValue_->spd.clear();
writeValue_->spd.push_back(left_spd);
writeValue_->spd.push_back(right_spd);
if (!multi_driver_->syncWriteMovingSpeed(writeValue_->spd))
{
ROS_ERROR("SyncWrite Moving Speed Failed!");
return false;
}
return true;
}
bool VelocityControl::checkLoadDynamixel()
{
ROS_INFO("-----------------------------------------------------------------------");
ROS_INFO(" dynamixel_workbench controller; velocity control example ");
ROS_INFO("-----------------------------------------------------------------------");
ROS_INFO("PAN MOTOR INFO");
ROS_INFO("ID : %d", dynamixel_info_[LEFT]->model_id);
ROS_INFO("MODEL : %s", dynamixel_info_[LEFT]->model_name.c_str());
ROS_INFO(" ");
ROS_INFO("TILT MOTOR INFO");
ROS_INFO("ID : %d", dynamixel_info_[RIGHT]->model_id);
ROS_INFO("MODEL : %s", dynamixel_info_[RIGHT]->model_name.c_str());
ROS_INFO("-----------------------------------------------------------------------");
}
bool VelocityControl::initDynamixelStatePublisher()
{
dynamixel_state_list_pub_ = node_handle_.advertise<dynamixel_workbench_msgs::DynamixelStateList>("/velocity_control/dynamixel_state", 10);
}
bool VelocityControl::initDynamixelInfoServer()
{
wheel_command_server = node_handle_.advertiseService("/wheel_command", &VelocityControl::wheelCommandMsgCallback, this);
}
bool VelocityControl::readDynamixelState()
{
multi_driver_->readMultiRegister("torque_enable");
multi_driver_->readMultiRegister("present_position");
multi_driver_->readMultiRegister("goal_position");
multi_driver_->readMultiRegister("moving");
if (multi_driver_->getProtocolVersion() == 2.0)
{
if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
{
multi_driver_->readMultiRegister("goal_current");
multi_driver_->readMultiRegister("present_current");
}
multi_driver_->readMultiRegister("goal_velocity");
multi_driver_->readMultiRegister("present_velocity");
}
else
{
multi_driver_->readMultiRegister("moving_speed");
multi_driver_->readMultiRegister("present_speed");
}
}
bool VelocityControl::dynamixelStatePublish()
{
readDynamixelState();
dynamixel_workbench_msgs::DynamixelState dynamixel_state[multi_driver_->multi_dynamixel_.size()];
dynamixel_workbench_msgs::DynamixelStateList dynamixel_state_list;
for (std::vector<dynamixel_tool::DynamixelTool *>::size_type num = 0; num < multi_driver_->multi_dynamixel_.size(); ++num)
{
dynamixel_state[num].model_name = multi_driver_->multi_dynamixel_[num]->model_name_;
dynamixel_state[num].id = multi_driver_->multi_dynamixel_[num]->id_;
dynamixel_state[num].torque_enable = multi_driver_->read_value_["torque_enable"] ->at(num);
dynamixel_state[num].present_position = multi_driver_->read_value_["present_position"] ->at(num);
dynamixel_state[num].goal_position = multi_driver_->read_value_["goal_position"] ->at(num);
dynamixel_state[num].moving = multi_driver_->read_value_["moving"] ->at(num);
if (multi_driver_->getProtocolVersion() == 2.0)
{
if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
{
dynamixel_state[num].goal_current = multi_driver_->read_value_["goal_current"] ->at(num);
dynamixel_state[num].present_current = multi_driver_->read_value_["present_current"]->at(num);
}
dynamixel_state[num].goal_velocity = multi_driver_->read_value_["goal_velocity"]->at(num);
dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_velocity"]->at(num);
}
else
{
dynamixel_state[num].goal_velocity = multi_driver_->read_value_["moving_speed"]->at(num);
dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_speed"]->at(num);
}
dynamixel_state_list.dynamixel_state.push_back(dynamixel_state[num]);
}
dynamixel_state_list_pub_.publish(dynamixel_state_list);
}
int32_t VelocityControl::convertVelocity2Value(float velocity)
{
return (int32_t) (velocity * multi_driver_->multi_dynamixel_[MOTOR]->velocity_to_value_ratio_);
}
bool VelocityControl::controlLoop()
{
dynamixelStatePublish();
}
bool VelocityControl::wheelCommandMsgCallback(dynamixel_workbench_msgs::WheelCommand::Request &req,
dynamixel_workbench_msgs::WheelCommand::Response &res)
{
sleep(0.01);
static float right_vel = 0.0;
static float left_vel = 0.0;
if (req.right_vel == 0.0 && req.left_vel == 0.0)
{
right_vel = 0.0;
left_vel = 0.0;
}
else
{
right_vel += req.right_vel;
left_vel += req.left_vel;
}
if (multi_driver_->getProtocolVersion() == 2.0)
{
if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("PRO") != std::string::npos)
setVelocity(convertVelocity2Value(left_vel), convertVelocity2Value(-right_vel));
else
setVelocity(convertVelocity2Value(left_vel), convertVelocity2Value(right_vel));
}
else
{
if (right_vel < 0.0 && left_vel < 0.0)
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel * (-1))));
}
else if (right_vel < 0.0 && left_vel > 0.0)
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) * (-1));
}
else if (right_vel > 0.0 && left_vel < 0.0)
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
}
else
{
setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
}
}
res.right_vel = right_vel;
res.left_vel = left_vel;
}
int main(int argc, char **argv)
{
// Init ROS node
ros::init(argc, argv, "velocity_control");
VelocityControl vel_ctrl;
ros::Rate loop_rate(250);
while (ros::ok())
{
vel_ctrl.controlLoop();
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Add gmock to main fil -User Stroy #8<commit_after>#include <gtest/gtest.h>
#include <gmock/gmock.h>
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>// 031. Next Permutation
/**
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
*
* If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
*
* The replacement must be in-place, do not allocate extra memory.
*
* Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
* 1,2,3 1,3,2
* 3,2,1 1,2,3
* 1,1,5 1,5,1
*
* Tags: Array
*
* Similar Problems: (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if (n < 2)
{
return;
}
// start from the last element, search for the first pair in ascending order
int i = n - 1;
while ((i > 0) && (nums[i - 1] >= nums[i]))
{
i--;
}
// if found, start from the last element, search for the first element that is larger
if (i != 0)
{
int j = n - 1;
while ((j >= i) && (nums[i - 1] >= nums[j]))
{
j--;
}
// swap these two elements
swap(nums[i - 1], nums[j]);
}
// reverse the rest of the array
reverse(nums.begin() + i, nums.end());
return;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> nums;
nums.push_back(1);
nums.push_back(6);
nums.push_back(6);
nums.push_back(3);
cout << "Current Permutation: ";
for (int i = 0; i < nums.size(); i++)
{
cout << nums[i] << " ";
}
cout << endl;
Solution mySolution;
mySolution.nextPermutation(nums);
cout << "Next Permutation: ";
for (int i = 0; i < nums.size(); i++)
{
cout << nums[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
<commit_msg>Update 031_Next_Permutation.cpp<commit_after>// 031. Next Permutation
/**
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
*
* If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
*
* The replacement must be in-place, do not allocate extra memory.
*
* Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
* 1,2,3 -> 1,3,2
* 3,2,1 -> 1,2,3
* 1,1,5 -> 1,5,1
*
* Tags: Array
*
* Similar Problems: (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if (n < 2)
{
return;
}
// start from the last element, search for the first pair in ascending order
int i = n - 1;
while ((i > 0) && (nums[i - 1] >= nums[i]))
{
i--;
}
// if found, start from the last element, search for the first element that is larger
if (i != 0)
{
int j = n - 1;
while ((j >= i) && (nums[i - 1] >= nums[j]))
{
j--;
}
// swap these two elements
swap(nums[i - 1], nums[j]);
}
// reverse the rest of the array
reverse(nums.begin() + i, nums.end());
return;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> nums;
nums.push_back(1);
nums.push_back(6);
nums.push_back(6);
nums.push_back(3);
cout << "Current Permutation: ";
for (int i = 0; i < nums.size(); i++)
{
cout << nums[i] << " ";
}
cout << endl;
Solution mySolution;
mySolution.nextPermutation(nums);
cout << "Next Permutation: ";
for (int i = 0; i < nums.size(); i++)
{
cout << nums[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2014-01-28 Mark Geiger <[email protected]>
*
* 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 "TIGLViewerSelectWingAndFlapStatusDialog.h"
#include "ui_TIGLViewerSelectWingAndFlapStatusDialog.h"
#include "CCPACSConfigurationManager.h"
#include "CCPACSConfiguration.h"
#include "CCPACSTrailingEdgeDevice.h"
#include "CCPACSWingComponentSegment.h"
#include "CCPACSWing.h"
#include "generated/CPACSControlSurfaceStep.h"
#include "tiglmathfunctions.h"
#include "tiglcommonfunctions.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QSlider>
#include <QToolTip>
#include <QSpacerItem>
#include <QPushButton>
#include <QDoubleSpinBox>
#include <QSpacerItem>
#include <QTableWidget>
#include <QHeaderView>
namespace
{
class SignalsBlocker
{
public:
SignalsBlocker(QObject* ptr):
_ptr(ptr)
{
_b = ptr->blockSignals(true);
}
~SignalsBlocker()
{
_ptr->blockSignals(_b);
}
private:
QObject* _ptr;
bool _b;
};
double sliderToRelativeDeflect(const QSlider* slider, const QDoubleSpinBox* spinBox)
{
double minSlider = static_cast<double>(slider->minimum());
double maxSlider = static_cast<double>(slider->maximum());
double valSlider = static_cast<double>(slider->value());
double minDeflect = spinBox->minimum();
double maxDeflect = spinBox->maximum();
return (maxDeflect - minDeflect)/(maxSlider-minSlider) * (valSlider - minSlider) + minDeflect;
}
} // namespace
TIGLViewerSelectWingAndFlapStatusDialog::TIGLViewerSelectWingAndFlapStatusDialog(TIGLViewerDocument* document, QWidget *parent) :
QDialog(parent),
ui(new Ui::TIGLViewerSelectWingAndFlapStatusDialog)
{
ui->setupUi(this);
this->setWindowTitle("Choose ControlSurface Deflections");
_document = document;
}
TIGLViewerSelectWingAndFlapStatusDialog::~TIGLViewerSelectWingAndFlapStatusDialog()
{
cleanup();
delete ui;
}
void TIGLViewerSelectWingAndFlapStatusDialog::slider_value_changed(int /* k */)
{
QSlider* slider = dynamic_cast<QSlider*>(QObject::sender());
std::string uid = slider->windowTitle().toStdString();
DeviceWidgets& elms = _guiMap.at(uid);
double inputDeflection = sliderToRelativeDeflect(elms.slider, elms.deflectionBox);
SignalsBlocker block(elms.deflectionBox);
updateWidgets(uid, inputDeflection);
_document->updateFlapTransform(uid);
}
void TIGLViewerSelectWingAndFlapStatusDialog::spinBox_value_changed(double inputDeflection)
{
QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(QObject::sender());
std::string uid = spinBox->windowTitle().toStdString();
DeviceWidgets& elms = _guiMap.at(uid);
SignalsBlocker block(elms.slider);
updateWidgets(uid, inputDeflection);
_document->updateFlapTransform(uid);
}
void TIGLViewerSelectWingAndFlapStatusDialog::cleanup()
{
_guiMap.clear();
return;
}
double TIGLViewerSelectWingAndFlapStatusDialog::getTrailingEdgeFlapValue( std::string uid )
{
try {
std::map< std::string, tigl::CCPACSTrailingEdgeDevice*>::iterator it;
it = _deviceMap.find(uid);
if (it == _deviceMap.end()) {
throw tigl::CTiglError("getTrailingEdgeFlapValue: UID not found", TIGL_UID_ERROR);
}
tigl::CCPACSTrailingEdgeDevice* device = it->second;
return device->GetDeflection();
}
catch(...) {
return 0;
}
}
void TIGLViewerSelectWingAndFlapStatusDialog::buildFlapRow(const tigl::CCPACSTrailingEdgeDevice& controlSurfaceDevice, int rowIdx, QTableWidget* gridLayout)
{
QString uid = controlSurfaceDevice.GetUID().c_str();
QLabel* labelUID = new QLabel(uid, this);
QString transparentBG = "background-color: rgba(0, 0, 0, 0.0); padding-left: 6px; padding-right: 6px;";
labelUID->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 0, labelUID);
QSlider* slider = new QSlider(Qt::Horizontal);
slider->setMaximum(1000);
slider->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 1, slider);
QDoubleSpinBox* spinBox = new QDoubleSpinBox();
spinBox->setDecimals(3);
spinBox->setSingleStep(0.005);
spinBox->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 2, spinBox);
QString rot;
if ( controlSurfaceDevice.GetPath().GetSteps().GetSteps().size() > 0 ) {
const auto& step = controlSurfaceDevice.GetPath().GetSteps().GetSteps().front();
if(step) {
rot.append(QString::number(step->GetHingeLineRotation().value_or(0.)));
}
}
QLabel* labelRotation = new QLabel(rot, this);
labelRotation->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 3, labelRotation);
double savedValue = controlSurfaceDevice.GetDeflection();
double minDeflect = controlSurfaceDevice.GetMinDeflection();
double maxDeflect = controlSurfaceDevice.GetMaxDeflection();
int newSliderValue = static_cast<int>((slider->maximum() - slider->minimum()) / (maxDeflect-minDeflect) * (savedValue - minDeflect))
+ slider->minimum();
slider->setValue(newSliderValue);
spinBox->setMinimum(minDeflect);
spinBox->setValue(savedValue);
spinBox->setMaximum(maxDeflect);
DeviceWidgets elements;
elements.slider = slider;
elements.deflectionBox = spinBox;
elements.rotAngleLabel = labelRotation;
_guiMap[uid.toStdString()] = elements;
slider->setWindowTitle( uid );
spinBox->setWindowTitle( uid );
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(slider_value_changed(int)));
connect(spinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBox_value_changed(double)));
}
void TIGLViewerSelectWingAndFlapStatusDialog::drawGUI()
{
cleanup();
std::string wingUID = m_currentWing;
if (wingUID.empty())
return;
tigl::CCPACSConfiguration& config = _document->GetConfiguration();
tigl::CCPACSWing &wing = config.GetWing(wingUID);
int noDevices = wing.GetComponentSegmentCount();
std::vector<tigl::CCPACSTrailingEdgeDevice*> devices;
for ( int i = 1; i <= wing.GetComponentSegmentCount(); i++ ) {
tigl::CCPACSWingComponentSegment& componentSegment = static_cast<tigl::CCPACSWingComponentSegment&>(wing.GetComponentSegment(i));
const auto& controlSurfaces = componentSegment.GetControlSurfaces();
if (!controlSurfaces || controlSurfaces->ControlSurfaceCount() < 1) {
noDevices--;
if (noDevices < 1) {
continue;
}
}
// @todo: what if no TEDS? fix this
for ( const auto& controlSurfaceDevice : controlSurfaces->GetTrailingEdgeDevices()->GetTrailingEdgeDevices()) {
if (!controlSurfaceDevice) {
continue;
}
if ((!ui->checkTED->isChecked() && controlSurfaceDevice->GetType() == TRAILING_EDGE_DEVICE) ||
(!ui->checkLED->isChecked() && controlSurfaceDevice->GetType() == LEADING_EDGE_DEVICE) ||
(!ui->checkSpoiler->isChecked() && controlSurfaceDevice->GetType() == SPOILER)) {
continue;
}
devices.push_back(controlSurfaceDevice.get());
}
}
auto* tableWidget = new QTableWidget(static_cast<int>(devices.size()), 4);
int rowIdx = 0;
for (auto* device : devices) {
buildFlapRow(*device, rowIdx++, tableWidget);
_deviceMap[device->GetUID()] = device;
updateWidgets(device->GetUID(), device->GetDeflection() );
}
// set style
tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
tableWidget->setAlternatingRowColors(true);
tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tableWidget->setHorizontalHeaderLabels(QStringList({"", "", "Deflection", "Rotation"}));
tableWidget->verticalHeader()->hide();
tableWidget->setStyleSheet("QHeaderView::section { border: 0px solid black}");
ui->scrollArea->setWidget(tableWidget);
}
void TIGLViewerSelectWingAndFlapStatusDialog::on_checkTED_stateChanged(int)
{
drawGUI();
}
void TIGLViewerSelectWingAndFlapStatusDialog::on_checkLED_stateChanged(int)
{
drawGUI();
}
void TIGLViewerSelectWingAndFlapStatusDialog::on_checkSpoiler_stateChanged(int)
{
drawGUI();
}
void TIGLViewerSelectWingAndFlapStatusDialog::updateWidgets(std::string controlSurfaceDeviceUID,
double inputDeflection)
{
DeviceWidgets& elms = _guiMap.at(controlSurfaceDeviceUID);
QString textVal;
std::map< std::string, tigl::CCPACSTrailingEdgeDevice*>::iterator it;
it = _deviceMap.find(controlSurfaceDeviceUID);
if (it == _deviceMap.end()) {
return;
}
tigl::CCPACSTrailingEdgeDevice* device = it->second;
// Get rotation for current deflection value
std::vector<double> relDeflections;
std::vector<double> rotations;
const tigl::CCPACSControlSurfaceSteps& steps = device->GetPath().GetSteps();
for ( const auto &step : steps.GetSteps()) {
if (!step) continue;
relDeflections.push_back(step->GetRelDeflection());
rotations.push_back(step->GetHingeLineRotation().value_or(0.));
}
double rotation = tigl::Interpolate(relDeflections, rotations, inputDeflection);
QString textRot = QString::number(rotation);
double factor = ( inputDeflection - device->GetMinDeflection() ) / ( device->GetMaxDeflection() - device->GetMinDeflection() );
textVal.append(QString::number(100 * factor));
textVal.append("% ");
int sliderVal = static_cast<int>(Mix(elms.slider->minimum(), elms.slider->maximum(), factor));
elms.slider->setValue(sliderVal);
elms.deflectionBox->setValue(inputDeflection);
elms.rotAngleLabel->setText(textRot);
device->SetDeflection(inputDeflection);
}
<commit_msg>Another compile fix for qt4<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2014-01-28 Mark Geiger <[email protected]>
*
* 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 "TIGLViewerSelectWingAndFlapStatusDialog.h"
#include "ui_TIGLViewerSelectWingAndFlapStatusDialog.h"
#include "CCPACSConfigurationManager.h"
#include "CCPACSConfiguration.h"
#include "CCPACSTrailingEdgeDevice.h"
#include "CCPACSWingComponentSegment.h"
#include "CCPACSWing.h"
#include "generated/CPACSControlSurfaceStep.h"
#include "tiglmathfunctions.h"
#include "tiglcommonfunctions.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QSlider>
#include <QToolTip>
#include <QSpacerItem>
#include <QPushButton>
#include <QDoubleSpinBox>
#include <QSpacerItem>
#include <QTableWidget>
#include <QHeaderView>
#include <QtGlobal>
namespace
{
class SignalsBlocker
{
public:
SignalsBlocker(QObject* ptr):
_ptr(ptr)
{
_b = ptr->blockSignals(true);
}
~SignalsBlocker()
{
_ptr->blockSignals(_b);
}
private:
QObject* _ptr;
bool _b;
};
double sliderToRelativeDeflect(const QSlider* slider, const QDoubleSpinBox* spinBox)
{
double minSlider = static_cast<double>(slider->minimum());
double maxSlider = static_cast<double>(slider->maximum());
double valSlider = static_cast<double>(slider->value());
double minDeflect = spinBox->minimum();
double maxDeflect = spinBox->maximum();
return (maxDeflect - minDeflect)/(maxSlider-minSlider) * (valSlider - minSlider) + minDeflect;
}
} // namespace
TIGLViewerSelectWingAndFlapStatusDialog::TIGLViewerSelectWingAndFlapStatusDialog(TIGLViewerDocument* document, QWidget *parent) :
QDialog(parent),
ui(new Ui::TIGLViewerSelectWingAndFlapStatusDialog)
{
ui->setupUi(this);
this->setWindowTitle("Choose ControlSurface Deflections");
_document = document;
}
TIGLViewerSelectWingAndFlapStatusDialog::~TIGLViewerSelectWingAndFlapStatusDialog()
{
cleanup();
delete ui;
}
void TIGLViewerSelectWingAndFlapStatusDialog::slider_value_changed(int /* k */)
{
QSlider* slider = dynamic_cast<QSlider*>(QObject::sender());
std::string uid = slider->windowTitle().toStdString();
DeviceWidgets& elms = _guiMap.at(uid);
double inputDeflection = sliderToRelativeDeflect(elms.slider, elms.deflectionBox);
SignalsBlocker block(elms.deflectionBox);
updateWidgets(uid, inputDeflection);
_document->updateFlapTransform(uid);
}
void TIGLViewerSelectWingAndFlapStatusDialog::spinBox_value_changed(double inputDeflection)
{
QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(QObject::sender());
std::string uid = spinBox->windowTitle().toStdString();
DeviceWidgets& elms = _guiMap.at(uid);
SignalsBlocker block(elms.slider);
updateWidgets(uid, inputDeflection);
_document->updateFlapTransform(uid);
}
void TIGLViewerSelectWingAndFlapStatusDialog::cleanup()
{
_guiMap.clear();
return;
}
double TIGLViewerSelectWingAndFlapStatusDialog::getTrailingEdgeFlapValue( std::string uid )
{
try {
std::map< std::string, tigl::CCPACSTrailingEdgeDevice*>::iterator it;
it = _deviceMap.find(uid);
if (it == _deviceMap.end()) {
throw tigl::CTiglError("getTrailingEdgeFlapValue: UID not found", TIGL_UID_ERROR);
}
tigl::CCPACSTrailingEdgeDevice* device = it->second;
return device->GetDeflection();
}
catch(...) {
return 0;
}
}
void TIGLViewerSelectWingAndFlapStatusDialog::buildFlapRow(const tigl::CCPACSTrailingEdgeDevice& controlSurfaceDevice, int rowIdx, QTableWidget* gridLayout)
{
QString uid = controlSurfaceDevice.GetUID().c_str();
QLabel* labelUID = new QLabel(uid, this);
QString transparentBG = "background-color: rgba(0, 0, 0, 0.0); padding-left: 6px; padding-right: 6px;";
labelUID->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 0, labelUID);
QSlider* slider = new QSlider(Qt::Horizontal);
slider->setMaximum(1000);
slider->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 1, slider);
QDoubleSpinBox* spinBox = new QDoubleSpinBox();
spinBox->setDecimals(3);
spinBox->setSingleStep(0.005);
spinBox->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 2, spinBox);
QString rot;
if ( controlSurfaceDevice.GetPath().GetSteps().GetSteps().size() > 0 ) {
const auto& step = controlSurfaceDevice.GetPath().GetSteps().GetSteps().front();
if(step) {
rot.append(QString::number(step->GetHingeLineRotation().value_or(0.)));
}
}
QLabel* labelRotation = new QLabel(rot, this);
labelRotation->setStyleSheet(transparentBG);
gridLayout->setCellWidget(rowIdx, 3, labelRotation);
double savedValue = controlSurfaceDevice.GetDeflection();
double minDeflect = controlSurfaceDevice.GetMinDeflection();
double maxDeflect = controlSurfaceDevice.GetMaxDeflection();
int newSliderValue = static_cast<int>((slider->maximum() - slider->minimum()) / (maxDeflect-minDeflect) * (savedValue - minDeflect))
+ slider->minimum();
slider->setValue(newSliderValue);
spinBox->setMinimum(minDeflect);
spinBox->setValue(savedValue);
spinBox->setMaximum(maxDeflect);
DeviceWidgets elements;
elements.slider = slider;
elements.deflectionBox = spinBox;
elements.rotAngleLabel = labelRotation;
_guiMap[uid.toStdString()] = elements;
slider->setWindowTitle( uid );
spinBox->setWindowTitle( uid );
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(slider_value_changed(int)));
connect(spinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBox_value_changed(double)));
}
void TIGLViewerSelectWingAndFlapStatusDialog::drawGUI()
{
cleanup();
std::string wingUID = m_currentWing;
if (wingUID.empty())
return;
tigl::CCPACSConfiguration& config = _document->GetConfiguration();
tigl::CCPACSWing &wing = config.GetWing(wingUID);
int noDevices = wing.GetComponentSegmentCount();
std::vector<tigl::CCPACSTrailingEdgeDevice*> devices;
for ( int i = 1; i <= wing.GetComponentSegmentCount(); i++ ) {
tigl::CCPACSWingComponentSegment& componentSegment = static_cast<tigl::CCPACSWingComponentSegment&>(wing.GetComponentSegment(i));
const auto& controlSurfaces = componentSegment.GetControlSurfaces();
if (!controlSurfaces || controlSurfaces->ControlSurfaceCount() < 1) {
noDevices--;
if (noDevices < 1) {
continue;
}
}
// @todo: what if no TEDS? fix this
for ( const auto& controlSurfaceDevice : controlSurfaces->GetTrailingEdgeDevices()->GetTrailingEdgeDevices()) {
if (!controlSurfaceDevice) {
continue;
}
if ((!ui->checkTED->isChecked() && controlSurfaceDevice->GetType() == TRAILING_EDGE_DEVICE) ||
(!ui->checkLED->isChecked() && controlSurfaceDevice->GetType() == LEADING_EDGE_DEVICE) ||
(!ui->checkSpoiler->isChecked() && controlSurfaceDevice->GetType() == SPOILER)) {
continue;
}
devices.push_back(controlSurfaceDevice.get());
}
}
auto* tableWidget = new QTableWidget(static_cast<int>(devices.size()), 4);
int rowIdx = 0;
for (auto* device : devices) {
buildFlapRow(*device, rowIdx++, tableWidget);
_deviceMap[device->GetUID()] = device;
updateWidgets(device->GetUID(), device->GetDeflection() );
}
// set style
tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
tableWidget->setAlternatingRowColors(true);
#if QT_VERSION >= 0x050000
tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif
tableWidget->setHorizontalHeaderLabels(QStringList({"", "", "Deflection", "Rotation"}));
tableWidget->verticalHeader()->hide();
tableWidget->setStyleSheet("QHeaderView::section { border: 0px solid black}");
ui->scrollArea->setWidget(tableWidget);
}
void TIGLViewerSelectWingAndFlapStatusDialog::on_checkTED_stateChanged(int)
{
drawGUI();
}
void TIGLViewerSelectWingAndFlapStatusDialog::on_checkLED_stateChanged(int)
{
drawGUI();
}
void TIGLViewerSelectWingAndFlapStatusDialog::on_checkSpoiler_stateChanged(int)
{
drawGUI();
}
void TIGLViewerSelectWingAndFlapStatusDialog::updateWidgets(std::string controlSurfaceDeviceUID,
double inputDeflection)
{
DeviceWidgets& elms = _guiMap.at(controlSurfaceDeviceUID);
QString textVal;
std::map< std::string, tigl::CCPACSTrailingEdgeDevice*>::iterator it;
it = _deviceMap.find(controlSurfaceDeviceUID);
if (it == _deviceMap.end()) {
return;
}
tigl::CCPACSTrailingEdgeDevice* device = it->second;
// Get rotation for current deflection value
std::vector<double> relDeflections;
std::vector<double> rotations;
const tigl::CCPACSControlSurfaceSteps& steps = device->GetPath().GetSteps();
for ( const auto &step : steps.GetSteps()) {
if (!step) continue;
relDeflections.push_back(step->GetRelDeflection());
rotations.push_back(step->GetHingeLineRotation().value_or(0.));
}
double rotation = tigl::Interpolate(relDeflections, rotations, inputDeflection);
QString textRot = QString::number(rotation);
double factor = ( inputDeflection - device->GetMinDeflection() ) / ( device->GetMaxDeflection() - device->GetMinDeflection() );
textVal.append(QString::number(100 * factor));
textVal.append("% ");
int sliderVal = static_cast<int>(Mix(elms.slider->minimum(), elms.slider->maximum(), factor));
elms.slider->setValue(sliderVal);
elms.deflectionBox->setValue(inputDeflection);
elms.rotAngleLabel->setText(textRot);
device->SetDeflection(inputDeflection);
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014 Luis B. Barrancos, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "orennayarbrdf.h"
// appleseed.renderer headers.
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/bsdfwrapper.h"
// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/sampling.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
// Standard headers.
#include <algorithm>
#include <cmath>
// Forward declarations.
namespace foundation { class AbortSwitch; }
namespace renderer { class Assembly; }
namespace renderer { class Project; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Oren-Nayar BRDF.
//
const char* Model = "orennayar_brdf";
class OrenNayarBRDFImpl
: public BSDF
{
public:
OrenNayarBRDFImpl(
const char* name,
const ParamArray& params)
: BSDF(name, Reflective, Diffuse, params)
{
m_inputs.declare("reflectance", InputFormatSpectralReflectance);
m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
m_inputs.declare("roughness" , InputFormatScalar, "0.1");
}
virtual void release() OVERRIDE
{
delete this;
}
virtual const char* get_model() const OVERRIDE
{
return Model;
}
FORCE_INLINE virtual Mode sample(
SamplingContext& sampling_context,
const void* data,
const bool adjoint,
const bool cosine_mult,
const Vector3d& geometric_normal,
const Basis3d& shading_basis,
const Vector3d& outgoing,
Vector3d& incoming,
Spectrum& value,
double& probability) const
{
// No reflection below the shading surface.
const Vector3d& n = shading_basis.get_normal();
const double cos_on = min(dot(outgoing, n), 1.0);
if (cos_on < 0.0)
return Absorption;
// Compute the incoming direction in local space.
sampling_context.split_in_place(2, 1);
const Vector2d s = sampling_context.next_vector2<2>();
const Vector3d wi = sample_hemisphere_cosine(s);
// Transform the incoming direction to parent space.
incoming = shading_basis.transform_to_parent(wi);
// No reflection below the shading surface.
const double cos_in = dot(incoming, n);
if (cos_in < 0.0)
return Absorption;
// Compute the BRDF value.
const InputValues* values = static_cast<const InputValues*>(data);
if (values->m_roughness != 0)
oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);
else
value = values->m_reflectance;
value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi);
// Compute the probability density of the sampled direction.
probability = wi.y * RcpPi;
assert(probability > 0.0);
// Return the scattering mode.
return Diffuse;
}
FORCE_INLINE virtual double evaluate(
const void* data,
const bool adjoint,
const bool cosine_mult,
const Vector3d& geometric_normal,
const Basis3d& shading_basis,
const Vector3d& outgoing,
const Vector3d& incoming,
const int modes,
Spectrum& value) const
{
if (!(modes & Diffuse))
return 0.0;
// No reflection below the shading surface.
const Vector3d& n = shading_basis.get_normal();
const double cos_in = dot(incoming, n);
const double cos_on = min(dot(outgoing, n), 1.0);
if (cos_in < 0.0 || cos_on < 0.0)
return 0.0;
// Compute the BRDF value.
const InputValues* values = static_cast<const InputValues*>(data);
if (values->m_roughness != 0)
oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);
else
value = values->m_reflectance;
value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi );
// Return the probability density of the sampled direction.
return cos_in * RcpPi;
}
FORCE_INLINE virtual double evaluate_pdf(
const void* data,
const Vector3d& geometric_normal,
const Basis3d& shading_basis,
const Vector3d& outgoing,
const Vector3d& incoming,
const int modes) const
{
if (!(modes & Diffuse))
return 0.0;
// No reflection below the shading surface.
const Vector3d& n = shading_basis.get_normal();
const double cos_in = dot(incoming, n);
const double cos_on = min(dot(outgoing, n), 1.0);
if (cos_in < 0.0 || cos_on < 0.0)
return 0.0;
return cos_in * RcpPi;
}
void oren_nayar_qualitative(
const double cos_on,
const double cos_in,
const double roughness,
const Spectrum& reflectance,
const Vector3d& outgoing,
const Vector3d& incoming,
const Vector3d& n,
Spectrum& value) const
{
const double theta_r = min(HalfPi, acos(cos_on));
const double theta_i = acos(cos_in);
const double alpha = max(theta_i, theta_r);
const double beta = min(theta_i, theta_r);
const double sigma2 = square(roughness);
const double C1 = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33));
double C2 = 0.45 * sigma2 / (sigma2 + 0.09);
const Vector3d V_perp_N = normalize(outgoing - n * dot(outgoing, n));
const double cos_phi_diff = dot(V_perp_N, normalize(incoming - n * cos_in));
if (cos_phi_diff >= 0.0)
C2 *= sin(alpha);
else
{
const double temp = 2.0 * beta * RcpPi;
C2 *= sin(alpha) - square(temp) * temp;
}
const double C3 = 0.125 * (sigma2 / (sigma2 + 0.09) * square(4.0 * alpha * beta * RcpPiSq)) * tan((alpha + beta) * 0.5);
value = reflectance ;
value *= static_cast<float>(C1 + (cos_phi_diff * C2 * tan(beta)) + (1 - abs(cos_phi_diff)) * C3);
value += square(reflectance) * static_cast<float>(0.17 * cos_in * (sigma2 / (sigma2 + 0.13)) *
(1 - cos_phi_diff * square(2 * beta * RcpPi)));
}
private:
typedef OrenNayarBRDFInputValues InputValues;
};
typedef BSDFWrapper<OrenNayarBRDFImpl> OrenNayarBRDF;
}
//
// OrenNayarBRDFFactory class implementation.
//
const char* OrenNayarBRDFFactory::get_model() const
{
return Model;
}
const char* OrenNayarBRDFFactory::get_human_readable_model() const
{
return "Oren-Nayar BRDF";
}
DictionaryArray OrenNayarBRDFFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "reflectance")
.insert("label", "Reflectance")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "reflectance_multiplier")
.insert("label", "Reflectance Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "roughness")
.insert("label", "Roughness")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.1"));
return metadata;
}
auto_release_ptr<BSDF> OrenNayarBRDFFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<BSDF>(new OrenNayarBRDF(name, params));
}
} // namespace renderer
<commit_msg>Fixed potential negative pdf values.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014 Luis B. Barrancos, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "orennayarbrdf.h"
// appleseed.renderer headers.
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/bsdfwrapper.h"
// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/sampling.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
// Standard headers.
#include <algorithm>
#include <cmath>
// Forward declarations.
namespace foundation { class AbortSwitch; }
namespace renderer { class Assembly; }
namespace renderer { class Project; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Oren-Nayar BRDF.
//
const char* Model = "orennayar_brdf";
class OrenNayarBRDFImpl
: public BSDF
{
public:
OrenNayarBRDFImpl(
const char* name,
const ParamArray& params)
: BSDF(name, Reflective, Diffuse, params)
{
m_inputs.declare("reflectance", InputFormatSpectralReflectance);
m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
m_inputs.declare("roughness" , InputFormatScalar, "0.1");
}
virtual void release() OVERRIDE
{
delete this;
}
virtual const char* get_model() const OVERRIDE
{
return Model;
}
FORCE_INLINE virtual Mode sample(
SamplingContext& sampling_context,
const void* data,
const bool adjoint,
const bool cosine_mult,
const Vector3d& geometric_normal,
const Basis3d& shading_basis,
const Vector3d& outgoing,
Vector3d& incoming,
Spectrum& value,
double& probability) const
{
// No reflection below the shading surface.
const Vector3d& n = shading_basis.get_normal();
const double cos_on = dot(outgoing, n);
if (cos_on < 0.0)
return Absorption;
// Compute the incoming direction in local space.
sampling_context.split_in_place(2, 1);
const Vector2d s = sampling_context.next_vector2<2>();
const Vector3d wi = sample_hemisphere_cosine(s);
// Transform the incoming direction to parent space.
incoming = shading_basis.transform_to_parent(wi);
// No reflection below the shading surface.
const double cos_in = dot(incoming, n);
if (cos_in < 0.0)
return Absorption;
// Compute the BRDF value.
const InputValues* values = static_cast<const InputValues*>(data);
if (values->m_roughness != 0)
oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);
else
value = values->m_reflectance;
value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi);
// Compute the probability density of the sampled direction.
probability = wi.y * RcpPi;
assert(probability > 0.0);
// Return the scattering mode.
return Diffuse;
}
FORCE_INLINE virtual double evaluate(
const void* data,
const bool adjoint,
const bool cosine_mult,
const Vector3d& geometric_normal,
const Basis3d& shading_basis,
const Vector3d& outgoing,
const Vector3d& incoming,
const int modes,
Spectrum& value) const
{
if (!(modes & Diffuse))
return 0.0;
// No reflection below the shading surface.
const Vector3d& n = shading_basis.get_normal();
const double cos_in = dot(incoming, n);
const double cos_on = min(dot(outgoing, n), 1.0);
if (cos_in < 0.0 || cos_on < 0.0)
return 0.0;
// Compute the BRDF value.
const InputValues* values = static_cast<const InputValues*>(data);
if (values->m_roughness != 0)
oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);
else
value = values->m_reflectance;
value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi );
// Return the probability density of the sampled direction.
return cos_in * RcpPi;
}
FORCE_INLINE virtual double evaluate_pdf(
const void* data,
const Vector3d& geometric_normal,
const Basis3d& shading_basis,
const Vector3d& outgoing,
const Vector3d& incoming,
const int modes) const
{
if (!(modes & Diffuse))
return 0.0;
// No reflection below the shading surface.
const Vector3d& n = shading_basis.get_normal();
const double cos_in = dot(incoming, n);
const double cos_on = min(dot(outgoing, n), 1.0);
if (cos_in < 0.0 || cos_on < 0.0)
return 0.0;
return cos_in * RcpPi;
}
void oren_nayar_qualitative(
const double cos_on,
const double cos_in,
const double roughness,
const Spectrum& reflectance,
const Vector3d& outgoing,
const Vector3d& incoming,
const Vector3d& n,
Spectrum& value) const
{
const double theta_r = min(HalfPi, acos(cos_on));
const double theta_i = acos(cos_in);
const double alpha = max(theta_i, theta_r);
const double beta = min(theta_i, theta_r);
const double sigma2 = square(roughness);
const double C1 = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33));
assert( C1 >= 0.0 );
double C2 = 0.45 * sigma2 / (sigma2 + 0.09);
const Vector3d V_perp_N = normalize(outgoing - n * dot(outgoing, n));
const double cos_phi_diff = dot(V_perp_N, normalize(incoming - n * cos_in));
if (cos_phi_diff >= 0.0)
C2 *= sin(alpha);
else
{
const double temp = 2.0 * beta * RcpPi;
C2 *= sin(alpha) - square(temp) * temp;
}
assert( C2 >= 0.0);
const double C3 = 0.125 * (sigma2 / (sigma2 + 0.09) * square(4.0 * alpha * beta * RcpPiSq)) * tan((alpha + beta) * 0.5);
assert( C3 >= 0.0);
value = reflectance ;
value *= static_cast<float>(C1 + (abs(cos_phi_diff) * C2 * tan(beta)) + (1 - abs(cos_phi_diff)) * C3);
value += square(reflectance) * static_cast<float>(0.17 * cos_in * (sigma2 / (sigma2 + 0.13)) *
(1 - cos_phi_diff * square(2 * beta * RcpPi)));
assert(min_value(value) >= 0.0 );
}
private:
typedef OrenNayarBRDFInputValues InputValues;
};
typedef BSDFWrapper<OrenNayarBRDFImpl> OrenNayarBRDF;
}
//
// OrenNayarBRDFFactory class implementation.
//
const char* OrenNayarBRDFFactory::get_model() const
{
return Model;
}
const char* OrenNayarBRDFFactory::get_human_readable_model() const
{
return "Oren-Nayar BRDF";
}
DictionaryArray OrenNayarBRDFFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "reflectance")
.insert("label", "Reflectance")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "reflectance_multiplier")
.insert("label", "Reflectance Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "roughness")
.insert("label", "Roughness")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.1"));
return metadata;
}
auto_release_ptr<BSDF> OrenNayarBRDFFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<BSDF>(new OrenNayarBRDF(name, params));
}
} // namespace renderer
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <ctime>
#include <functional>
#include <nix/valid/validator.hpp>
#include <nix/valid/checks.hpp>
#include <nix/valid/conditions.hpp>
#include <nix/valid/validate.hpp>
#include <nix.hpp>
#include "TestValidate.hpp"
using namespace nix;
using namespace valid;
using namespace std;
void TestValidate::setUp() {
startup_time = time(NULL);
}
void TestValidate::tearDown() {
return;
}
void TestValidate::test() {
// dummy class to test empty checks
class fooC {
public:
std::string getFoo () const { return std::string("I'm not empty!"); };
std::string getBar () const { return std::string(); };
};
std::vector<std::string> vect = {"foo", "bar"};
std::vector<std::string> vect2;
fooC foobar;
// NOTE: we can't test nix specific checks since nix & validation
// structs cannot be included together
valid::Result myResult = validator({
could(vect, &std::vector<std::string>::empty, notFalse(), {
must(vect, &std::vector<std::string>::size, notSmaller(2), "some msg") }),
must(vect, &std::vector<std::string>::size, notSmaller(2), "some msg"),
must(vect, &std::vector<std::string>::size, isSmaller(2), "some msg"),
should(vect, &std::vector<std::string>::size, notGreater(2), "some msg"),
should(vect, &std::vector<std::string>::size, isGreater(0), "some msg"),
must(vect, &std::vector<std::string>::size, notEqual<size_t>(0), "some msg"),
should(vect, &std::vector<std::string>::size, isEqual<size_t>(2), "some msg"),
must(vect2, &std::vector<std::string>::size, isFalse(), "some msg"),
must(foobar, &fooC::getFoo, notEmpty(), "some msg"),
should(foobar, &fooC::getBar, isEmpty(), "some msg") })
});
CPPUNIT_ASSERT(myResult.hasWarnings() == false);
CPPUNIT_ASSERT(myResult.hasErrors() == false);
}
<commit_msg>Fixed tiny bracket error in TestValidate<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <ctime>
#include <functional>
#include <nix/valid/validator.hpp>
#include <nix/valid/checks.hpp>
#include <nix/valid/conditions.hpp>
#include <nix/valid/validate.hpp>
#include <nix.hpp>
#include "TestValidate.hpp"
using namespace nix;
using namespace valid;
using namespace std;
void TestValidate::setUp() {
startup_time = time(NULL);
}
void TestValidate::tearDown() {
return;
}
void TestValidate::test() {
// dummy class to test empty checks
class fooC {
public:
std::string getFoo () const { return std::string("I'm not empty!"); };
std::string getBar () const { return std::string(); };
};
std::vector<std::string> vect = {"foo", "bar"};
std::vector<std::string> vect2;
fooC foobar;
// NOTE: we can't test nix specific checks since nix & validation
// structs cannot be included together
valid::Result myResult = validator({
could(vect, &std::vector<std::string>::empty, notFalse(), {
must(vect, &std::vector<std::string>::size, notSmaller(2), "some msg") }),
must(vect, &std::vector<std::string>::size, notSmaller(2), "some msg"),
must(vect, &std::vector<std::string>::size, isSmaller(2), "some msg"),
should(vect, &std::vector<std::string>::size, notGreater(2), "some msg"),
should(vect, &std::vector<std::string>::size, isGreater(0), "some msg"),
must(vect, &std::vector<std::string>::size, notEqual<size_t>(0), "some msg"),
should(vect, &std::vector<std::string>::size, isEqual<size_t>(2), "some msg"),
must(vect2, &std::vector<std::string>::size, isFalse(), "some msg"),
must(foobar, &fooC::getFoo, notEmpty(), "some msg"),
should(foobar, &fooC::getBar, isEmpty(), "some msg")
});
CPPUNIT_ASSERT(myResult.hasWarnings() == false);
CPPUNIT_ASSERT(myResult.hasErrors() == false);
}
<|endoftext|> |
<commit_before>#include <mlopen.h>
#include "test.hpp"
#include <vector>
#include <array>
#include <iterator>
#include <memory>
#include <mlopen/tensor_extra.hpp>
struct handle_fixture
{
mlopenHandle_t handle;
#if MLOPEN_BACKEND_OPENCL
cl_command_queue q;
#endif
handle_fixture()
{
mlopenCreate(&handle);
#if MLOPEN_BACKEND_OPENCL
mlopenGetStream(handle, &q);
#endif
}
~handle_fixture()
{
mlopenDestroy(handle);
}
};
struct input_tensor_fixture
{
mlopenTensorDescriptor_t inputTensor;
input_tensor_fixture()
{
STATUS(mlopenCreateTensorDescriptor(&inputTensor));
STATUS(mlopenSet4dTensorDescriptor(
inputTensor,
mlopenFloat,
100,
32,
8,
8));
}
~input_tensor_fixture()
{
mlopenDestroyTensorDescriptor(inputTensor);
}
void run()
{
int n, c, h, w;
int nStride, cStride, hStride, wStride;
mlopenDataType_t dt;
STATUS(mlopenGet4dTensorDescriptor(
inputTensor,
&dt,
&n,
&c,
&h,
&w,
&nStride,
&cStride,
&hStride,
&wStride));
EXPECT(dt == 1);
EXPECT(n == 100);
EXPECT(c == 32);
EXPECT(h == 8);
EXPECT(w == 8);
EXPECT(nStride == c * cStride);
EXPECT(cStride == h * hStride);
EXPECT(hStride == w * wStride);
EXPECT(wStride == 1);
}
};
struct conv_filter_fixture : virtual handle_fixture
{
mlopenTensorDescriptor_t convFilter;
mlopenConvolutionDescriptor_t convDesc;
static const mlopenConvolutionMode_t mode = mlopenConvolution;
conv_filter_fixture()
{
STATUS(mlopenCreateTensorDescriptor(&convFilter));
// weights
STATUS(mlopenSet4dTensorDescriptor(
convFilter,
mlopenFloat,
64, // outputs
32, // inputs
5, // kernel size
5));
STATUS(mlopenCreateConvolutionDescriptor(&convDesc));
// convolution with padding 2
STATUS(mlopenInitConvolutionDescriptor(convDesc,
mode,
0,
0,
1,
1,
1,
1));
}
~conv_filter_fixture()
{
mlopenDestroyTensorDescriptor(convFilter);
mlopenDestroyConvolutionDescriptor(convDesc);
}
void run()
{
// TODO: Update API to not require mode by pointer
mlopenConvolutionMode_t lmode = mode;
int pad_w, pad_h, u, v, upx, upy;
STATUS(mlopenGetConvolutionDescriptor(convDesc,
&lmode,
&pad_h, &pad_w, &u, &v,
&upx, &upy));
EXPECT(mode == 0);
EXPECT(pad_h == 0);
EXPECT(pad_w == 0);
EXPECT(u == 1);
EXPECT(v == 1);
EXPECT(upx == 1);
EXPECT(upy == 1);
}
};
struct output_tensor_fixture : conv_filter_fixture, input_tensor_fixture
{
mlopenTensorDescriptor_t outputTensor;
output_tensor_fixture()
{
int x, y, z, a;
STATUS(mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
STATUS(mlopenCreateTensorDescriptor(&outputTensor));
STATUS(mlopenSet4dTensorDescriptor(
outputTensor,
mlopenFloat,
x,
y,
z,
a));
}
~output_tensor_fixture()
{
mlopenDestroyTensorDescriptor(outputTensor);
}
void run()
{
int x, y, z, a;
STATUS(mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
EXPECT(x == 100);
EXPECT(y == 64);
EXPECT(z == 4);
EXPECT(a == 4);
}
};
template<bool Profile>
struct conv_forward : output_tensor_fixture
{
void run()
{
STATUS(mlopenEnableProfiling(handle, Profile));
int alpha = 1, beta = 1;
STATUS(mlopenTransformTensor(handle,
&alpha,
inputTensor,
NULL,
&beta,
convFilter,
NULL));
int value = 10;
// STATUS(mlopenSetTensor(handle, inputTensor, NULL, &value));
// STATUS(mlopenScaleTensor(handle, inputTensor, NULL, &alpha));
// Setup OpenCL buffers
int n, h, c, w;
STATUS(mlopenGet4dTensorDescriptorLengths(inputTensor, &n, &c, &h, &w));
size_t sz_in = n*c*h*w;
STATUS(mlopenGet4dTensorDescriptorLengths(convFilter, &n, &c, &h, &w));
size_t sz_wei = n*c*h*w;
STATUS(mlopenGet4dTensorDescriptorLengths(outputTensor, &n, &c, &h, &w));
size_t sz_out = n*c*h*w;
std::vector<float> in(sz_in);
std::vector<float> wei(sz_wei);
std::vector<float> out(sz_out);
for(int i = 0; i < sz_in; i++) {
in[i] = rand() * (1.0 / RAND_MAX);
}
for (int i = 0; i < sz_wei; i++) {
wei[i] = (double)(rand() * (1.0 / RAND_MAX) - 0.5) * 0.001;
}
#if MLOPEN_BACKEND_OPENCL
cl_context ctx;
clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);
cl_int status = CL_SUCCESS;
cl_mem in_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_in,NULL, &status);
cl_mem wei_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_wei,NULL, NULL);
cl_mem out_dev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz_out,NULL, NULL);
status = clEnqueueWriteBuffer(q, in_dev, CL_TRUE, 0, 4*sz_in, in.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, wei_dev, CL_TRUE, 0, 4*sz_wei, wei.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, out_dev, CL_TRUE, 0, 4*sz_out, out.data(), 0, NULL, NULL);
EXPECT(status == CL_SUCCESS);
#elif MLOPEN_BACKEND_HIP
void * in_dev;
void * wei_dev;
void * out_dev;
EXPECT(hipMalloc(&in_dev, 4*sz_in) == hipSuccess);
EXPECT(hipMalloc(&wei_dev, 4*sz_wei) == hipSuccess);
EXPECT(hipMalloc(&out_dev, 4*sz_out) == hipSuccess);
EXPECT(hipMemcpy(in_dev, in.data(), 4*sz_in, hipMemcpyDeviceToHost) == hipSuccess);
EXPECT(hipMemcpy(wei_dev, wei.data(), 4*sz_wei, hipMemcpyDeviceToHost) == hipSuccess);
EXPECT(hipMemcpy(out_dev, out.data(), 4*sz_out, hipMemcpyDeviceToHost) == hipSuccess);
#endif
int ret_algo_count;
mlopenConvAlgoPerf_t perf;
STATUS(mlopenFindConvolutionForwardAlgorithm(handle,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
outputTensor,
out_dev,
1,
&ret_algo_count,
&perf,
mlopenConvolutionFastest,
NULL,
10,
0)); // MD: Not performing exhaustiveSearch by default for now
STATUS(mlopenConvolutionForward(handle,
&alpha,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
mlopenConvolutionFwdAlgoDirect,
&beta,
outputTensor,
out_dev,
NULL,
0));
float time;
STATUS(mlopenGetKernelTime(handle, &time));
if (Profile)
{
CHECK(time > 0.0);
}
else
{
CHECK(time == 0.0);
}
}
};
int main() {
run_test<input_tensor_fixture>();
run_test<conv_filter_fixture>();
run_test<output_tensor_fixture>();
run_test<conv_forward<true>>();
run_test<conv_forward<false>>();
}
<commit_msg>Fix copy direction<commit_after>#include <mlopen.h>
#include "test.hpp"
#include <vector>
#include <array>
#include <iterator>
#include <memory>
#include <mlopen/tensor_extra.hpp>
struct handle_fixture
{
mlopenHandle_t handle;
#if MLOPEN_BACKEND_OPENCL
cl_command_queue q;
#endif
handle_fixture()
{
mlopenCreate(&handle);
#if MLOPEN_BACKEND_OPENCL
mlopenGetStream(handle, &q);
#endif
}
~handle_fixture()
{
mlopenDestroy(handle);
}
};
struct input_tensor_fixture
{
mlopenTensorDescriptor_t inputTensor;
input_tensor_fixture()
{
STATUS(mlopenCreateTensorDescriptor(&inputTensor));
STATUS(mlopenSet4dTensorDescriptor(
inputTensor,
mlopenFloat,
100,
32,
8,
8));
}
~input_tensor_fixture()
{
mlopenDestroyTensorDescriptor(inputTensor);
}
void run()
{
int n, c, h, w;
int nStride, cStride, hStride, wStride;
mlopenDataType_t dt;
STATUS(mlopenGet4dTensorDescriptor(
inputTensor,
&dt,
&n,
&c,
&h,
&w,
&nStride,
&cStride,
&hStride,
&wStride));
EXPECT(dt == 1);
EXPECT(n == 100);
EXPECT(c == 32);
EXPECT(h == 8);
EXPECT(w == 8);
EXPECT(nStride == c * cStride);
EXPECT(cStride == h * hStride);
EXPECT(hStride == w * wStride);
EXPECT(wStride == 1);
}
};
struct conv_filter_fixture : virtual handle_fixture
{
mlopenTensorDescriptor_t convFilter;
mlopenConvolutionDescriptor_t convDesc;
static const mlopenConvolutionMode_t mode = mlopenConvolution;
conv_filter_fixture()
{
STATUS(mlopenCreateTensorDescriptor(&convFilter));
// weights
STATUS(mlopenSet4dTensorDescriptor(
convFilter,
mlopenFloat,
64, // outputs
32, // inputs
5, // kernel size
5));
STATUS(mlopenCreateConvolutionDescriptor(&convDesc));
// convolution with padding 2
STATUS(mlopenInitConvolutionDescriptor(convDesc,
mode,
0,
0,
1,
1,
1,
1));
}
~conv_filter_fixture()
{
mlopenDestroyTensorDescriptor(convFilter);
mlopenDestroyConvolutionDescriptor(convDesc);
}
void run()
{
// TODO: Update API to not require mode by pointer
mlopenConvolutionMode_t lmode = mode;
int pad_w, pad_h, u, v, upx, upy;
STATUS(mlopenGetConvolutionDescriptor(convDesc,
&lmode,
&pad_h, &pad_w, &u, &v,
&upx, &upy));
EXPECT(mode == 0);
EXPECT(pad_h == 0);
EXPECT(pad_w == 0);
EXPECT(u == 1);
EXPECT(v == 1);
EXPECT(upx == 1);
EXPECT(upy == 1);
}
};
struct output_tensor_fixture : conv_filter_fixture, input_tensor_fixture
{
mlopenTensorDescriptor_t outputTensor;
output_tensor_fixture()
{
int x, y, z, a;
STATUS(mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
STATUS(mlopenCreateTensorDescriptor(&outputTensor));
STATUS(mlopenSet4dTensorDescriptor(
outputTensor,
mlopenFloat,
x,
y,
z,
a));
}
~output_tensor_fixture()
{
mlopenDestroyTensorDescriptor(outputTensor);
}
void run()
{
int x, y, z, a;
STATUS(mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
EXPECT(x == 100);
EXPECT(y == 64);
EXPECT(z == 4);
EXPECT(a == 4);
}
};
template<bool Profile>
struct conv_forward : output_tensor_fixture
{
void run()
{
STATUS(mlopenEnableProfiling(handle, Profile));
int alpha = 1, beta = 1;
STATUS(mlopenTransformTensor(handle,
&alpha,
inputTensor,
NULL,
&beta,
convFilter,
NULL));
int value = 10;
// STATUS(mlopenSetTensor(handle, inputTensor, NULL, &value));
// STATUS(mlopenScaleTensor(handle, inputTensor, NULL, &alpha));
// Setup OpenCL buffers
int n, h, c, w;
STATUS(mlopenGet4dTensorDescriptorLengths(inputTensor, &n, &c, &h, &w));
size_t sz_in = n*c*h*w;
STATUS(mlopenGet4dTensorDescriptorLengths(convFilter, &n, &c, &h, &w));
size_t sz_wei = n*c*h*w;
STATUS(mlopenGet4dTensorDescriptorLengths(outputTensor, &n, &c, &h, &w));
size_t sz_out = n*c*h*w;
std::vector<float> in(sz_in);
std::vector<float> wei(sz_wei);
std::vector<float> out(sz_out);
for(int i = 0; i < sz_in; i++) {
in[i] = rand() * (1.0 / RAND_MAX);
}
for (int i = 0; i < sz_wei; i++) {
wei[i] = (double)(rand() * (1.0 / RAND_MAX) - 0.5) * 0.001;
}
#if MLOPEN_BACKEND_OPENCL
cl_context ctx;
clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);
cl_int status = CL_SUCCESS;
cl_mem in_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_in,NULL, &status);
cl_mem wei_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_wei,NULL, NULL);
cl_mem out_dev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz_out,NULL, NULL);
status = clEnqueueWriteBuffer(q, in_dev, CL_TRUE, 0, 4*sz_in, in.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, wei_dev, CL_TRUE, 0, 4*sz_wei, wei.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, out_dev, CL_TRUE, 0, 4*sz_out, out.data(), 0, NULL, NULL);
EXPECT(status == CL_SUCCESS);
#elif MLOPEN_BACKEND_HIP
void * in_dev;
void * wei_dev;
void * out_dev;
EXPECT(hipMalloc(&in_dev, 4*sz_in) == hipSuccess);
EXPECT(hipMalloc(&wei_dev, 4*sz_wei) == hipSuccess);
EXPECT(hipMalloc(&out_dev, 4*sz_out) == hipSuccess);
EXPECT(hipMemcpy(in_dev, in.data(), 4*sz_in, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(wei_dev, wei.data(), 4*sz_wei, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(out_dev, out.data(), 4*sz_out, hipMemcpyHostToDevice) == hipSuccess);
#endif
int ret_algo_count;
mlopenConvAlgoPerf_t perf;
STATUS(mlopenFindConvolutionForwardAlgorithm(handle,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
outputTensor,
out_dev,
1,
&ret_algo_count,
&perf,
mlopenConvolutionFastest,
NULL,
10,
0)); // MD: Not performing exhaustiveSearch by default for now
STATUS(mlopenConvolutionForward(handle,
&alpha,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
mlopenConvolutionFwdAlgoDirect,
&beta,
outputTensor,
out_dev,
NULL,
0));
float time;
STATUS(mlopenGetKernelTime(handle, &time));
if (Profile)
{
CHECK(time > 0.0);
}
else
{
CHECK(time == 0.0);
}
// Potential memory leak free memory at end of function
#if MLOPEN_BACKEND_OPENCL
#elif MLOPEN_BACKEND_HIP
hipFree(in_dev);
hipFree(wei_dev);
hipFree(out_dev);
#endif
}
};
int main() {
run_test<input_tensor_fixture>();
run_test<conv_filter_fixture>();
run_test<output_tensor_fixture>();
run_test<conv_forward<true>>();
run_test<conv_forward<false>>();
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014 Srinath Ravichandran, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "curveobject.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/math/sampling/mappings.h"
#include "foundation/math/aabb.h"
#include "foundation/math/qmc.h"
#include "foundation/math/rng.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/defaulttimers.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <fstream>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// CurveObject class implementation.
//
struct CurveObject::Impl
{
RegionKit m_region_kit;
Lazy<RegionKit> m_lazy_region_kit;
vector<BezierCurve3d> m_curves;
vector<string> m_material_slots;
Impl()
: m_lazy_region_kit(&m_region_kit)
{
}
GAABB3 compute_bounds() const
{
AABB3d bbox;
bbox.invalidate();
const size_t curve_count = m_curves.size();
for (size_t i = 0; i < curve_count; ++i)
bbox.insert(m_curves[i].compute_bbox());
return bbox;
}
template <typename RNG>
static Vector2d rand_vector2d(RNG& rng)
{
Vector2d v;
v[0] = rand_double2(rng);
v[1] = rand_double2(rng);
return v;
}
void create_hair_ball(const ParamArray& params)
{
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_width = params.get_optional<double>("width", 0.002);
Vector3d points[ControlPointCount];
MersenneTwister rng;
m_curves.reserve(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < ControlPointCount; ++p)
{
// http://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability
const double r = pow(1.0 - rand_double2(rng), 1.0 / 3);
const Vector3d d = sample_sphere_uniform(rand_vector2d(rng));
points[p] = r * d;
}
const BezierCurve3d curve(&points[0], curve_width);
m_curves.push_back(curve);
}
}
void create_furry_ball(const ParamArray& params)
{
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_length = params.get_optional<double>("length", 0.1);
const double base_width = params.get_optional<double>("base_width", 0.001);
const double tip_width = params.get_optional<double>("tip_width", 0.0001);
const double length_fuzziness = params.get_optional<double>("length_fuzziness", 0.3);
const double curliness = params.get_optional<double>("curliness", 0.5);
Vector3d points[ControlPointCount];
double widths[ControlPointCount];
MersenneTwister rng;
m_curves.reserve(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
static const size_t Bases[] = { 2 };
const Vector2d s = hammersley_sequence<double, 2>(Bases, c, curve_count);
const Vector3d d = sample_sphere_uniform(s);
points[0] = d;
widths[0] = base_width;
const double f = rand_double1(rng, -length_fuzziness, +length_fuzziness);
const double length = curve_length * (1.0 + f);
for (size_t p = 1; p < ControlPointCount; ++p)
{
const double r = static_cast<double>(p) / (ControlPointCount - 1);
const Vector3d f = curliness * sample_sphere_uniform(rand_vector2d(rng));
points[p] = points[0] + length * (r * d + f);
widths[p] = lerp(base_width, tip_width, r);
}
const BezierCurve3d curve(&points[0], &widths[0]);
m_curves.push_back(curve);
}
}
void load_curve_file(const char* filepath)
{
const double CurveWidth = 0.009;
ifstream input;
input.open(filepath);
if (input.good())
{
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
// Read the number of curves.
size_t curve_count;
input >> curve_count;
// Read the number of control points per curve.
size_t control_point_count;
input >> control_point_count;
vector<Vector3d> points(control_point_count);
m_curves.reserve(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < control_point_count; ++p)
{
Vector3d point;
input >> point.x >> point.y >> point.z;
points[p] = point;
}
const BezierCurve3d curve(&points[0], CurveWidth);
m_curves.push_back(curve);
}
stopwatch.measure();
RENDERER_LOG_INFO(
"loaded curve file %s (%s curves) in %s.",
filepath,
pretty_uint(curve_count).c_str(),
pretty_time(stopwatch.get_seconds()).c_str());
input.close();
}
else
{
RENDERER_LOG_ERROR("failed to load curve file %s.", filepath);
}
}
};
CurveObject::CurveObject(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
: Object(name, params)
, impl(new Impl())
{
const string filepath = params.get<string>("filepath");
if (filepath == "builtin:hairball")
impl->create_hair_ball(params);
else if (filepath == "builtin:furryball")
impl->create_furry_ball(params);
else
{
impl->load_curve_file(
search_paths.qualify(filepath).c_str());
}
}
CurveObject::~CurveObject()
{
delete impl;
}
void CurveObject::release()
{
delete this;
}
const char* CurveObject::get_model() const
{
return CurveObjectFactory::get_model();
}
GAABB3 CurveObject::compute_local_bbox() const
{
return impl->compute_bounds();
}
Lazy<RegionKit>& CurveObject::get_region_kit()
{
return impl->m_lazy_region_kit;
}
size_t CurveObject::get_material_slot_count() const
{
return impl->m_material_slots.size();
}
const char* CurveObject::get_material_slot(const size_t index) const
{
return impl->m_material_slots[index].c_str();
}
size_t CurveObject::get_curve_count() const
{
return impl->m_curves.size();
}
const BezierCurve3d& CurveObject::get_curve(const size_t index) const
{
assert(index < impl->m_curves.size());
return impl->m_curves[index];
}
//
// CurveObjectFactory class implementation.
//
const char* CurveObjectFactory::get_model()
{
return "curve_object";
}
auto_release_ptr<CurveObject> CurveObjectFactory::create(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
{
return
auto_release_ptr<CurveObject>(
new CurveObject(search_paths, name, params));
}
} // namespace renderer
<commit_msg>support per-control point width in temporary curve file format.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014 Srinath Ravichandran, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "curveobject.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/math/sampling/mappings.h"
#include "foundation/math/aabb.h"
#include "foundation/math/qmc.h"
#include "foundation/math/rng.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/defaulttimers.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <fstream>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// CurveObject class implementation.
//
struct CurveObject::Impl
{
RegionKit m_region_kit;
Lazy<RegionKit> m_lazy_region_kit;
vector<BezierCurve3d> m_curves;
vector<string> m_material_slots;
Impl()
: m_lazy_region_kit(&m_region_kit)
{
}
GAABB3 compute_bounds() const
{
AABB3d bbox;
bbox.invalidate();
const size_t curve_count = m_curves.size();
for (size_t i = 0; i < curve_count; ++i)
bbox.insert(m_curves[i].compute_bbox());
return bbox;
}
template <typename RNG>
static Vector2d rand_vector2d(RNG& rng)
{
Vector2d v;
v[0] = rand_double2(rng);
v[1] = rand_double2(rng);
return v;
}
void create_hair_ball(const ParamArray& params)
{
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_width = params.get_optional<double>("width", 0.002);
Vector3d points[ControlPointCount];
MersenneTwister rng;
m_curves.reserve(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < ControlPointCount; ++p)
{
// http://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability
const double r = pow(1.0 - rand_double2(rng), 1.0 / 3);
const Vector3d d = sample_sphere_uniform(rand_vector2d(rng));
points[p] = r * d;
}
const BezierCurve3d curve(&points[0], curve_width);
m_curves.push_back(curve);
}
}
void create_furry_ball(const ParamArray& params)
{
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_length = params.get_optional<double>("length", 0.1);
const double base_width = params.get_optional<double>("base_width", 0.001);
const double tip_width = params.get_optional<double>("tip_width", 0.0001);
const double length_fuzziness = params.get_optional<double>("length_fuzziness", 0.3);
const double curliness = params.get_optional<double>("curliness", 0.5);
Vector3d points[ControlPointCount];
double widths[ControlPointCount];
MersenneTwister rng;
m_curves.reserve(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
static const size_t Bases[] = { 2 };
const Vector2d s = hammersley_sequence<double, 2>(Bases, c, curve_count);
const Vector3d d = sample_sphere_uniform(s);
points[0] = d;
widths[0] = base_width;
const double f = rand_double1(rng, -length_fuzziness, +length_fuzziness);
const double length = curve_length * (1.0 + f);
for (size_t p = 1; p < ControlPointCount; ++p)
{
const double r = static_cast<double>(p) / (ControlPointCount - 1);
const Vector3d f = curliness * sample_sphere_uniform(rand_vector2d(rng));
points[p] = points[0] + length * (r * d + f);
widths[p] = lerp(base_width, tip_width, r);
}
const BezierCurve3d curve(&points[0], &widths[0]);
m_curves.push_back(curve);
}
}
void load_curve_file(const char* filepath)
{
ifstream input;
input.open(filepath);
if (input.good())
{
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
// Read the number of curves.
size_t curve_count;
input >> curve_count;
// Read the number of control points per curve.
size_t control_point_count;
input >> control_point_count;
if (control_point_count != 4)
{
RENDERER_LOG_ERROR(
"while loading curve file %s: only curves with 4 control points are currently supported.",
filepath);
return;
}
vector<Vector3d> points(control_point_count);
vector<double> widths(control_point_count);
m_curves.reserve(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < control_point_count; ++p)
{
input >> points[p].x >> points[p].y >> points[p].z;
input >> widths[p];
}
const BezierCurve3d curve(&points[0], &widths[0]);
m_curves.push_back(curve);
}
input.close();
stopwatch.measure();
RENDERER_LOG_INFO(
"loaded curve file %s (%s curves) in %s.",
filepath,
pretty_uint(curve_count).c_str(),
pretty_time(stopwatch.get_seconds()).c_str());
}
else
{
RENDERER_LOG_ERROR("failed to load curve file %s.", filepath);
}
}
};
CurveObject::CurveObject(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
: Object(name, params)
, impl(new Impl())
{
const string filepath = params.get<string>("filepath");
if (filepath == "builtin:hairball")
impl->create_hair_ball(params);
else if (filepath == "builtin:furryball")
impl->create_furry_ball(params);
else
{
impl->load_curve_file(
search_paths.qualify(filepath).c_str());
}
}
CurveObject::~CurveObject()
{
delete impl;
}
void CurveObject::release()
{
delete this;
}
const char* CurveObject::get_model() const
{
return CurveObjectFactory::get_model();
}
GAABB3 CurveObject::compute_local_bbox() const
{
return impl->compute_bounds();
}
Lazy<RegionKit>& CurveObject::get_region_kit()
{
return impl->m_lazy_region_kit;
}
size_t CurveObject::get_material_slot_count() const
{
return impl->m_material_slots.size();
}
const char* CurveObject::get_material_slot(const size_t index) const
{
return impl->m_material_slots[index].c_str();
}
size_t CurveObject::get_curve_count() const
{
return impl->m_curves.size();
}
const BezierCurve3d& CurveObject::get_curve(const size_t index) const
{
assert(index < impl->m_curves.size());
return impl->m_curves[index];
}
//
// CurveObjectFactory class implementation.
//
const char* CurveObjectFactory::get_model()
{
return "curve_object";
}
auto_release_ptr<CurveObject> CurveObjectFactory::create(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
{
return
auto_release_ptr<CurveObject>(
new CurveObject(search_paths, name, params));
}
} // namespace renderer
<|endoftext|> |
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_posh/popo/client.hpp"
#include "iceoryx_posh/popo/listener.hpp"
#include "iceoryx_posh/popo/server.hpp"
#include "iceoryx_posh/popo/subscriber.hpp"
#include "iceoryx_posh/popo/untyped_client.hpp"
#include "iceoryx_posh/popo/untyped_server.hpp"
#include "iceoryx_posh/popo/untyped_subscriber.hpp"
#include "iceoryx_posh/testing/mocks/posh_runtime_mock.hpp"
#include "test.hpp"
namespace
{
using namespace ::testing;
using namespace ::iox::popo;
using namespace ::iox::cxx;
using namespace ::iox::capro;
using namespace ::iox::mepoo;
constexpr const char RUNTIME_NAME[] = "torben_dallas";
constexpr const char SERVICE[] = "respect_to_the_man_in_the_icecream_van";
constexpr const char INSTANCE[] = "Lakierski materialski";
constexpr const char EVENT[] = "boom boom boomerang";
/// Those tests verify that the destructor of the attachables is correct. When we
/// use inheritance it is possible that the trigger is a member of the base class
/// and destroyed in the base class constructor as well.
/// But the listener and waitset require the child class for cleanup. If the child
/// class destructor does not call reset on all the triggers the base class will
/// and the listener and waitset will call a method on the original class which is
/// already deleted. This causes undefined behavior which the sanitizer will catch.
///
/// The following tests should be run for all classes which can be attached to a
/// listener or a waitset to ensure that trigger.reset() is called in the child destructor
/// when we work with inheritance.
///
/// When no inheritance is used we shouldn't encounter any problems.
///
/// It suffices to call all tests on the listener since the listener and the waitset
/// are using the same trigger concept
class ListenerWaitsetAttachments_test : public Test
{
public:
void SetUp()
{
EXPECT_CALL(*this->runtimeMock, getMiddlewareConditionVariable())
.WillOnce(Return(&this->conditionVariableData));
listener.emplace();
}
template <typename T>
static void genericTriggerCallback(T* const)
{
}
std::unique_ptr<PoshRuntimeMock> runtimeMock = PoshRuntimeMock::create(RUNTIME_NAME);
ConditionVariableData conditionVariableData{RUNTIME_NAME};
optional<Listener> listener;
MemoryManager memoryManager;
};
TEST_F(ListenerWaitsetAttachments_test, SubscriberAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "f1d163e0-4479-47b4-b4e8-01b0ee6a71b0");
SubscriberPortData subscriberData({SERVICE, INSTANCE, EVENT},
RUNTIME_NAME,
VariantQueueTypes::SoFi_MultiProducerSingleConsumer,
SubscriberOptions());
EXPECT_CALL(*this->runtimeMock, getMiddlewareSubscriber(_, _, _)).WillOnce(Return(&subscriberData));
optional<Subscriber<int>> subscriber;
subscriber.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*subscriber,
SubscriberEvent::DATA_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<Subscriber<int>>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
subscriber.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, UntypedSubscriberAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "a78a7016-46b6-4223-b7b1-e30344bb208f");
SubscriberPortData subscriberData({SERVICE, INSTANCE, EVENT},
RUNTIME_NAME,
VariantQueueTypes::SoFi_MultiProducerSingleConsumer,
SubscriberOptions());
EXPECT_CALL(*this->runtimeMock, getMiddlewareSubscriber(_, _, _)).WillOnce(Return(&subscriberData));
optional<UntypedSubscriber> subscriber;
subscriber.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*subscriber,
SubscriberEvent::DATA_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<UntypedSubscriber>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
subscriber.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, ClientAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "e21d98b9-9d24-4c85-90b9-0e7acd24a242");
ClientPortData clientData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ClientOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareClient(_, _, _)).WillOnce(Return(&clientData));
optional<Client<int, int>> client;
client.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*client,
ClientEvent::RESPONSE_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<Client<int, int>>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
client.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, UntypedClientAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "07934dd2-93aa-4aab-a216-eb86e842088b");
ClientPortData clientData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ClientOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareClient(_, _, _)).WillOnce(Return(&clientData));
optional<UntypedClient> client;
client.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*client,
ClientEvent::RESPONSE_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<UntypedClient>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
client.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, ServerAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "306d7ef9-1fb1-4ce8-8b58-e5a7cb5fff69");
ServerPortData serverData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ServerOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareServer(_, _, _)).WillOnce(Return(&serverData));
optional<Server<int, int>> server;
server.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*server,
ServerEvent::REQUEST_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<Server<int, int>>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
server.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, UntypedServerAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "3d074e8f-eab6-475d-a884-de8b4d2596ea");
ServerPortData serverData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ServerOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareServer(_, _, _)).WillOnce(Return(&serverData));
optional<UntypedServer> server;
server.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*server,
ServerEvent::REQUEST_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<UntypedServer>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
server.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
} // namespace
<commit_msg>iox-#1173 Copyright year adjusted<commit_after>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_posh/popo/client.hpp"
#include "iceoryx_posh/popo/listener.hpp"
#include "iceoryx_posh/popo/server.hpp"
#include "iceoryx_posh/popo/subscriber.hpp"
#include "iceoryx_posh/popo/untyped_client.hpp"
#include "iceoryx_posh/popo/untyped_server.hpp"
#include "iceoryx_posh/popo/untyped_subscriber.hpp"
#include "iceoryx_posh/testing/mocks/posh_runtime_mock.hpp"
#include "test.hpp"
namespace
{
using namespace ::testing;
using namespace ::iox::popo;
using namespace ::iox::cxx;
using namespace ::iox::capro;
using namespace ::iox::mepoo;
constexpr const char RUNTIME_NAME[] = "torben_dallas";
constexpr const char SERVICE[] = "respect_to_the_man_in_the_icecream_van";
constexpr const char INSTANCE[] = "Lakierski materialski";
constexpr const char EVENT[] = "boom boom boomerang";
/// Those tests verify that the destructor of the attachables is correct. When we
/// use inheritance it is possible that the trigger is a member of the base class
/// and destroyed in the base class constructor as well.
/// But the listener and waitset require the child class for cleanup. If the child
/// class destructor does not call reset on all the triggers the base class will
/// and the listener and waitset will call a method on the original class which is
/// already deleted. This causes undefined behavior which the sanitizer will catch.
///
/// The following tests should be run for all classes which can be attached to a
/// listener or a waitset to ensure that trigger.reset() is called in the child destructor
/// when we work with inheritance.
///
/// When no inheritance is used we shouldn't encounter any problems.
///
/// It suffices to call all tests on the listener since the listener and the waitset
/// are using the same trigger concept
class ListenerWaitsetAttachments_test : public Test
{
public:
void SetUp()
{
EXPECT_CALL(*this->runtimeMock, getMiddlewareConditionVariable())
.WillOnce(Return(&this->conditionVariableData));
listener.emplace();
}
template <typename T>
static void genericTriggerCallback(T* const)
{
}
std::unique_ptr<PoshRuntimeMock> runtimeMock = PoshRuntimeMock::create(RUNTIME_NAME);
ConditionVariableData conditionVariableData{RUNTIME_NAME};
optional<Listener> listener;
MemoryManager memoryManager;
};
TEST_F(ListenerWaitsetAttachments_test, SubscriberAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "f1d163e0-4479-47b4-b4e8-01b0ee6a71b0");
SubscriberPortData subscriberData({SERVICE, INSTANCE, EVENT},
RUNTIME_NAME,
VariantQueueTypes::SoFi_MultiProducerSingleConsumer,
SubscriberOptions());
EXPECT_CALL(*this->runtimeMock, getMiddlewareSubscriber(_, _, _)).WillOnce(Return(&subscriberData));
optional<Subscriber<int>> subscriber;
subscriber.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*subscriber,
SubscriberEvent::DATA_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<Subscriber<int>>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
subscriber.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, UntypedSubscriberAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "a78a7016-46b6-4223-b7b1-e30344bb208f");
SubscriberPortData subscriberData({SERVICE, INSTANCE, EVENT},
RUNTIME_NAME,
VariantQueueTypes::SoFi_MultiProducerSingleConsumer,
SubscriberOptions());
EXPECT_CALL(*this->runtimeMock, getMiddlewareSubscriber(_, _, _)).WillOnce(Return(&subscriberData));
optional<UntypedSubscriber> subscriber;
subscriber.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*subscriber,
SubscriberEvent::DATA_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<UntypedSubscriber>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
subscriber.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, ClientAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "e21d98b9-9d24-4c85-90b9-0e7acd24a242");
ClientPortData clientData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ClientOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareClient(_, _, _)).WillOnce(Return(&clientData));
optional<Client<int, int>> client;
client.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*client,
ClientEvent::RESPONSE_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<Client<int, int>>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
client.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, UntypedClientAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "07934dd2-93aa-4aab-a216-eb86e842088b");
ClientPortData clientData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ClientOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareClient(_, _, _)).WillOnce(Return(&clientData));
optional<UntypedClient> client;
client.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*client,
ClientEvent::RESPONSE_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<UntypedClient>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
client.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, ServerAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "306d7ef9-1fb1-4ce8-8b58-e5a7cb5fff69");
ServerPortData serverData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ServerOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareServer(_, _, _)).WillOnce(Return(&serverData));
optional<Server<int, int>> server;
server.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*server,
ServerEvent::REQUEST_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<Server<int, int>>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
server.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
TEST_F(ListenerWaitsetAttachments_test, UntypedServerAttachesToListener)
{
::testing::Test::RecordProperty("TEST_ID", "3d074e8f-eab6-475d-a884-de8b4d2596ea");
ServerPortData serverData({SERVICE, INSTANCE, EVENT}, RUNTIME_NAME, ServerOptions(), &memoryManager);
EXPECT_CALL(*this->runtimeMock, getMiddlewareServer(_, _, _)).WillOnce(Return(&serverData));
optional<UntypedServer> server;
server.emplace(ServiceDescription(SERVICE, INSTANCE, EVENT));
ASSERT_FALSE(listener
->attachEvent(*server,
ServerEvent::REQUEST_RECEIVED,
createNotificationCallback(
ListenerWaitsetAttachments_test::genericTriggerCallback<UntypedServer>))
.has_error());
EXPECT_THAT(listener->size(), Eq(1));
server.reset();
EXPECT_THAT(listener->size(), Eq(0));
}
} // namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright 2016 Realm 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 "test_all.hpp"
int main(int argc, char* argv[])
{
return test_all(argc, argv);
}
<commit_msg>Make realm-tests switch to test directory upon start<commit_after>/*************************************************************************
*
* Copyright 2016 Realm 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 "test_all.hpp"
#ifdef _MSC_VER
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#else
#include <unistd.h>
#include <libgen.h>
#endif
int main(int argc, char* argv[])
{
#ifdef _MSC_VER
char path[MAX_PATH];
if (GetModuleFileNameA(NULL, path, sizeof(path)) == 0) {
fprintf(stderr, "Failed to retrieve path to exectuable.\n");
return 1;
}
PathRemoveFileSpecA(path);
SetCurrentDirectoryA(path);
#else
char executable[PATH_MAX];
realpath(argv[0], executable);
const char* directory = dirname(executable);
chdir(directory);
#endif
return test_all(argc, argv);
}
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_METAINFO_HPP
#define VIENNAGRID_METAINFO_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
namespace viennagrid
{
namespace metainfo
{
struct random_access_tag {};
struct associative_access_tag {};
namespace result_of
{
template<typename container_type>
struct associative_container_value_type
{
typedef typename container_type::value_type type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_value_type< std::map<key_type, value_type, compare, allocator> >
{
typedef value_type type;
};
template<typename container_type>
struct associative_container_access_tag
{
typedef random_access_tag type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_access_tag< std::map<key_type, value_type, compare, allocator> >
{
typedef associative_access_tag type;
};
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, random_access_tag )
{
if (container.size() >= element.id().get() )
container.resize( element.id().get()+1 );
container[ element.id().get() ] = info;
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, associative_access_tag )
{
container.insert(
std::make_pair( element.id(), info )
);
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info )
{
set(container, element, info, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
}
}
namespace viennagrid
{
namespace result_of
{
template<typename container_collection_type, typename element_type, typename metainfo_type>
struct info_container;
template<typename container_typemap, typename element_type, typename metainfo_type>
struct info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type >
{
typedef typename viennagrid::storage::result_of::container_of< viennagrid::storage::collection_t<container_typemap>, viennameta::static_pair<element_type, metainfo_type> >::type type;
};
}
template< typename element_type, typename metainfo_type, typename container_typemap >
typename result_of::info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template< typename element_type, typename metainfo_type, typename container_typemap >
const typename result_of::info_container<viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( const viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
void set(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element,
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & meta_info )
{
metainfo::set( get_info<element_type, metainfo_type>(metainfo_collection), element, meta_info );
}
namespace metainfo
{
template<typename element_type, typename cur_typemap>
struct for_each_element_helper;
template<typename element_type, typename cur_element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
cur_element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
functor( get_info<element_type, cur_metainfo_type>(collection) );
//get_info<element_type, cur_metainfo_type>(collection).resize( size );
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type>
struct for_each_element_helper<
element_type,
viennameta::null_type
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{}
};
class resize_functor
{
public:
resize_functor(std::size_t size_) : size(size_) {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize(size);
}
private:
std::size_t size;
};
template<typename element_type, typename metainfo_container_typemap>
void resize_container( storage::collection_t<metainfo_container_typemap> & collection, std::size_t size )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, resize_functor(size) );
}
class increment_size_functor
{
public:
increment_size_functor() {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize( container.size()+1 );
}
};
template<typename element_type, typename metainfo_container_typemap>
void increment_size( storage::collection_t<metainfo_container_typemap> & collection )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, increment_size_functor() );
}
}
namespace result_of
{
template<typename pair_type, typename container_config, typename topologic_domain_config>
struct metainfo_container;
template<typename element_type, typename metainfo_type, typename container_config, typename topologic_domain_config>
struct metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config >
{
typedef typename viennameta::typemap::result_of::find<container_config, viennameta::static_pair<element_type, metainfo_type> >::type search_result;
typedef typename viennameta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container;
typedef typename viennameta::_if<
!viennameta::_equal<search_result, viennameta::not_found>::value,
search_result,
default_container
>::type container_tag_pair;
//typedef typename viennagrid::storage::result_of::container_from_tag<value_type, typename container_tag_pair::second>::type type;
typedef typename viennagrid::storage::result_of::container<metainfo_type, typename container_tag_pair::second>::type type;
};
template<typename element_list, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap;
template<typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::null_type, container_config, topologic_domain_config>
{
typedef viennameta::null_type type;
};
template<typename element_tag, typename metainfo_type, typename tail, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::typelist_t< viennameta::static_pair<element_tag, metainfo_type>, tail>, container_config, topologic_domain_config>
{
typedef typename viennagrid::result_of::element<topologic_domain_config, element_tag>::type element_type;
typedef viennameta::typelist_t<
typename viennameta::static_pair<
viennameta::static_pair<element_type, metainfo_type>,
typename metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config>::type
>,
typename metainfo_container_typemap<tail, container_config, topologic_domain_config>::type
> type;
};
}
}
#endif
<commit_msg>added const version of look_up<commit_after>#ifndef VIENNAGRID_METAINFO_HPP
#define VIENNAGRID_METAINFO_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
namespace viennagrid
{
namespace metainfo
{
struct random_access_tag {};
struct associative_access_tag {};
namespace result_of
{
template<typename container_type>
struct associative_container_value_type
{
typedef typename container_type::value_type type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_value_type< std::map<key_type, value_type, compare, allocator> >
{
typedef value_type type;
};
template<typename container_type>
struct associative_container_access_tag
{
typedef random_access_tag type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_access_tag< std::map<key_type, value_type, compare, allocator> >
{
typedef associative_access_tag type;
};
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, random_access_tag )
{
if (container.size() >= element.id().get() )
container.resize( element.id().get()+1 );
container[ element.id().get() ] = info;
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, associative_access_tag )
{
container.insert(
std::make_pair( element.id(), info )
);
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info )
{
set(container, element, info, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
}
}
namespace viennagrid
{
namespace result_of
{
template<typename container_collection_type, typename element_type, typename metainfo_type>
struct info_container;
template<typename container_typemap, typename element_type, typename metainfo_type>
struct info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type >
{
typedef typename viennagrid::storage::result_of::container_of< viennagrid::storage::collection_t<container_typemap>, viennameta::static_pair<element_type, metainfo_type> >::type type;
};
}
template< typename element_type, typename metainfo_type, typename container_typemap >
typename result_of::info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template< typename element_type, typename metainfo_type, typename container_typemap >
const typename result_of::info_container<viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( const viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
const viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
void set(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element,
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & meta_info )
{
metainfo::set( get_info<element_type, metainfo_type>(metainfo_collection), element, meta_info );
}
namespace metainfo
{
template<typename element_type, typename cur_typemap>
struct for_each_element_helper;
template<typename element_type, typename cur_element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
cur_element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
functor( get_info<element_type, cur_metainfo_type>(collection) );
//get_info<element_type, cur_metainfo_type>(collection).resize( size );
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type>
struct for_each_element_helper<
element_type,
viennameta::null_type
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{}
};
class resize_functor
{
public:
resize_functor(std::size_t size_) : size(size_) {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize(size);
}
private:
std::size_t size;
};
template<typename element_type, typename metainfo_container_typemap>
void resize_container( storage::collection_t<metainfo_container_typemap> & collection, std::size_t size )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, resize_functor(size) );
}
class increment_size_functor
{
public:
increment_size_functor() {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize( container.size()+1 );
}
};
template<typename element_type, typename metainfo_container_typemap>
void increment_size( storage::collection_t<metainfo_container_typemap> & collection )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, increment_size_functor() );
}
}
namespace result_of
{
template<typename pair_type, typename container_config, typename topologic_domain_config>
struct metainfo_container;
template<typename element_type, typename metainfo_type, typename container_config, typename topologic_domain_config>
struct metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config >
{
typedef typename viennameta::typemap::result_of::find<container_config, viennameta::static_pair<element_type, metainfo_type> >::type search_result;
typedef typename viennameta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container;
typedef typename viennameta::_if<
!viennameta::_equal<search_result, viennameta::not_found>::value,
search_result,
default_container
>::type container_tag_pair;
//typedef typename viennagrid::storage::result_of::container_from_tag<value_type, typename container_tag_pair::second>::type type;
typedef typename viennagrid::storage::result_of::container<metainfo_type, typename container_tag_pair::second>::type type;
};
template<typename element_list, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap;
template<typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::null_type, container_config, topologic_domain_config>
{
typedef viennameta::null_type type;
};
template<typename element_tag, typename metainfo_type, typename tail, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::typelist_t< viennameta::static_pair<element_tag, metainfo_type>, tail>, container_config, topologic_domain_config>
{
typedef typename viennagrid::result_of::element<topologic_domain_config, element_tag>::type element_type;
typedef viennameta::typelist_t<
typename viennameta::static_pair<
viennameta::static_pair<element_type, metainfo_type>,
typename metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config>::type
>,
typename metainfo_container_typemap<tail, container_config, topologic_domain_config>::type
> type;
};
}
}
#endif
<|endoftext|> |
<commit_before>/**
* \file RLSFilter.cpp
*/
#include "RLSFilter.h"
#include <cstdint>
#include <cstring>
#include <stdexcept>
namespace ATK
{
template<typename DataType_>
RLSFilter<DataType_>::RLSFilter(int64_t size)
:Parent(1, 1), global_size(size), P(PType::Identity(size, size)), w(wType::Zero(size, 1)), memory(.99), learning(false)
{
input_delay = size;
}
template<typename DataType_>
RLSFilter<DataType_>::~RLSFilter()
{
}
template<typename DataType_>
void RLSFilter<DataType_>::set_size(int64_t size)
{
if(size < 0)
{
throw std::out_of_range("Size must be positive");
}
P = PType::Identity(size, size) / size;
w = wType(size, 1);
input_delay = size+1;
this->global_size = size;
}
template<typename DataType_>
int64_t RLSFilter<DataType_>::get_size() const
{
return global_size;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_memory(DataType_ memory)
{
if(memory > 1)
{
throw std::out_of_range("Memory must be less than 1");
}
if(memory <= 0)
{
throw std::out_of_range("Memory must be strictly positive");
}
this->memory = memory;
}
template<typename DataType_>
DataType_ RLSFilter<DataType_>::get_memory() const
{
return memory;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_learning(bool learning)
{
this->learning = learning;
}
template<typename DataType_>
bool RLSFilter<DataType_>::get_learning() const
{
return learning;
}
template<typename DataType_>
void RLSFilter<DataType_>::process_impl(int64_t size)
{
const DataType* ATK_RESTRICT input = converted_inputs[0];
DataType* ATK_RESTRICT output = outputs[0];
for(int64_t i = 0; i < size; ++i)
{
xType x(input - global_size + i, global_size, 1);
// compute next sample
output[i] = w.transpose() * x.reverse();
if(learning)
{
//update w and P
learn(x, input[i], output[i]);
}
}
}
template<typename DataType_>
void RLSFilter<DataType_>::learn(const xType& x, DataType_ target, DataType_ actual)
{
auto alpha = target - actual;
auto xreverse = x.reverse();
wType g = (P * xreverse) / (memory + xreverse.transpose() * P * xreverse);
PType pupdate = (g * (xreverse.transpose() * P));
P = (P - (pupdate+pupdate.transpose())/2) / memory;
w = w + alpha * g;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_P(const Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic>& P)
{
assert(P.rows() == P.cols());
assert(P.rows() == size);
this->P = P;
}
template<typename DataType_>
Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic> RLSFilter<DataType_>::get_P() const
{
return P;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_w(const Eigen::Matrix<DataType_, Eigen::Dynamic, 1>& w)
{
assert(w.rows() == size);
this->w = w;
}
template<typename DataType_>
Eigen::Matrix<DataType_, Eigen::Dynamic, 1> RLSFilter<DataType_>::get_w() const
{
return w;
}
template class RLSFilter<float>;
template class RLSFilter<double>;
}
<commit_msg>Fixed init to match size reinit<commit_after>/**
* \file RLSFilter.cpp
*/
#include "RLSFilter.h"
#include <cstdint>
#include <cstring>
#include <stdexcept>
namespace ATK
{
template<typename DataType_>
RLSFilter<DataType_>::RLSFilter(int64_t size)
:Parent(1, 1), global_size(size), P(PType::Identity(size, size)/size), w(wType::Zero(size, 1)), memory(.99), learning(false)
{
input_delay = size;
}
template<typename DataType_>
RLSFilter<DataType_>::~RLSFilter()
{
}
template<typename DataType_>
void RLSFilter<DataType_>::set_size(int64_t size)
{
if(size < 0)
{
throw std::out_of_range("Size must be positive");
}
P = PType::Identity(size, size) / size;
w = wType(size, 1);
input_delay = size+1;
this->global_size = size;
}
template<typename DataType_>
int64_t RLSFilter<DataType_>::get_size() const
{
return global_size;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_memory(DataType_ memory)
{
if(memory > 1)
{
throw std::out_of_range("Memory must be less than 1");
}
if(memory <= 0)
{
throw std::out_of_range("Memory must be strictly positive");
}
this->memory = memory;
}
template<typename DataType_>
DataType_ RLSFilter<DataType_>::get_memory() const
{
return memory;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_learning(bool learning)
{
this->learning = learning;
}
template<typename DataType_>
bool RLSFilter<DataType_>::get_learning() const
{
return learning;
}
template<typename DataType_>
void RLSFilter<DataType_>::process_impl(int64_t size)
{
const DataType* ATK_RESTRICT input = converted_inputs[0];
DataType* ATK_RESTRICT output = outputs[0];
for(int64_t i = 0; i < size; ++i)
{
xType x(input - global_size + i, global_size, 1);
// compute next sample
output[i] = w.transpose() * x.reverse();
if(learning)
{
//update w and P
learn(x, input[i], output[i]);
}
}
}
template<typename DataType_>
void RLSFilter<DataType_>::learn(const xType& x, DataType_ target, DataType_ actual)
{
auto alpha = target - actual;
auto xreverse = x.reverse();
wType g = (P * xreverse) / (memory + xreverse.transpose() * P * xreverse);
PType pupdate = (g * (xreverse.transpose() * P));
P = (P - (pupdate+pupdate.transpose())/2) / memory;
w = w + alpha * g;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_P(const Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic>& P)
{
assert(P.rows() == P.cols());
assert(P.rows() == size);
this->P = P;
}
template<typename DataType_>
Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic> RLSFilter<DataType_>::get_P() const
{
return P;
}
template<typename DataType_>
void RLSFilter<DataType_>::set_w(const Eigen::Matrix<DataType_, Eigen::Dynamic, 1>& w)
{
assert(w.rows() == size);
this->w = w;
}
template<typename DataType_>
Eigen::Matrix<DataType_, Eigen::Dynamic, 1> RLSFilter<DataType_>::get_w() const
{
return w;
}
template class RLSFilter<float>;
template class RLSFilter<double>;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Monteverdi
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#include "mvdI18nMainWindow.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbSystem.h"
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdBackgroundTask.h"
#include "mvdImageImporter.h"
#include "mvdOverviewBuilder.h"
#include "mvdVectorImageModel.h"
#include "mvdAboutDialog.h"
#include "mvdI18nApplication.h"
#include "mvdImportImagesDialog.h"
#include "mvdTaskProgressDialog.h"
namespace mvd
{
/*
TRANSLATOR mvd::I18nMainWindow
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
I18nMainWindow
::I18nMainWindow( QWidget* p, Qt::WindowFlags flags ) :
QMainWindow( p, flags )
{
}
/*****************************************************************************/
I18nMainWindow
::~I18nMainWindow()
{
}
/*****************************************************************************/
void
I18nMainWindow
::Initialize()
{
/*
// Default setup.
setObjectName( "mvd::I18nMainWindow" );
setWindowTitle( PROJECT_NAME );
*/
virtual_SetupUI();
// Connect Appllication and MainWindow when selected model is about
// to change.
QObject::connect(
I18nApplication::Instance(),
SIGNAL( AboutToChangeModel( const AbstractModel* ) ),
this,
SLOT( OnAboutToChangeModel( const AbstractModel* ) )
);
// Connect Application and MainWindow when selected model has been
// changed.
QObject::connect(
I18nApplication::Instance(),
SIGNAL( ModelChanged( AbstractModel* ) ),
this,
SLOT( OnModelChanged( AbstractModel* ) )
);
virtual_ConnectUI();
virtual_InitializeUI();
}
/*****************************************************************************/
QDockWidget*
I18nMainWindow
::AddWidgetToDock( QWidget* widget,
const QString& dockName,
const QString& dockTitle,
Qt::DockWidgetArea dockArea,
DockLayoutFlags flags )
{
// New dock.
QDockWidget* dockWidget = new QDockWidget( dockTitle, this );
// You can use findChild( dockName ) to get dock-widget.
dockWidget->setObjectName( dockName );
dockWidget->setWidget( widget );
// Features.
dockWidget->setFloating( flags.testFlag( DOCK_LAYOUT_FLOATING ) );
dockWidget->setFeatures(
QDockWidget::DockWidgetMovable |
QDockWidget::DockWidgetFloatable |
QDockWidget::DockWidgetClosable
);
// dockWidget->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
// dockWidget->adjustSize();
// Add dock.
addDockWidget( dockArea, dockWidget );
//
return dockWidget;
}
/*****************************************************************************/
VectorImageModel *
I18nMainWindow
::ImportImage( const QString& filename,
int widthVal,
int heightVal )
{
return
QObjectCast< VectorImageModel * >(
Import(
// New dataset-importer worker.
// It will be auto-deleted by background-task.
new ImageImporter(
filename,
widthVal, heightVal
)
),
"QObject is not a VectorImageModel."
);
}
/*****************************************************************************/
bool
I18nMainWindow
::BuildGDALOverviews( const QStringList & filenames )
{
ImportImagesDialog * importDialog = new ImportImagesDialog( filenames, this );
if( importDialog->GetEffectiveCount()<1 )
return true;
int result = importDialog->exec();
if( result== QDialog::Rejected )
return false;
if( result==QDialog::Accepted )
{
// AbstractWorker will be automatically deleted by BackgroundTask in
// ::Import().
OverviewBuilder * builder =
new OverviewBuilder(
importDialog->GetGDALOverviewsBuilders()
);
delete importDialog;
importDialog = NULL;
Import( builder );
}
return true;
}
/*****************************************************************************/
QObject *
I18nMainWindow
::Import( AbstractWorker * importer )
{
assert( importer );
//
// Background task.
// New background-task running worker.
// Will be self auto-deleted when worker has finished.
BackgroundTask* task = new BackgroundTask( importer, false, this );
//
// Progress dialog.
TaskProgressDialog progress(
task,
this,
Qt::CustomizeWindowHint | Qt::WindowTitleHint
);
progress.setWindowModality( Qt::WindowModal );
progress.setAutoReset( false );
progress.setAutoClose( false );
progress.setCancelButton( NULL );
progress.setMinimumDuration( 0 );
//
// Result.
int button = progress.Exec();
// MANTIS-921 (synchronize deletion of BackgroungTask).
task->wait();
delete task;
task = NULL;
// MANTIS-921 (then, process result).
if( button!=QDialog::Accepted )
{
assert( progress.GetObject()==NULL );
return NULL;
}
// qDebug() << "object:" << progress.GetObject< DatasetModel >();
// assert( progress.GetObject()!=NULL );
return progress.GetObject();
}
/*****************************************************************************/
void
I18nMainWindow
::closeEvent( QCloseEvent * e )
{
QMainWindow::closeEvent( e );
}
/*****************************************************************************/
void
I18nMainWindow
::virtual_InitializeUI()
{
// Change to NULL model to force emitting GUI signals when GUI is
// instantiated. So, GUI will be initialized and controller-widgets
// disabled.
I18nApplication::Instance()->SetModel( NULL );
}
/*****************************************************************************/
void
I18nMainWindow
::SaveLayout( int version ) const
{
// qDebug() << this << "::SaveLayout()";
assert( I18nCoreApplication::Instance()!=NULL );
QString name( objectName() );
I18nCoreApplication::Instance()
->StoreSettingsKey( name + "Geometry", saveGeometry() );
I18nCoreApplication::Instance()
->StoreSettingsKey( name + "State", saveState( version ) );
}
/*****************************************************************************/
bool
I18nMainWindow
::RestoreLayout( int version )
{
// qDebug() << this << "::RestoreLayout()";
I18nCoreApplication * application = I18nCoreApplication::Instance();
assert( application!=NULL );
QString name( objectName() );
assert( !name.isEmpty() );
if( !restoreGeometry(
application->RetrieveSettingsKey( name + "Geometry" ).toByteArray() ) )
return false;
return
restoreState(
application->RetrieveSettingsKey( name + "State" ).toByteArray(),
version
);
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
void
I18nMainWindow
::on_action_Quit_triggered()
{
close();
}
/*****************************************************************************/
void
I18nMainWindow
::on_action_About_triggered()
{
AboutDialog aboutDialog( this );
aboutDialog.exec();
}
/*****************************************************************************/
} // end namespace 'mvd'
<commit_msg>BUG: Mantis-1338: ImportImageDialog was not deleted<commit_after>/*=========================================================================
Program: Monteverdi
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#include "mvdI18nMainWindow.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbSystem.h"
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdBackgroundTask.h"
#include "mvdImageImporter.h"
#include "mvdOverviewBuilder.h"
#include "mvdVectorImageModel.h"
#include "mvdAboutDialog.h"
#include "mvdI18nApplication.h"
#include "mvdImportImagesDialog.h"
#include "mvdTaskProgressDialog.h"
namespace mvd
{
/*
TRANSLATOR mvd::I18nMainWindow
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
I18nMainWindow
::I18nMainWindow( QWidget* p, Qt::WindowFlags flags ) :
QMainWindow( p, flags )
{
}
/*****************************************************************************/
I18nMainWindow
::~I18nMainWindow()
{
}
/*****************************************************************************/
void
I18nMainWindow
::Initialize()
{
/*
// Default setup.
setObjectName( "mvd::I18nMainWindow" );
setWindowTitle( PROJECT_NAME );
*/
virtual_SetupUI();
// Connect Appllication and MainWindow when selected model is about
// to change.
QObject::connect(
I18nApplication::Instance(),
SIGNAL( AboutToChangeModel( const AbstractModel* ) ),
this,
SLOT( OnAboutToChangeModel( const AbstractModel* ) )
);
// Connect Application and MainWindow when selected model has been
// changed.
QObject::connect(
I18nApplication::Instance(),
SIGNAL( ModelChanged( AbstractModel* ) ),
this,
SLOT( OnModelChanged( AbstractModel* ) )
);
virtual_ConnectUI();
virtual_InitializeUI();
}
/*****************************************************************************/
QDockWidget*
I18nMainWindow
::AddWidgetToDock( QWidget* widget,
const QString& dockName,
const QString& dockTitle,
Qt::DockWidgetArea dockArea,
DockLayoutFlags flags )
{
// New dock.
QDockWidget* dockWidget = new QDockWidget( dockTitle, this );
// You can use findChild( dockName ) to get dock-widget.
dockWidget->setObjectName( dockName );
dockWidget->setWidget( widget );
// Features.
dockWidget->setFloating( flags.testFlag( DOCK_LAYOUT_FLOATING ) );
dockWidget->setFeatures(
QDockWidget::DockWidgetMovable |
QDockWidget::DockWidgetFloatable |
QDockWidget::DockWidgetClosable
);
// dockWidget->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
// dockWidget->adjustSize();
// Add dock.
addDockWidget( dockArea, dockWidget );
//
return dockWidget;
}
/*****************************************************************************/
VectorImageModel *
I18nMainWindow
::ImportImage( const QString& filename,
int widthVal,
int heightVal )
{
return
QObjectCast< VectorImageModel * >(
Import(
// New dataset-importer worker.
// It will be auto-deleted by background-task.
new ImageImporter(
filename,
widthVal, heightVal
)
),
"QObject is not a VectorImageModel."
);
}
/*****************************************************************************/
bool
I18nMainWindow
::BuildGDALOverviews( const QStringList & filenames )
{
ImportImagesDialog * importDialog = new ImportImagesDialog( filenames, this );
// The import dialog should be deleted before leaving this function
if( importDialog->GetEffectiveCount()<1 )
{
delete importDialog;
importDialog = NULL;
return true;
}
int result = importDialog->exec();
if( result== QDialog::Rejected )
{
delete importDialog;
importDialog = NULL;
return false;
}
if( result==QDialog::Accepted )
{
// AbstractWorker will be automatically deleted by BackgroundTask in
// ::Import().
OverviewBuilder * builder =
new OverviewBuilder(
importDialog->GetGDALOverviewsBuilders()
);
delete importDialog;
importDialog = NULL;
Import( builder );
}
if (importDialog)
{
delete importDialog;
importDialog = NULL;
}
return true;
}
/*****************************************************************************/
QObject *
I18nMainWindow
::Import( AbstractWorker * importer )
{
assert( importer );
//
// Background task.
// New background-task running worker.
// Will be self auto-deleted when worker has finished.
BackgroundTask* task = new BackgroundTask( importer, false, this );
//
// Progress dialog.
TaskProgressDialog progress(
task,
this,
Qt::CustomizeWindowHint | Qt::WindowTitleHint
);
progress.setWindowModality( Qt::WindowModal );
progress.setAutoReset( false );
progress.setAutoClose( false );
progress.setCancelButton( NULL );
progress.setMinimumDuration( 0 );
//
// Result.
int button = progress.Exec();
// MANTIS-921 (synchronize deletion of BackgroungTask).
task->wait();
delete task;
task = NULL;
// MANTIS-921 (then, process result).
if( button!=QDialog::Accepted )
{
assert( progress.GetObject()==NULL );
return NULL;
}
// qDebug() << "object:" << progress.GetObject< DatasetModel >();
// assert( progress.GetObject()!=NULL );
return progress.GetObject();
}
/*****************************************************************************/
void
I18nMainWindow
::closeEvent( QCloseEvent * e )
{
QMainWindow::closeEvent( e );
}
/*****************************************************************************/
void
I18nMainWindow
::virtual_InitializeUI()
{
// Change to NULL model to force emitting GUI signals when GUI is
// instantiated. So, GUI will be initialized and controller-widgets
// disabled.
I18nApplication::Instance()->SetModel( NULL );
}
/*****************************************************************************/
void
I18nMainWindow
::SaveLayout( int version ) const
{
// qDebug() << this << "::SaveLayout()";
assert( I18nCoreApplication::Instance()!=NULL );
QString name( objectName() );
I18nCoreApplication::Instance()
->StoreSettingsKey( name + "Geometry", saveGeometry() );
I18nCoreApplication::Instance()
->StoreSettingsKey( name + "State", saveState( version ) );
}
/*****************************************************************************/
bool
I18nMainWindow
::RestoreLayout( int version )
{
// qDebug() << this << "::RestoreLayout()";
I18nCoreApplication * application = I18nCoreApplication::Instance();
assert( application!=NULL );
QString name( objectName() );
assert( !name.isEmpty() );
if( !restoreGeometry(
application->RetrieveSettingsKey( name + "Geometry" ).toByteArray() ) )
return false;
return
restoreState(
application->RetrieveSettingsKey( name + "State" ).toByteArray(),
version
);
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
void
I18nMainWindow
::on_action_Quit_triggered()
{
close();
}
/*****************************************************************************/
void
I18nMainWindow
::on_action_About_triggered()
{
AboutDialog aboutDialog( this );
aboutDialog.exec();
}
/*****************************************************************************/
} // end namespace 'mvd'
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_data_struct.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] 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_stop_data_struct.H
/// @brief describes data structures internal to STOP API.
///
// *HWP HW Owner : Greg Still <[email protected]>
// *HWP FW Owner : Prem Shanker Jha <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : HB:HYP
#ifndef __STOP_DATA_STRUCT_
#define __STOP_DATA_STRUCT_
#ifndef _AIX
#include <endian.h>
#endif
#include "p9_hcd_memmap_base.H"
#ifdef __FAPI_2_
#include <fapi2.H>
#endif
#ifdef __cplusplus
extern "C" {
namespace stopImageSection
{
#endif
enum
{
MAX_SPR_RESTORE_INST = 0x08,
SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) / sizeof(uint32_t)),
};
typedef struct
{
uint32_t scomEntryHeader;
uint32_t scomEntryAddress;
uint64_t scomEntryData;
} ScomEntry_t;
/**
* @brief models a CPU register restoration area in STOP section of homer image.
*/
typedef struct
{
uint8_t threadArea[CORE_RESTORE_THREAD_AREA_SIZE];
uint8_t coreArea[CORE_RESTORE_CORE_AREA_SIZE];
} SprRestoreArea_t;
/**
* @brief models homer image of a chip.
* @note sections not relevant for CPU register restoration have been
* abstracted using field 'reserve'.
*/
typedef struct
{
uint8_t occ_host_sgpe_area[ TWO_MB ]; // CPU restore area starts at an offset of 2MB from chip HOMER
uint8_t interrruptHandler[SELF_RESTORE_INT_SIZE];
uint8_t threadLauncher[THREAD_LAUNCHER_SIZE];
SprRestoreArea_t coreThreadRestore[MAX_CORES_PER_CHIP][MAX_THREADS_PER_CORE];
uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL];
} HomerSection_t;
/**
* @brief models cache subsection in STOP section of a given homer image.
* @note given the start of cache subsection associated with a given core,
* the structure below represents what a cache subsection would look
* like. Based on known start address, quick traversing can be done
* within the cache subsection.
*/
typedef struct
{
ScomEntry_t nonCacheArea[MAX_EQ_SCOM_ENTRIES];
ScomEntry_t l2CacheArea[MAX_L2_SCOM_ENTRIES];
ScomEntry_t l3CacheArea[MAX_L3_SCOM_ENTRIES];
} StopCacheSection_t;
/**
* @brief summarizes attributes associated with a SPR register.
*/
typedef struct
{
uint32_t sprId;
bool isThreadScope;
} StopSprReg_t;
enum
{
SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ),
SCOM_ENTRY_START = 0xDEADDEAD,
};
#ifdef __FAPI_2_
#define MY_ERR( _fmt_, _args_...) FAPI_ERR(_fmt_, ##_args_)
#define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#else
#define MY_ERR( _fmt_, _args_...)
#define MY_INF(_fmt_, _args_...)
#endif
#define CORE_ID_SCOM_START(io_image,\
i_chipletId) \
((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\
((i_chipletId - CORE_CHIPLET_ID_MIN) * \
CORE_SCOM_RESTORE_SIZE_PER_CORE)));
#define CACHE_SECTN_START(io_image,\
i_chipletId) \
((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\
((i_chipletId - CACHE_CHIPLET_ID_MIN) * \
QUAD_SCOM_RESTORE_SIZE_PER_QUAD)));
#ifdef __cplusplus
} // extern "C"
} //namespace stopImageSection ends
#endif //__cplusplus
#endif
<commit_msg>Fixes required to build P9 STOP API with skiboot<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_data_struct.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] 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_stop_data_struct.H
/// @brief describes data structures internal to STOP API.
///
// *HWP HW Owner : Greg Still <[email protected]>
// *HWP FW Owner : Prem Shanker Jha <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : HB:HYP
#ifndef __STOP_DATA_STRUCT_
#define __STOP_DATA_STRUCT_
#ifndef _AIX
#include <endian.h>
#endif
#include "p9_hcd_memmap_base.H"
#ifdef __SKIBOOT__
#include <skiboot.h>
#endif
#ifdef __FAPI_2_
#include <fapi2.H>
#endif
#ifdef __cplusplus
extern "C" {
namespace stopImageSection
{
#endif
enum
{
MAX_SPR_RESTORE_INST = 0x08,
SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) / sizeof(uint32_t)),
};
typedef struct
{
uint32_t scomEntryHeader;
uint32_t scomEntryAddress;
uint64_t scomEntryData;
} ScomEntry_t;
/**
* @brief models a CPU register restoration area in STOP section of homer image.
*/
typedef struct
{
uint8_t threadArea[CORE_RESTORE_THREAD_AREA_SIZE];
uint8_t coreArea[CORE_RESTORE_CORE_AREA_SIZE];
} SprRestoreArea_t;
/**
* @brief models homer image of a chip.
* @note sections not relevant for CPU register restoration have been
* abstracted using field 'reserve'.
*/
typedef struct
{
uint8_t occ_host_sgpe_area[ TWO_MB ]; // CPU restore area starts at an offset of 2MB from chip HOMER
uint8_t interrruptHandler[SELF_RESTORE_INT_SIZE];
uint8_t threadLauncher[THREAD_LAUNCHER_SIZE];
SprRestoreArea_t coreThreadRestore[MAX_CORES_PER_CHIP][MAX_THREADS_PER_CORE];
uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL];
} HomerSection_t;
/**
* @brief models cache subsection in STOP section of a given homer image.
* @note given the start of cache subsection associated with a given core,
* the structure below represents what a cache subsection would look
* like. Based on known start address, quick traversing can be done
* within the cache subsection.
*/
typedef struct
{
ScomEntry_t nonCacheArea[MAX_EQ_SCOM_ENTRIES];
ScomEntry_t l2CacheArea[MAX_L2_SCOM_ENTRIES];
ScomEntry_t l3CacheArea[MAX_L3_SCOM_ENTRIES];
} StopCacheSection_t;
/**
* @brief summarizes attributes associated with a SPR register.
*/
typedef struct
{
uint32_t sprId;
bool isThreadScope;
} StopSprReg_t;
enum
{
SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ),
SCOM_ENTRY_START = 0xDEADDEAD,
};
#ifdef __FAPI_2_
#define MY_ERR( _fmt_, _args_...) FAPI_ERR(_fmt_, ##_args_)
#define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#else
#define MY_ERR( _fmt_, _args_...)
#define MY_INF(_fmt_, _args_...)
#endif
#define CORE_ID_SCOM_START(io_image,\
i_chipletId) \
((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\
((i_chipletId - CORE_CHIPLET_ID_MIN) * \
CORE_SCOM_RESTORE_SIZE_PER_CORE)));
#define CACHE_SECTN_START(io_image,\
i_chipletId) \
((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\
((i_chipletId - CACHE_CHIPLET_ID_MIN) * \
QUAD_SCOM_RESTORE_SIZE_PER_QUAD)));
#ifdef __cplusplus
} // extern "C"
} //namespace stopImageSection ends
#endif //__cplusplus
#endif
<|endoftext|> |
<commit_before>#include "ksp_plugin/journal.hpp"
#include <fstream>
#include <list>
#include <string>
#include <type_traits>
#include "base/array.hpp"
#include "base/get_line.hpp"
#include "base/hexadecimal.hpp"
#include "base/map_util.hpp"
#include "glog/logging.h"
namespace principia {
namespace ksp_plugin {
using base::Bytes;
using base::FindOrDie;
using base::GetLine;
using base::HexadecimalDecode;
using base::HexadecimalEncode;
using base::UniqueBytes;
namespace {
int const kBufferSize = 100;
template<typename T,
typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T Find(PointerMap const& pointer_map, std::uint64_t const address) {
return reinterpret_cast<T>(FindOrDie(pointer_map, address));
}
template<typename T>
void Insert(not_null<PointerMap*> const pointer_map,
std::uint64_t const address,
T* const pointer) {
auto inserted = pointer_map->emplace(address, pointer);
CHECK(inserted.second) << address;
}
template<typename T>
std::uint64_t SerializePointer(T* t) {
return reinterpret_cast<std::uint64_t>(t);
}
serialization::XYZ SerializeXYZ(XYZ const& xyz) {
serialization::XYZ m;
m.set_x(xyz.x);
m.set_y(xyz.y);
m.set_z(xyz.z);
return m;
}
serialization::QP SerializeQP(QP const& qp) {
serialization::QP m;
*m.mutable_p() = SerializeXYZ(qp.p);
*m.mutable_q() = SerializeXYZ(qp.q);
return m;
}
} // namespace
void SetBufferedLogging::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_max_severity(in.max_severity);
}
void SetBufferedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetBufferedLogging(message.in().max_severity());
}
void GetBufferedLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_max_severity(result);
}
void GetBufferedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().max_severity(), principia__GetBufferedLogging());
}
void SetBufferDuration::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_seconds(in.seconds);
}
void SetBufferDuration::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetBufferDuration(message.in().seconds());
}
void GetBufferDuration::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_seconds(result);
}
void GetBufferDuration::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().seconds(), principia__GetBufferDuration());
}
void SetSuppressedLogging::Fill(In const& in,
not_null<Message*> const message) {
message->mutable_in()->set_min_severity(in.min_severity);
}
void SetSuppressedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetSuppressedLogging(message.in().min_severity());
}
void GetSuppressedLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_min_severity(result);
}
void GetSuppressedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().min_severity(), principia__GetSuppressedLogging());
}
void SetVerboseLogging::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_level(in.level);
}
void SetVerboseLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetVerboseLogging(message.in().level());
}
void GetVerboseLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_level(result);
}
void GetVerboseLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().level(), principia__GetVerboseLogging());
}
void SetStderrLogging::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_min_severity(in.min_severity);
}
void SetStderrLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetStderrLogging(message.in().min_severity());
}
void GetStderrLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_min_severity(result);
}
void GetStderrLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().min_severity(), principia__GetStderrLogging());
}
void LogInfo::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogInfo::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogInfo(message.in().message().c_str());
}
void LogWarning::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogWarning::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogWarning(message.in().message().c_str());
}
void LogError::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogError::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogError(message.in().message().c_str());
}
void LogFatal::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogFatal::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogFatal(message.in().message().c_str());
}
void NewPlugin::Fill(In const& in, not_null<Message*> const message) {
auto* mutable_in = message->mutable_in();
mutable_in->set_initial_time(in.initial_time);
mutable_in->set_planetarium_rotation_in_degrees(
in.planetarium_rotation_in_degrees);
}
void NewPlugin::Fill(Return const& result, not_null<Message*> const message) {
message->mutable_return_()->set_plugin(SerializePointer(result));
}
void NewPlugin::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
auto* plugin = principia__NewPlugin(
message.in().initial_time(),
message.in().planetarium_rotation_in_degrees());
Insert(pointer_map, message.return_().plugin(), plugin);
}
void DeletePlugin::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_plugin(SerializePointer(in.plugin));
}
void DeletePlugin::Fill(Out const& out, not_null<Message*> const message) {
message->mutable_out()->set_plugin(SerializePointer(*out.plugin));
}
void DeletePlugin::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
auto* plugin = Find<Plugin const*>(*pointer_map, message.in().plugin());
principia__DeletePlugin(&plugin);
// TODO(phl): should we do something with out() here?
}
void DirectlyInsertCelestial::Fill(In const& in,
not_null<Message*> const message) {
Message::In* m = message->mutable_in();
m->set_plugin(SerializePointer(in.plugin));
m->set_celestial_index(in.celestial_index);
if (in.parent_index != nullptr) {
m->set_parent_index(*in.parent_index);
}
m->set_gravitational_parameter(in.gravitational_parameter);
if (in.axis_right_ascension != nullptr) {
m->set_axis_right_ascension(in.axis_right_ascension);
}
if (in.axis_declination != nullptr) {
m->set_axis_declination(in.axis_declination);
}
if (in.j2 != nullptr) {
m->set_j2(in.j2);
}
if (in.reference_radius != nullptr) {
m->set_reference_radius(in.reference_radius);
}
m->set_x(in.x);
m->set_y(in.y);
m->set_z(in.z);
m->set_vx(in.vx);
m->set_vy(in.vy);
m->set_vz(in.vz);
}
void InsertCelestial::Fill(In const& in, not_null<Message*> const message) {
Message::In* m = message->mutable_in();
m->set_plugin(SerializePointer(in.plugin));
m->set_celestial_index(in.celestial_index);
m->set_gravitational_parameter(in.gravitational_parameter);
m->set_parent_index(in.parent_index);
*m->mutable_from_parent() = SerializeQP(in.from_parent);
}
Journal::Journal(std::experimental::filesystem::path const& path)
: stream_(path, std::ios::out) {}
Journal::~Journal() {
stream_.close();
}
void Journal::Write(serialization::Method const& method) {
UniqueBytes bytes(method.ByteSize());
method.SerializeToArray(bytes.data.get(), static_cast<int>(bytes.size));
std::int64_t const hexadecimal_size = (bytes.size << 1) + 2;
UniqueBytes hexadecimal(hexadecimal_size);
HexadecimalEncode({bytes.data.get(), bytes.size}, hexadecimal.get());
hexadecimal.data.get()[hexadecimal_size - 2] = '\n';
hexadecimal.data.get()[hexadecimal_size - 1] = '\0';
stream_ << hexadecimal.data.get();
stream_.flush();
}
void Journal::Activate(base::not_null<Journal*> const journal) {
CHECK(active_ == nullptr);
active_ = journal;
}
void Journal::Deactivate() {
CHECK(active_ != nullptr);
delete active_;
active_ = nullptr;
}
Player::Player(std::experimental::filesystem::path const& path)
: stream_(path, std::ios::in) {}
bool Player::Play() {
std::unique_ptr<serialization::Method> method = Read();
if (method == nullptr) {
return false;
}
bool ran = false;
ran |= RunIfAppropriate<DeletePlugin>(*method);
ran |= RunIfAppropriate<NewPlugin>(*method);
CHECK(ran);
return true;
}
std::unique_ptr<serialization::Method> Player::Read() {
std::string const line = GetLine(&stream_);
if (line.empty()) {
return nullptr;
}
uint8_t const* const hexadecimal =
reinterpret_cast<uint8_t const*>(line.c_str());
int const hexadecimal_size = strlen(line.c_str());
UniqueBytes bytes(hexadecimal_size >> 1);
HexadecimalDecode({hexadecimal, hexadecimal_size},
{bytes.data.get(), bytes.size});
auto method = std::make_unique<serialization::Method>();
CHECK(method->ParseFromArray(bytes.data.get(),
static_cast<int>(bytes.size)));
return method;
}
Journal* Journal::active_ = nullptr;
} // namespace ksp_plugin
} // namespace principia
<commit_msg>Empty definitions.<commit_after>#include "ksp_plugin/journal.hpp"
#include <fstream>
#include <list>
#include <string>
#include <type_traits>
#include "base/array.hpp"
#include "base/get_line.hpp"
#include "base/hexadecimal.hpp"
#include "base/map_util.hpp"
#include "glog/logging.h"
namespace principia {
namespace ksp_plugin {
using base::Bytes;
using base::FindOrDie;
using base::GetLine;
using base::HexadecimalDecode;
using base::HexadecimalEncode;
using base::UniqueBytes;
namespace {
int const kBufferSize = 100;
template<typename T,
typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T Find(PointerMap const& pointer_map, std::uint64_t const address) {
return reinterpret_cast<T>(FindOrDie(pointer_map, address));
}
template<typename T>
void Insert(not_null<PointerMap*> const pointer_map,
std::uint64_t const address,
T* const pointer) {
auto inserted = pointer_map->emplace(address, pointer);
CHECK(inserted.second) << address;
}
template<typename T>
std::uint64_t SerializePointer(T* t) {
return reinterpret_cast<std::uint64_t>(t);
}
serialization::XYZ SerializeXYZ(XYZ const& xyz) {
serialization::XYZ m;
m.set_x(xyz.x);
m.set_y(xyz.y);
m.set_z(xyz.z);
return m;
}
serialization::QP SerializeQP(QP const& qp) {
serialization::QP m;
*m.mutable_p() = SerializeXYZ(qp.p);
*m.mutable_q() = SerializeXYZ(qp.q);
return m;
}
} // namespace
void SetBufferedLogging::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_max_severity(in.max_severity);
}
void SetBufferedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetBufferedLogging(message.in().max_severity());
}
void GetBufferedLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_max_severity(result);
}
void GetBufferedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().max_severity(), principia__GetBufferedLogging());
}
void SetBufferDuration::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_seconds(in.seconds);
}
void SetBufferDuration::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetBufferDuration(message.in().seconds());
}
void GetBufferDuration::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_seconds(result);
}
void GetBufferDuration::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().seconds(), principia__GetBufferDuration());
}
void SetSuppressedLogging::Fill(In const& in,
not_null<Message*> const message) {
message->mutable_in()->set_min_severity(in.min_severity);
}
void SetSuppressedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetSuppressedLogging(message.in().min_severity());
}
void GetSuppressedLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_min_severity(result);
}
void GetSuppressedLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().min_severity(), principia__GetSuppressedLogging());
}
void SetVerboseLogging::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_level(in.level);
}
void SetVerboseLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetVerboseLogging(message.in().level());
}
void GetVerboseLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_level(result);
}
void GetVerboseLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().level(), principia__GetVerboseLogging());
}
void SetStderrLogging::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_min_severity(in.min_severity);
}
void SetStderrLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__SetStderrLogging(message.in().min_severity());
}
void GetStderrLogging::Fill(Return const& result,
not_null<Message*> const message) {
message->mutable_return_()->set_min_severity(result);
}
void GetStderrLogging::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
CHECK_EQ(message.return_().min_severity(), principia__GetStderrLogging());
}
void LogInfo::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogInfo::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogInfo(message.in().message().c_str());
}
void LogWarning::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogWarning::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogWarning(message.in().message().c_str());
}
void LogError::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogError::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogError(message.in().message().c_str());
}
void LogFatal::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_message(in.message);
}
void LogFatal::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
principia__LogFatal(message.in().message().c_str());
}
void NewPlugin::Fill(In const& in, not_null<Message*> const message) {
auto* mutable_in = message->mutable_in();
mutable_in->set_initial_time(in.initial_time);
mutable_in->set_planetarium_rotation_in_degrees(
in.planetarium_rotation_in_degrees);
}
void NewPlugin::Fill(Return const& result, not_null<Message*> const message) {
message->mutable_return_()->set_plugin(SerializePointer(result));
}
void NewPlugin::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
auto* plugin = principia__NewPlugin(
message.in().initial_time(),
message.in().planetarium_rotation_in_degrees());
Insert(pointer_map, message.return_().plugin(), plugin);
}
void DeletePlugin::Fill(In const& in, not_null<Message*> const message) {
message->mutable_in()->set_plugin(SerializePointer(in.plugin));
}
void DeletePlugin::Fill(Out const& out, not_null<Message*> const message) {
message->mutable_out()->set_plugin(SerializePointer(*out.plugin));
}
void DeletePlugin::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {
auto* plugin = Find<Plugin const*>(*pointer_map, message.in().plugin());
principia__DeletePlugin(&plugin);
// TODO(phl): should we do something with out() here?
}
void DirectlyInsertCelestial::Fill(In const& in,
not_null<Message*> const message) {
Message::In* m = message->mutable_in();
m->set_plugin(SerializePointer(in.plugin));
m->set_celestial_index(in.celestial_index);
if (in.parent_index != nullptr) {
m->set_parent_index(*in.parent_index);
}
m->set_gravitational_parameter(in.gravitational_parameter);
if (in.axis_right_ascension != nullptr) {
m->set_axis_right_ascension(in.axis_right_ascension);
}
if (in.axis_declination != nullptr) {
m->set_axis_declination(in.axis_declination);
}
if (in.j2 != nullptr) {
m->set_j2(in.j2);
}
if (in.reference_radius != nullptr) {
m->set_reference_radius(in.reference_radius);
}
m->set_x(in.x);
m->set_y(in.y);
m->set_z(in.z);
m->set_vx(in.vx);
m->set_vy(in.vy);
m->set_vz(in.vz);
}
void DirectlyInsertCelestial::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void InsertCelestial::Fill(In const& in, not_null<Message*> const message) {
Message::In* m = message->mutable_in();
m->set_plugin(SerializePointer(in.plugin));
m->set_celestial_index(in.celestial_index);
m->set_gravitational_parameter(in.gravitational_parameter);
m->set_parent_index(in.parent_index);
*m->mutable_from_parent() = SerializeQP(in.from_parent);
}
void InsertCelestial::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void InsertSun::Fill(In const& in, not_null<Message*> const message) {}
void InsertSun::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void UpdateCelestialHierarchy::Fill(In const& in,
not_null<Message*> const message) {}
void UpdateCelestialHierarchy::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void EndInitialization::Fill(In const& in, not_null<Message*> const message) {}
void EndInitialization::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void InsertOrKeepVessel::Fill(In const& in, not_null<Message*> const message) {}
void InsertOrKeepVessel::Fill(Return const& result,
not_null<Message*> const message) {}
void InsertOrKeepVessel::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void SetVesselStateOffset::Fill(In const& in,
not_null<Message*> const message) {}
void SetVesselStateOffset::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void AdvanceTime::Fill(In const& in, not_null<Message*> const message) {}
void AdvanceTime::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
void ForgetAllHistoriesBefore::Fill(In const& in,
not_null<Message*> const message) {}
void ForgetAllHistoriesBefore::Run(Message const& message,
not_null<PointerMap*> const pointer_map) {}
Journal::Journal(std::experimental::filesystem::path const& path)
: stream_(path, std::ios::out) {}
Journal::~Journal() {
stream_.close();
}
void Journal::Write(serialization::Method const& method) {
UniqueBytes bytes(method.ByteSize());
method.SerializeToArray(bytes.data.get(), static_cast<int>(bytes.size));
std::int64_t const hexadecimal_size = (bytes.size << 1) + 2;
UniqueBytes hexadecimal(hexadecimal_size);
HexadecimalEncode({bytes.data.get(), bytes.size}, hexadecimal.get());
hexadecimal.data.get()[hexadecimal_size - 2] = '\n';
hexadecimal.data.get()[hexadecimal_size - 1] = '\0';
stream_ << hexadecimal.data.get();
stream_.flush();
}
void Journal::Activate(base::not_null<Journal*> const journal) {
CHECK(active_ == nullptr);
active_ = journal;
}
void Journal::Deactivate() {
CHECK(active_ != nullptr);
delete active_;
active_ = nullptr;
}
Player::Player(std::experimental::filesystem::path const& path)
: stream_(path, std::ios::in) {}
bool Player::Play() {
std::unique_ptr<serialization::Method> method = Read();
if (method == nullptr) {
return false;
}
bool ran = false;
ran |= RunIfAppropriate<DeletePlugin>(*method);
ran |= RunIfAppropriate<NewPlugin>(*method);
CHECK(ran);
return true;
}
std::unique_ptr<serialization::Method> Player::Read() {
std::string const line = GetLine(&stream_);
if (line.empty()) {
return nullptr;
}
uint8_t const* const hexadecimal =
reinterpret_cast<uint8_t const*>(line.c_str());
int const hexadecimal_size = strlen(line.c_str());
UniqueBytes bytes(hexadecimal_size >> 1);
HexadecimalDecode({hexadecimal, hexadecimal_size},
{bytes.data.get(), bytes.size});
auto method = std::make_unique<serialization::Method>();
CHECK(method->ParseFromArray(bytes.data.get(),
static_cast<int>(bytes.size)));
return method;
}
Journal* Journal::active_ = nullptr;
} // namespace ksp_plugin
} // namespace principia
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleSlide.h"
#include "SkCanvas.h"
#include "SkCommonFlags.h"
#include "SkKey.h"
#include "SkOSFile.h"
#include "SkStream.h"
using namespace sk_app;
SampleSlide::SampleSlide(const SkViewFactory* factory)
: fViewFactory(factory)
, fClick(nullptr) {
SkView* view = (*factory)();
SampleCode::RequestTitle(view, &fName);
view->unref();
}
SampleSlide::~SampleSlide() { delete fClick; }
void SampleSlide::draw(SkCanvas* canvas) {
SkASSERT(fView);
fView->draw(canvas);
}
void SampleSlide::load(SkScalar winWidth, SkScalar winHeight) {
fView.reset((*fViewFactory)());
fView->setVisibleP(true);
fView->setClipToBounds(false);
fView->setSize(winWidth, winHeight);
}
void SampleSlide::unload() {
fView.reset();
}
bool SampleSlide::onChar(SkUnichar c) {
if (!fView) {
return false;
}
SkEvent evt(gCharEvtName);
evt.setFast32(c);
return fView->doQuery(&evt);
}
bool SampleSlide::onMouse(SkScalar x, SkScalar y, Window::InputState state,
uint32_t modifiers) {
// map to SkView modifiers
unsigned modifierKeys = 0;
modifierKeys |= (state & Window::kShift_ModifierKey) ? kShift_SkModifierKey : 0;
modifierKeys |= (state & Window::kControl_ModifierKey) ? kControl_SkModifierKey : 0;
modifierKeys |= (state & Window::kOption_ModifierKey) ? kOption_SkModifierKey : 0;
modifierKeys |= (state & Window::kCommand_ModifierKey) ? kCommand_SkModifierKey : 0;
bool handled = false;
switch (state) {
case Window::kDown_InputState: {
delete fClick;
fClick = fView->findClickHandler(SkIntToScalar(x), SkIntToScalar(y), modifierKeys);
if (fClick) {
SkView::DoClickDown(fClick, x, y, modifierKeys);
handled = true;
}
break;
}
case Window::kMove_InputState: {
if (fClick) {
SkView::DoClickMoved(fClick, x, y, modifierKeys);
handled = true;
}
break;
}
case Window::kUp_InputState: {
if (fClick) {
SkView::DoClickUp(fClick, x, y, modifierKeys);
delete fClick;
fClick = nullptr;
handled = true;
}
break;
}
}
return handled;
}
<commit_msg>Fix sample modifier keys for mouse events<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleSlide.h"
#include "SkCanvas.h"
#include "SkCommonFlags.h"
#include "SkKey.h"
#include "SkOSFile.h"
#include "SkStream.h"
using namespace sk_app;
SampleSlide::SampleSlide(const SkViewFactory* factory)
: fViewFactory(factory)
, fClick(nullptr) {
SkView* view = (*factory)();
SampleCode::RequestTitle(view, &fName);
view->unref();
}
SampleSlide::~SampleSlide() { delete fClick; }
void SampleSlide::draw(SkCanvas* canvas) {
SkASSERT(fView);
fView->draw(canvas);
}
void SampleSlide::load(SkScalar winWidth, SkScalar winHeight) {
fView.reset((*fViewFactory)());
fView->setVisibleP(true);
fView->setClipToBounds(false);
fView->setSize(winWidth, winHeight);
}
void SampleSlide::unload() {
fView.reset();
}
bool SampleSlide::onChar(SkUnichar c) {
if (!fView) {
return false;
}
SkEvent evt(gCharEvtName);
evt.setFast32(c);
return fView->doQuery(&evt);
}
bool SampleSlide::onMouse(SkScalar x, SkScalar y, Window::InputState state,
uint32_t modifiers) {
// map to SkView modifiers
unsigned modifierKeys = 0;
modifierKeys |= (modifiers & Window::kShift_ModifierKey) ? kShift_SkModifierKey : 0;
modifierKeys |= (modifiers & Window::kControl_ModifierKey) ? kControl_SkModifierKey : 0;
modifierKeys |= (modifiers & Window::kOption_ModifierKey) ? kOption_SkModifierKey : 0;
modifierKeys |= (modifiers & Window::kCommand_ModifierKey) ? kCommand_SkModifierKey : 0;
bool handled = false;
switch (state) {
case Window::kDown_InputState: {
delete fClick;
fClick = fView->findClickHandler(SkIntToScalar(x), SkIntToScalar(y), modifierKeys);
if (fClick) {
SkView::DoClickDown(fClick, x, y, modifierKeys);
handled = true;
}
break;
}
case Window::kMove_InputState: {
if (fClick) {
SkView::DoClickMoved(fClick, x, y, modifierKeys);
handled = true;
}
break;
}
case Window::kUp_InputState: {
if (fClick) {
SkView::DoClickUp(fClick, x, y, modifierKeys);
delete fClick;
fClick = nullptr;
handled = true;
}
break;
}
}
return handled;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <cstdlib>
// --- Root ---
#include <TROOT.h>
#include <TInterpreter.h>
#include <TClonesArray.h>
//#include <Riostream.h>
//#include <TObjectTable.h>
// --- Analysis ---
#include "AliAnalysisTaskCaloTrackCorrelation.h"
#include "AliAnaCaloTrackCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliLog.h"
/// \cond CLASSIMP
ClassImp(AliAnalysisTaskCaloTrackCorrelation) ;
/// \endcond
//________________________________________________________________________
/// Default constructor.
//________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation() :
AliAnalysisTaskSE(),
fAna(0x0),
fOutputContainer(0x0),
fConfigName(""),
fCuts(0x0),
fFirstEvent(0),
fLastEvent(0),
fStoreEventSummary(0)
{
}
//________________________________________________________________________________________
/// Default constructor.
//________________________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation(const char* name) :
AliAnalysisTaskSE(name),
fAna(0x0),
fOutputContainer(0x0),
fConfigName(""),
fCuts(0x0),
fFirstEvent(0),
fLastEvent(0),
fStoreEventSummary(0)
{
DefineOutput(1, TList::Class());
DefineOutput(2, TList::Class()); // will contain cuts or local params
}
//_________________________________________________________________________
/// Destructor.
//_________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::~AliAnalysisTaskCaloTrackCorrelation()
{
if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return;
if (fOutputContainer)
{
fOutputContainer->Clear() ;
delete fOutputContainer ;
}
if (fAna) delete fAna;
}
//_________________________________________________________________
/// Create the output container, recover it from the maker
/// (*AliAnaCaloTrackMaker fAna*) pointer.
//_________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserCreateOutputObjects()
{
AliDebug(1,"Begin");
// Get list of aod arrays, add each aod array to analysis frame
TList * list = fAna->FillAndGetAODBranchList(); //Loop the analysis and create the list of branches
AliDebug(1,Form("n AOD branches %d",list->GetEntries()));
// Put the delta AODs in output file, std or delta
if((fAna->GetReader())->WriteDeltaAODToFile())
{
TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName();
for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++)
{
TClonesArray * array = (TClonesArray*) list->At(iaod);
if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file
else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file
}
}
// Histograms container
OpenFile(1);
fOutputContainer = fAna->GetOutputContainer();
AliDebug(1,Form("n histograms %d",fOutputContainer->GetEntries()));
fOutputContainer->SetOwner(kTRUE);
AliDebug(1,"End");
PostData(1,fOutputContainer);
}
//___________________________________________________
/// Local Initialization.
/// Call the Init to initialize the configuration of the analysis.
//___________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::LocalInit()
{
Init();
}
//______________________________________________
/// Analysis configuration, if provided, and initialization.
//______________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Init()
{
AliDebug(1,"Begin");
if( fDebug >= 0 )
(AliAnalysisManager::GetAnalysisManager())->AddClassDebug(this->ClassName(),fDebug);
// Call configuration file if specified
if (fConfigName.Length())
{
AliInfo(Form("### Configuration file is %s.C ###", fConfigName.Data()));
gROOT->LoadMacro(fConfigName+".C");
fAna = (AliAnaCaloTrackCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
}
if(!fAna)
{
AliFatal("Analysis maker pointer not initialized, no analysis specified, STOP!");
return; // coverity
}
// Add different generator particles to PDG Data Base
// to avoid problems when reading MC generator particles
AliPDG::AddParticlesToPdgDataBase();
// Set in the reader the name of the task in case is needed
(fAna->GetReader())->SetTaskName(GetName());
// Initialise analysis
fAna->Init();
// Delta AOD
if((fAna->GetReader())->GetDeltaAODFileName()!="")
AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName());
// Selected Trigger
if(fAna->GetReader()->IsEventTriggerAtSEOn()) fAna->GetReader()->SetEventTriggerMask(GetCollisionCandidates());
AliDebug(1,"End");
}
//______________________________________________________________________
/// Execute analysis for current event.
//______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserExec(Option_t */*option*/)
{
if ( !fAna->IsEventProcessed() ) return;
if ( (fLastEvent > 0 && Entry() > fLastEvent ) ||
(fFirstEvent > 0 && Entry() < fFirstEvent) ) return ;
AliDebug(1,Form("Begin event %d", (Int_t) Entry()));
// Get the type of data, check if type is correct
Int_t datatype = fAna->GetReader()->GetDataType();
if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
datatype != AliCaloTrackReader::kMC)
{
AliError("Wrong type of data");
return ;
}
fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());
// Process event
fAna->ProcessEvent((Int_t) Entry(), CurrentFileName());
PostData(1, fOutputContainer);
AliDebug(1,"End");
//gObjectTable->Print();
}
//_______________________________________________________________________
/// Terminate analysis. Do some plots (plotting not used so far).
//_______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Terminate(Option_t */*option*/)
{
// Get merged histograms from the output container
// Propagate histagrams to maker
fAna->Terminate((TList*)GetOutputData(1));
// Create cuts/param objects and publish to slot
fCuts = fAna->GetListOfAnalysisCuts();
fCuts ->SetOwner(kTRUE);
// Post Data
PostData(2, fCuts);
}
//__________________________________________________________
/// Put in the output some standard event summary histograms.
//__________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::FinishTaskOutput()
{
if ( !fStoreEventSummary ) return ;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler *inputH = dynamic_cast<AliInputEventHandler*>(am->GetInputEventHandler());
if (!inputH) return;
TH2F *histStat = dynamic_cast<TH2F*>(inputH->GetStatistics());
TH2F *histBin0 = dynamic_cast<TH2F*>(inputH->GetStatistics("BIN0"));
if ( histStat )
{
if ( histStat == histBin0 ) histBin0 = 0 ;
histStat = (TH2F*) histStat->Clone(Form("%s_%s",histStat->GetName(),"CaloTrackCorr"));
fOutputContainer->Add(histStat);
}
if ( histBin0 )
{
histBin0 = (TH2F*) histBin0->Clone(Form("%s_%s",histBin0->GetName(),"CaloTrackCorr"));
fOutputContainer->Add(histBin0);
}
}
<commit_msg>add debug for event number and check event selection number<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <cstdlib>
// --- Root ---
#include <TROOT.h>
#include <TInterpreter.h>
#include <TClonesArray.h>
//#include <Riostream.h>
//#include <TObjectTable.h>
// --- Analysis ---
#include "AliAnalysisTaskCaloTrackCorrelation.h"
#include "AliAnaCaloTrackCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliAODInputHandler.h"
#include "AliLog.h"
/// \cond CLASSIMP
ClassImp(AliAnalysisTaskCaloTrackCorrelation) ;
/// \endcond
//________________________________________________________________________
/// Default constructor.
//________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation() :
AliAnalysisTaskSE(),
fAna(0x0),
fOutputContainer(0x0),
fConfigName(""),
fCuts(0x0),
fFirstEvent(0),
fLastEvent(0),
fStoreEventSummary(0)
{
}
//________________________________________________________________________________________
/// Default constructor.
//________________________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation(const char* name) :
AliAnalysisTaskSE(name),
fAna(0x0),
fOutputContainer(0x0),
fConfigName(""),
fCuts(0x0),
fFirstEvent(0),
fLastEvent(0),
fStoreEventSummary(0)
{
DefineOutput(1, TList::Class());
DefineOutput(2, TList::Class()); // will contain cuts or local params
}
//_________________________________________________________________________
/// Destructor.
//_________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::~AliAnalysisTaskCaloTrackCorrelation()
{
if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return;
if (fOutputContainer)
{
fOutputContainer->Clear() ;
delete fOutputContainer ;
}
if (fAna) delete fAna;
}
//_________________________________________________________________
/// Create the output container, recover it from the maker
/// (*AliAnaCaloTrackMaker fAna*) pointer.
//_________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserCreateOutputObjects()
{
AliDebug(1,"Begin");
// Get list of aod arrays, add each aod array to analysis frame
TList * list = fAna->FillAndGetAODBranchList(); //Loop the analysis and create the list of branches
AliDebug(1,Form("n AOD branches %d",list->GetEntries()));
// Put the delta AODs in output file, std or delta
if((fAna->GetReader())->WriteDeltaAODToFile())
{
TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName();
for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++)
{
TClonesArray * array = (TClonesArray*) list->At(iaod);
if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file
else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file
}
}
// Histograms container
OpenFile(1);
fOutputContainer = fAna->GetOutputContainer();
AliDebug(1,Form("n histograms %d",fOutputContainer->GetEntries()));
fOutputContainer->SetOwner(kTRUE);
AliDebug(1,"End");
PostData(1,fOutputContainer);
}
//___________________________________________________
/// Local Initialization.
/// Call the Init to initialize the configuration of the analysis.
//___________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::LocalInit()
{
Init();
}
//______________________________________________
/// Analysis configuration, if provided, and initialization.
//______________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Init()
{
AliDebug(1,"Begin");
if( fDebug >= 0 )
(AliAnalysisManager::GetAnalysisManager())->AddClassDebug(this->ClassName(),fDebug);
// Call configuration file if specified
if (fConfigName.Length())
{
AliInfo(Form("### Configuration file is %s.C ###", fConfigName.Data()));
gROOT->LoadMacro(fConfigName+".C");
fAna = (AliAnaCaloTrackCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
}
if(!fAna)
{
AliFatal("Analysis maker pointer not initialized, no analysis specified, STOP!");
return; // coverity
}
// Add different generator particles to PDG Data Base
// to avoid problems when reading MC generator particles
AliPDG::AddParticlesToPdgDataBase();
// Set in the reader the name of the task in case is needed
(fAna->GetReader())->SetTaskName(GetName());
// Initialise analysis
fAna->Init();
// Delta AOD
if((fAna->GetReader())->GetDeltaAODFileName()!="")
AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName());
// Selected Trigger
if(fAna->GetReader()->IsEventTriggerAtSEOn()) fAna->GetReader()->SetEventTriggerMask(GetCollisionCandidates());
AliDebug(1,"End");
}
//______________________________________________________________________
/// Execute analysis for current event.
//______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserExec(Option_t */*option*/)
{
if ( !fAna->IsEventProcessed() ) return;
Int_t eventN = Entry();
// Entry() does not work for AODs
if ( eventN <= 0 )
{
AliAODInputHandler* aodIH = dynamic_cast<AliAODInputHandler*>
((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
if ( aodIH ) eventN = aodIH->GetReadEntry();
}
if ( (fLastEvent > 0 && eventN > fLastEvent ) ||
(fFirstEvent > 0 && eventN < fFirstEvent) ) return ;
AliDebug(1,Form("Begin: Event %d - Entry %d - (First,Last)=(%d,%d)",
eventN, (Int_t) Entry(), fFirstEvent, fLastEvent));
//printf("AliAnalysisTaskCaloTrackCorrelation::UserExec() - Event %d - Entry %d - (First,Last)=(%d,%d) \n",
// eventN, (Int_t) Entry(), fFirstEvent, fLastEvent);
// Get the type of data, check if type is correct
Int_t datatype = fAna->GetReader()->GetDataType();
if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
datatype != AliCaloTrackReader::kMC)
{
AliError("Wrong type of data");
return ;
}
fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());
// Process event
fAna->ProcessEvent((Int_t) Entry(), CurrentFileName());
PostData(1, fOutputContainer);
AliDebug(1,"End");
//gObjectTable->Print();
}
//_______________________________________________________________________
/// Terminate analysis. Do some plots (plotting not used so far).
//_______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Terminate(Option_t */*option*/)
{
// Get merged histograms from the output container
// Propagate histagrams to maker
fAna->Terminate((TList*)GetOutputData(1));
// Create cuts/param objects and publish to slot
fCuts = fAna->GetListOfAnalysisCuts();
fCuts ->SetOwner(kTRUE);
// Post Data
PostData(2, fCuts);
}
//__________________________________________________________
/// Put in the output some standard event summary histograms.
//__________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::FinishTaskOutput()
{
if ( !fStoreEventSummary ) return ;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler *inputH = dynamic_cast<AliInputEventHandler*>(am->GetInputEventHandler());
if (!inputH) return;
TH2F *histStat = dynamic_cast<TH2F*>(inputH->GetStatistics());
TH2F *histBin0 = dynamic_cast<TH2F*>(inputH->GetStatistics("BIN0"));
if ( histStat )
{
if ( histStat == histBin0 ) histBin0 = 0 ;
histStat = (TH2F*) histStat->Clone(Form("%s_%s",histStat->GetName(),"CaloTrackCorr"));
fOutputContainer->Add(histStat);
}
if ( histBin0 )
{
histBin0 = (TH2F*) histBin0->Clone(Form("%s_%s",histBin0->GetName(),"CaloTrackCorr"));
fOutputContainer->Add(histBin0);
}
}
<|endoftext|> |
<commit_before>
#include "XXX/kernel.h"
#include "XXX/topic.h"
#include "XXX/wamp_session.h"
#include "XXX/wamp_connector.h"
#include "XXX/websocket_protocol.h"
#include "XXX/rawsocket_protocol.h"
#include <iostream>
using namespace XXX;
struct timeout_error : public std::runtime_error
{
timeout_error()
: std::runtime_error("timeout_error"){}
};
void make_connection()
{
auto __logger = logger::stdlog(std::cout,
logger::levels_upto(logger::eError), 0);
std::unique_ptr<kernel> the_kernel( new XXX::kernel({}, __logger) );
the_kernel->start();
std::promise<void> promise_on_close;
auto wconn = wamp_connector::create(
the_kernel.get(),
"10.0.0.0", "55555",
false,
[&promise_on_close](XXX::session_handle, bool is_open){
if (!is_open)
promise_on_close.set_value();
}
);
auto connect_future = wconn->get_future();
auto connect_status = connect_future.wait_for(std::chrono::milliseconds(50));
if (connect_status == std::future_status::timeout)
{
throw timeout_error();
}
else
{
throw std::runtime_error("call should have timed-out");
}
}
int run_test()
{
try
{
make_connection();
}
catch (timeout_error&)
{
// OK, this is what we expected
return 0;
}
return 1; // unexpected
}
int main()
{
try
{
for (int i =0; i < 100; i++)
{
std::cout << "."<< std::flush;
run_test();
}
return 0;
}
catch (std::exception& e)
{
std::cerr << "error: " << e.what() << std::endl;
return 1;
}
}
<commit_msg>additional test<commit_after>#include "XXX/kernel.h"
#include "XXX/topic.h"
#include "XXX/wamp_session.h"
#include "XXX/wamp_connector.h"
#include "XXX/websocket_protocol.h"
#include "XXX/rawsocket_protocol.h"
#include <iostream>
using namespace XXX;
enum test_outcome
{
e_expected,
e_unexpected
};
test_outcome throw_on_invalid_address()
{
kernel the_kernel( {}, logger::nolog() );
the_kernel.start();
auto wconn = wamp_connector::create(
&the_kernel,
"0.42.42.42", /* Invalid argument */
"55555",
false,
[](XXX::session_handle, bool){});
auto connect_future = wconn->get_future();
auto connect_status = connect_future.wait_for(std::chrono::milliseconds(50));
std::shared_ptr<wamp_session> session;
if (connect_status == std::future_status::ready)
try
{
session = connect_future.get();
}
catch (std::exception& e)
{
return e_expected;
}
return e_unexpected;
}
test_outcome timeout_for_unreachable_connect()
{
std::unique_ptr<kernel> the_kernel( new XXX::kernel({}, logger::nolog() ) );
the_kernel->start();
auto wconn = wamp_connector::create(
the_kernel.get(),
"10.255.255.1", "55555",
false,
[](XXX::session_handle, bool){});
auto connect_future = wconn->get_future();
auto connect_status = connect_future.wait_for(std::chrono::milliseconds(50));
if (connect_status == std::future_status::timeout)
return e_expected;
return e_unexpected;
}
#define TEST( X ) \
if ( X () != e_expected) \
{ \
std::cout << "FAIL for: " << #X << std::endl; \
result |= 1; \
}
/* Note, these tests will only succeed if the system has access to a network. */
int main()
{
int result = 0;
for (int i =0; i < 20; i++)
{
std::cout << "."<< std::flush;
TEST( throw_on_invalid_address );
TEST( timeout_for_unreachable_connect );
}
/* We let any uncaught exceptions (which are not expected) to terminate main,
* and cause test failure. */
return result;
}
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "geo_location.h"
using vespalib::geo::ZCurve;
namespace search::common {
namespace {
ZCurve::BoundingBox to_z(GeoLocation::Box box) {
return ZCurve::BoundingBox(box.x.low, box.x.high,
box.y.low, box.y.high);
}
GeoLocation::Box
adjust_bounding_box(GeoLocation::Box orig, GeoLocation::Point point, uint32_t radius, GeoLocation::Aspect x_aspect)
{
if (radius == GeoLocation::radius_inf) {
// only happens if GeoLocation is explicitly constructed with "infinite" radius
return orig;
}
uint32_t maxdx = radius;
if (x_aspect.active()) {
// x_aspect is a 32-bit fixed-point number in range [0,1]
// so this implements maxdx = ceil(radius/x_aspect)
uint64_t maxdx2 = ((static_cast<uint64_t>(radius) << 32) + 0xffffffffu) / x_aspect.multiplier;
if (maxdx2 >= 0xffffffffu) {
maxdx = 0xffffffffu;
} else {
maxdx = static_cast<uint32_t>(maxdx2);
}
}
// implied limits from radius and point:
int64_t implied_max_x = int64_t(point.x) + int64_t(maxdx);
int64_t implied_min_x = int64_t(point.x) - int64_t(maxdx);
int64_t implied_max_y = int64_t(point.y) + int64_t(radius);
int64_t implied_min_y = int64_t(point.y) - int64_t(radius);
int32_t max_x = orig.x.high;
int32_t min_x = orig.x.low;
int32_t max_y = orig.y.high;
int32_t min_y = orig.y.low;
if (implied_max_x < max_x) max_x = implied_max_x;
if (implied_min_x > min_x) min_x = implied_min_x;
if (implied_max_y < max_y) max_y = implied_max_y;
if (implied_min_y > min_y) min_y = implied_min_y;
return GeoLocation::Box{GeoLocation::Range{min_x, max_x},
GeoLocation::Range{min_y, max_y}};
}
} // namespace <unnamed>
GeoLocation::GeoLocation()
: has_point(false),
point{0, 0},
radius(radius_inf),
x_aspect(),
bounding_box(no_box),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(no_box))
{}
GeoLocation::GeoLocation(Point p)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(),
bounding_box(no_box),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(no_box))
{}
GeoLocation::GeoLocation(Point p, Aspect xa)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(xa),
bounding_box(no_box),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(no_box))
{}
GeoLocation::GeoLocation(Point p, uint32_t r)
: has_point(true),
point(p),
radius(r),
x_aspect(),
bounding_box(adjust_bounding_box(no_box, p, r, Aspect())),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Point p, uint32_t r, Aspect xa)
: has_point(true),
point(p),
radius(r),
x_aspect(xa),
bounding_box(adjust_bounding_box(no_box, p, r, xa)),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b)
: has_point(false),
point{0, 0},
radius(radius_inf),
x_aspect(),
bounding_box(b),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(),
bounding_box(b),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p, Aspect xa)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(xa),
bounding_box(b),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p, uint32_t r)
: has_point(true),
point(p),
radius(r),
x_aspect(),
bounding_box(adjust_bounding_box(b, p, r, Aspect())),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p, uint32_t r, Aspect xa)
: has_point(true),
point(p),
radius(r),
x_aspect(xa),
bounding_box(adjust_bounding_box(b, p, r, xa)),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
uint64_t GeoLocation::sq_distance_to(Point p) const {
if (has_point) {
uint64_t dx = (p.x > point.x) ? (p.x - point.x) : (point.x - p.x);
if (x_aspect.active()) {
// x_aspect is a 32-bit fixed-point number in range [0,1]
// this implements dx = (dx * x_aspect)
dx = (dx * x_aspect.multiplier) >> 32;
}
uint64_t dy = (p.y > point.y) ? (p.y - point.y) : (point.y - p.y);
return dx*dx + dy*dy;
}
return 0;
}
bool GeoLocation::inside_limit(Point p) const {
if (p.x < bounding_box.x.low) return false;
if (p.x > bounding_box.x.high) return false;
if (p.y < bounding_box.y.low) return false;
if (p.y > bounding_box.y.high) return false;
uint64_t sq_dist = sq_distance_to(p);
return sq_dist <= _sq_radius;
}
} // namespace search::common
<commit_msg>fix undefined behavior in geo distance<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "geo_location.h"
using vespalib::geo::ZCurve;
namespace search::common {
namespace {
uint64_t abs_diff(int32_t a, int32_t b) {
return (a > b)
? (int64_t(a) - int64_t(b))
: (int64_t(b) - int64_t(a));
}
ZCurve::BoundingBox to_z(GeoLocation::Box box) {
return ZCurve::BoundingBox(box.x.low, box.x.high,
box.y.low, box.y.high);
}
GeoLocation::Box
adjust_bounding_box(GeoLocation::Box orig, GeoLocation::Point point, uint32_t radius, GeoLocation::Aspect x_aspect)
{
if (radius == GeoLocation::radius_inf) {
// only happens if GeoLocation is explicitly constructed with "infinite" radius
return orig;
}
uint32_t maxdx = radius;
if (x_aspect.active()) {
// x_aspect is a 32-bit fixed-point number in range [0,1]
// so this implements maxdx = ceil(radius/x_aspect)
uint64_t maxdx2 = ((static_cast<uint64_t>(radius) << 32) + 0xffffffffu) / x_aspect.multiplier;
if (maxdx2 >= 0xffffffffu) {
maxdx = 0xffffffffu;
} else {
maxdx = static_cast<uint32_t>(maxdx2);
}
}
// implied limits from radius and point:
int64_t implied_max_x = int64_t(point.x) + int64_t(maxdx);
int64_t implied_min_x = int64_t(point.x) - int64_t(maxdx);
int64_t implied_max_y = int64_t(point.y) + int64_t(radius);
int64_t implied_min_y = int64_t(point.y) - int64_t(radius);
int32_t max_x = orig.x.high;
int32_t min_x = orig.x.low;
int32_t max_y = orig.y.high;
int32_t min_y = orig.y.low;
if (implied_max_x < max_x) max_x = implied_max_x;
if (implied_min_x > min_x) min_x = implied_min_x;
if (implied_max_y < max_y) max_y = implied_max_y;
if (implied_min_y > min_y) min_y = implied_min_y;
return GeoLocation::Box{GeoLocation::Range{min_x, max_x},
GeoLocation::Range{min_y, max_y}};
}
} // namespace <unnamed>
GeoLocation::GeoLocation()
: has_point(false),
point{0, 0},
radius(radius_inf),
x_aspect(),
bounding_box(no_box),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(no_box))
{}
GeoLocation::GeoLocation(Point p)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(),
bounding_box(no_box),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(no_box))
{}
GeoLocation::GeoLocation(Point p, Aspect xa)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(xa),
bounding_box(no_box),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(no_box))
{}
GeoLocation::GeoLocation(Point p, uint32_t r)
: has_point(true),
point(p),
radius(r),
x_aspect(),
bounding_box(adjust_bounding_box(no_box, p, r, Aspect())),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Point p, uint32_t r, Aspect xa)
: has_point(true),
point(p),
radius(r),
x_aspect(xa),
bounding_box(adjust_bounding_box(no_box, p, r, xa)),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b)
: has_point(false),
point{0, 0},
radius(radius_inf),
x_aspect(),
bounding_box(b),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(),
bounding_box(b),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p, Aspect xa)
: has_point(true),
point(p),
radius(radius_inf),
x_aspect(xa),
bounding_box(b),
_sq_radius(sq_radius_inf),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p, uint32_t r)
: has_point(true),
point(p),
radius(r),
x_aspect(),
bounding_box(adjust_bounding_box(b, p, r, Aspect())),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
GeoLocation::GeoLocation(Box b, Point p, uint32_t r, Aspect xa)
: has_point(true),
point(p),
radius(r),
x_aspect(xa),
bounding_box(adjust_bounding_box(b, p, r, xa)),
_sq_radius(uint64_t(r) * uint64_t(r)),
_z_bounding_box(to_z(bounding_box))
{}
uint64_t GeoLocation::sq_distance_to(Point p) const {
if (has_point) {
uint64_t dx = abs_diff(p.x, point.x);
if (x_aspect.active()) {
// x_aspect is a 32-bit fixed-point number in range [0,1]
// this implements dx = (dx * x_aspect)
dx = (dx * x_aspect.multiplier) >> 32;
}
uint64_t dy = abs_diff(p.y, point.y);
return dx*dx + dy*dy;
}
return 0;
}
bool GeoLocation::inside_limit(Point p) const {
if (p.x < bounding_box.x.low) return false;
if (p.x > bounding_box.x.high) return false;
if (p.y < bounding_box.y.low) return false;
if (p.y > bounding_box.y.high) return false;
uint64_t sq_dist = sq_distance_to(p);
return sq_dist <= _sq_radius;
}
} // namespace search::common
<|endoftext|> |
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/experimental/array.hpp>
#include <agency/experimental/span.hpp>
#include <type_traits>
#include <iterator>
namespace agency
{
namespace experimental
{
// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<typename Container::value_type> all(Container& c)
{
return span<typename Container::value_type>(c);
}
// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<const typename Container::value_type> all(const Container& c)
{
return span<const typename Container::value_type>(c);
}
template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<T,N> all(array<T,N>& a)
{
return span<T,N>(a);
}
template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<const T,N> all(const array<T,N>& a)
{
return span<const T,N>(a);
}
// spans are already views, so don't wrap them
// XXX maybe should put this in span.hpp
template<class ElementType, std::ptrdiff_t Extent>
__AGENCY_ANNOTATION
span<ElementType,Extent> all(span<ElementType,Extent> s)
{
return s;
}
template<class Iterator, class Sentinel = Iterator>
class range_view
{
public:
using iterator = Iterator;
using sentinel = Sentinel;
__AGENCY_ANNOTATION
range_view(iterator begin, sentinel end)
: begin_(begin),
end_(end)
{}
__AGENCY_ANNOTATION
iterator begin() const
{
return begin_;
}
__AGENCY_ANNOTATION
sentinel end() const
{
return end_;
}
// "drops" the first n elements of the range by advancing the begin iterator n times
__AGENCY_ANNOTATION
void drop(typename std::iterator_traits<iterator>::difference_type n)
{
begin_ += n;
}
private:
iterator begin_;
sentinel end_;
};
// range_views are already views, so don't wrap them
template<class Iterator, class Sentinel>
__AGENCY_ANNOTATION
range_view<Iterator,Sentinel> all(range_view<Iterator,Sentinel> v)
{
return v;
}
namespace detail
{
template<class Range>
using range_iterator_t = decltype(std::declval<Range*>()->begin());
template<class Range>
using range_sentinel_t = decltype(std::declval<Range*>()->end());
template<class Range>
using decay_range_iterator_t = range_iterator_t<typename std::decay<Range>::type>;
template<class Range>
using decay_range_sentinel_t = range_sentinel_t<typename std::decay<Range>::type>;
template<class Range>
using range_difference_t = typename std::iterator_traits<range_iterator_t<Range>>::difference_type;
template<class Range>
using range_value_t = typename std::iterator_traits<range_iterator_t<Range>>::value_type;
} // end detail
template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
make_range_view(Range&& rng)
{
return range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>(rng.begin(), rng.end());
}
// create a view of the given range and drop the first n elements from the view
template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
drop(Range&& rng, detail::range_difference_t<typename std::decay<Range>::type> n)
{
auto result = make_range_view(rng);
result.drop(n);
return result;
}
} // end experimental
} // end agency
<commit_msg>Add experimental::detail::decay_range_difference_t<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/experimental/array.hpp>
#include <agency/experimental/span.hpp>
#include <type_traits>
#include <iterator>
namespace agency
{
namespace experimental
{
// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<typename Container::value_type> all(Container& c)
{
return span<typename Container::value_type>(c);
}
// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<const typename Container::value_type> all(const Container& c)
{
return span<const typename Container::value_type>(c);
}
template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<T,N> all(array<T,N>& a)
{
return span<T,N>(a);
}
template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<const T,N> all(const array<T,N>& a)
{
return span<const T,N>(a);
}
// spans are already views, so don't wrap them
// XXX maybe should put this in span.hpp
template<class ElementType, std::ptrdiff_t Extent>
__AGENCY_ANNOTATION
span<ElementType,Extent> all(span<ElementType,Extent> s)
{
return s;
}
template<class Iterator, class Sentinel = Iterator>
class range_view
{
public:
using iterator = Iterator;
using sentinel = Sentinel;
__AGENCY_ANNOTATION
range_view(iterator begin, sentinel end)
: begin_(begin),
end_(end)
{}
__AGENCY_ANNOTATION
iterator begin() const
{
return begin_;
}
__AGENCY_ANNOTATION
sentinel end() const
{
return end_;
}
// "drops" the first n elements of the range by advancing the begin iterator n times
__AGENCY_ANNOTATION
void drop(typename std::iterator_traits<iterator>::difference_type n)
{
begin_ += n;
}
private:
iterator begin_;
sentinel end_;
};
// range_views are already views, so don't wrap them
template<class Iterator, class Sentinel>
__AGENCY_ANNOTATION
range_view<Iterator,Sentinel> all(range_view<Iterator,Sentinel> v)
{
return v;
}
namespace detail
{
template<class Range>
using range_iterator_t = decltype(std::declval<Range*>()->begin());
template<class Range>
using range_sentinel_t = decltype(std::declval<Range*>()->end());
template<class Range>
using range_difference_t = typename std::iterator_traits<range_iterator_t<Range>>::difference_type;
template<class Range>
using range_value_t = typename std::iterator_traits<range_iterator_t<Range>>::value_type;
template<class Range>
using decay_range_iterator_t = range_iterator_t<typename std::decay<Range>::type>;
template<class Range>
using decay_range_sentinel_t = range_sentinel_t<typename std::decay<Range>::type>;
template<class Range>
using decay_range_difference_t = range_difference_t<typename std::decay<Range>::type>;
} // end detail
template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
make_range_view(Range&& rng)
{
return range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>(rng.begin(), rng.end());
}
// create a view of the given range and drop the first n elements from the view
template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
drop(Range&& rng, detail::range_difference_t<typename std::decay<Range>::type> n)
{
auto result = make_range_view(rng);
result.drop(n);
return result;
}
} // end experimental
} // end agency
<|endoftext|> |
<commit_before>#include<iostream.h>
#include<conio.h>
#include<dos.h>
char s[3][3]={" "," "," "};
char p1[15],p2[15]="COMPUTER";
<commit_msg>Create board<commit_after>#include<iostream.h>
#include<conio.h>
#include<dos.h>
char s[3][3]={"123","456","789"};
char p1[15],p2[15]="COMPUTER";
void board()
{
clrscr();
cout<<"The block # sequence is as follows:-\n";
cout<<" | | "<<"\n";
cout<<" | | "<<"\n";
cout<<" "<<s[0][0]<<" | "<<s[0][1]<<" | "<<s[0][2]<<"\n";
cout<<" | | "<<"\n";
cout<<" ___________|___________|___________"<<"\n";
cout<<" | | "<<"\n";
cout<<" | | "<<"\n";
cout<<" "<<s[1][0]<<" | "<<s[1][1]<<" | "<<s[1][2]<<"\n";
cout<<" | | "<<"\n";
cout<<" ___________|___________|___________"<<"\n";
cout<<" | | "<<"\n";
cout<<" | | "<<"\n";
cout<<" "<<s[2][0]<<" | "<<s[2][1]<<" | "<<s[2][2]<<"\n";
cout<<" | | "<<"\n";
cout<<" | | "<<"\n\n\n\n\n\n";
}
void main()
{
board();
getch();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "SynchronousEventBeat.h"
namespace facebook {
namespace react {
SynchronousEventBeat::SynchronousEventBeat(
RunLoopObserver::Unique uiRunLoopObserver,
RuntimeExecutor runtimeExecutor)
: EventBeat({}),
uiRunLoopObserver_(std::move(uiRunLoopObserver)),
runtimeExecutor_(std::move(runtimeExecutor)) {
uiRunLoopObserver_->setDelegate(this);
uiRunLoopObserver_->enable();
}
void SynchronousEventBeat::activityDidChange(
RunLoopObserver::Delegate const *delegate,
RunLoopObserver::Activity activity) const noexcept {
assert(delegate == this);
lockExecutorAndBeat();
}
void SynchronousEventBeat::induce() const {
if (!this->isRequested_) {
return;
}
if (uiRunLoopObserver_->isOnRunLoopThread()) {
this->lockExecutorAndBeat();
}
}
void SynchronousEventBeat::lockExecutorAndBeat() const {
if (!this->isRequested_) {
return;
}
executeSynchronouslyOnSameThread_CAN_DEADLOCK(
runtimeExecutor_, [this](jsi::Runtime &runtime) { beat(runtime); });
}
} // namespace react
} // namespace facebook
<commit_msg>Fabric: Replace #import statement in SynchronousEventBeat (#29885)<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "SynchronousEventBeat.h"
namespace facebook {
namespace react {
SynchronousEventBeat::SynchronousEventBeat(
RunLoopObserver::Unique uiRunLoopObserver,
RuntimeExecutor runtimeExecutor)
: EventBeat({}),
uiRunLoopObserver_(std::move(uiRunLoopObserver)),
runtimeExecutor_(std::move(runtimeExecutor)) {
uiRunLoopObserver_->setDelegate(this);
uiRunLoopObserver_->enable();
}
void SynchronousEventBeat::activityDidChange(
RunLoopObserver::Delegate const *delegate,
RunLoopObserver::Activity activity) const noexcept {
assert(delegate == this);
lockExecutorAndBeat();
}
void SynchronousEventBeat::induce() const {
if (!this->isRequested_) {
return;
}
if (uiRunLoopObserver_->isOnRunLoopThread()) {
this->lockExecutorAndBeat();
}
}
void SynchronousEventBeat::lockExecutorAndBeat() const {
if (!this->isRequested_) {
return;
}
executeSynchronouslyOnSameThread_CAN_DEADLOCK(
runtimeExecutor_, [this](jsi::Runtime &runtime) { beat(runtime); });
}
} // namespace react
} // namespace facebook
<|endoftext|> |
<commit_before>#ifndef _RATIONAL_H
#define _RATIONAL_H
#include <cmath>
#include <cstddef>
#include <iosfwd>
#include <stdexcept>
#include <type_traits>
#include <limits>
#ifndef RATIONAL_NCONSTEXPR
#define CONSTEXPR constexpr
#else
#define CONSTEXPR /* not supported */
#endif
namespace rational {
struct NoReduceTag {};
struct DivideByZeroException : public std::runtime_error {
DivideByZeroException() noexcept :
runtime_error("Division by zero is undefined.")
{ }
};
struct OverflowException : public std::runtime_error {
OverflowException() noexcept :
runtime_error("Arithmetic operation resulted in an overflow.")
{ }
};
template<class T>
CONSTEXPR T cpow(const T base, unsigned const exponent) noexcept
{
return (exponent == 0) ? 1 : (base * pow(base, exponent-1));
}
template<class T>
CONSTEXPR unsigned pow10_cap(T x) noexcept
{
unsigned pow10 = 0;
x = x > T(0) ? x : -x;
do {
++pow10;
x /= 10;
} while(x > 1);
return pow10;
}
template<class T>
T gcd(T a, T b) noexcept {
if(a < T(0)) a = -a;
if(b < T(0)) b = -b;
while(b != T(0)) {
a %= b;
if(a == T(0)) {
return b;
}
b %= a;
}
return a;
}
template<class T>
class Ratio {
public:
static_assert(std::is_integral<T>::value, "Ratio<T>: T must meet the requirements of Integral");
CONSTEXPR Ratio() noexcept :
numer_(0),
denom_(1)
{ }
template<class U>
CONSTEXPR Ratio(const U u) noexcept :
Ratio(T(u), T(1), NoReduceTag())
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::Ratio<U>(const U): U must meet the requirements of Convertible to T.");
}
Ratio(const float u, const unsigned prec) :
Ratio(static_cast<std::ptrdiff_t>(u * cpow(10, prec)), cpow(10, prec))
{
if((u > 0 && u > this->numer_)
|| (u < 0 && u < this->numer_)) {
throw OverflowException();
}
}
Ratio(const T numer, const T denom) noexcept :
numer_(numer),
denom_(denom)
{
if(denom == T(0)) {
throw DivideByZeroException();
}
Ratio<T> ret(numer, denom, NoReduceTag());
ret.reduce();
*this = ret;
}
CONSTEXPR Ratio(const T numer, const T denom, NoReduceTag) noexcept :
numer_(numer),
denom_(denom)
{ }
CONSTEXPR Ratio(const Ratio<T>& rat) noexcept :
numer_(rat.numer_),
denom_(rat.denom_)
{ }
CONSTEXPR Ratio& operator=(const Ratio<T>& rat) noexcept
{
this->numer_ = rat.numer_;
this->denom_ = rat.denom_;
return *this;
}
template<class U>
CONSTEXPR Ratio(const Ratio<U>& rat) noexcept :
numer_(rat.numer_),
denom_(rat.denom_)
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::Ratio<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
}
template<class U>
Ratio& operator=(const Ratio<U>& rat) noexcept
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::operator=<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
this->numer_ = rat.numer_;
this->denom_ = rat.denom_;
return *this;
}
CONSTEXPR T to_integer() const noexcept
{
return (this->numer_ / this->denom_);
}
template<class Float = float>
CONSTEXPR Float to_float() const noexcept
{
static_assert(std::is_constructible<Float, T>::value,
"Ratio<T>::to_floating<Float>(): T must meet the requirements of Convertible to Float.");
return Float(Float(this->numer_) / Float(this->denom_));
}
const T& numer() const noexcept
{
return this->numer_;
}
const T& denom() const noexcept
{
return this->denom_;
}
bool is_integer() const noexcept
{
return this->denom_ == T(1);
}
void reduce() noexcept
{
T g = gcd(this->numer_, this->denom_);
this->numer_ = this->numer_ / g;
this->denom_ = this->denom_ / g;
if(this->denom_ < T(0)) {
this->numer_ = T(0) - this->numer_;
this->denom_ = T(0) - this->denom_;
}
}
Ratio<T> reduced() const noexcept
{
Ratio<T> ret(*this);
ret.reduce();
return ret;
}
Ratio<T> floor() const noexcept
{
if(*this < Ratio<T>(0)) {
T one (1);
return Ratio<T>((this->numer_ - this->denom_ + one) / this->denom_);
} else {
return Ratio<T>(this->numer_ / this->denom_);
}
}
Ratio<T> ceil() const noexcept
{
if(*this < Ratio<T>(0)) {
return Ratio<T>(this->numer_ / this->denom_);
} else {
T one (1);
return Ratio<T>((this->numer_ + this->denom_ - one) / this->denom_);
}
}
Ratio<T> round() const noexcept
{
const Ratio<T> zero(0);
const T one(1);
const T two(one + one);
Ratio<T> fractional = this->fract();
if(fractional < zero) {
fractional = zero - fractional;
}
const bool half_or_larger;
if(fractional.denom() % 2 == 0) {
half_or_larger = fractional.numer_ >= fractional.denom_ / two;
} else {
half_or_larger = fractional.numer_ >= (fractional.denom_ / two) + one;
}
if(half_or_larger) {
Ratio<T> one(1);
if(*this > Ratio<T>(0)) {
return this->trunc() + one;
} else {
return this->trunc() - one;
}
} else {
return this->trunc();
}
}
Ratio<T> trunc() const noexcept
{
return Ratio<T>(this->numer_ / this->denom_);
}
Ratio<T> fract() const noexcept
{
return Ratio<T>(this->numer_ % this->denom_, this->denom_, NoReduceTag());
}
Ratio<T> pow(const Ratio<T>& r, int expon) const noexcept
{
if(expon == 0) {
return Ratio<T>(1);
} else if(expon < 0) {
return std::pow(recip(r), -expon);
} else {
return Ratio<T>(std::pow(r.numer(), expon), std::pow(r.numer(), expon));
}
}
bool is_zero() const noexcept
{
return (this->numer_ == 0);
}
bool is_positive() const noexcept
{
return (this->numer_ > 0);
}
bool is_negative() const noexcept
{
return (this->numer_ < 0);
}
static CONSTEXPR Ratio<T> zero() noexcept
{
return Ratio<T>(0, 1, NoReduceTag());
}
static CONSTEXPR Ratio<T> one() noexcept
{
return Ratio<T>(1, 1, NoReduceTag());
}
static CONSTEXPR Ratio<T> pi() noexcept
{
return Ratio<T>(6283, 2000, NoReduceTag());
}
Ratio<T> abs() const noexcept
{
return (this->is_positive() || this->is_zero() ? *this : -*this);
}
Ratio<T> abs_sub(const Ratio<T>& rhs) const noexcept
{
return abs(*this - rhs);
}
T signum() const noexcept
{
if(this->is_zero()) {
return T(0);
} else if(this->is_positive()) {
return T(1);
} else {
return T(-1);
}
}
template<class U>
explicit CONSTEXPR operator Ratio<U>() const noexcept
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::operator Ratio<U>(): T must meet the requirements of ImplicitlyConvertible to U.");
return Ratio<U>(U(this->numer_), U(this->denom_), NoReduceTag());
}
template<class U>
friend class Ratio;
private:
T numer_;
T denom_;
};
template<class T>
Ratio<T> make_ratio(const T& num) noexcept
{
return Ratio<T>(num);
}
template<class T>
Ratio<T> make_ratio(const T& numer, const T& denom) noexcept
{
return Ratio<T>(numer, denom);
}
template<class T>
Ratio<T> operator+(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.denom()) + (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator-(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.denom()) - (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator%(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.denom()) % (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator*(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator/(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return make_ratio((lhs.numer() * rhs.denom()), (lhs.denom() * rhs.numer()));
}
template<class T>
Ratio<T> operator+=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs + rhs;
}
template<class T>
Ratio<T> operator-=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs - rhs;
}
template<class T>
Ratio<T> operator*=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs * rhs;
}
template<class T>
Ratio<T> operator/=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs / rhs;
}
template<class T>
Ratio<T> operator%=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs % rhs;
}
template<class T>
Ratio<T> operator+(const Ratio<T>& rat) noexcept
{
return Ratio<T>(rat);
}
template<class T>
Ratio<T> operator-(const Ratio<T>& rat) noexcept
{
return Ratio<T>(-rat.numer(), rat.denom(), NoReduceTag());
}
template<class T>
bool operator==(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return (lhs.numer() * lhs.denom()) == (rhs.numer() * rhs.denom());
}
template<class T>
bool operator!=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return !(lhs == rhs);
}
template<class T>
bool operator>(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return (lhs.numer() * lhs.denom()) > (rhs.numer() * rhs.denom());
}
template<class T>
bool operator<(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return (rhs > lhs);
}
template<class T>
bool operator<=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return !(lhs > rhs);
}
template<class T>
bool operator>=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return !(lhs < rhs);
}
template<class T>
Ratio<T>& operator++(Ratio<T>& rat) noexcept
{
return rat = rat + Ratio<T>(1);;
}
template<class T>
Ratio<T>& operator--(Ratio<T>& rat) noexcept
{
return rat = rat - Ratio<T>(1);
}
template<class T>
Ratio<T> operator++(Ratio<T>& rat, int) noexcept
{
Ratio<T> cpy = rat;
++rat;
return cpy;
}
template<class T>
Ratio<T> operator--(Ratio<T>& rat, int) noexcept
{
Ratio<T> cpy = rat;
--rat;
return cpy;
}
typedef Ratio<std::ptrdiff_t> Rational;
typedef Ratio<std::int32_t> Rational32;
typedef Ratio<std::int64_t> Rational64;
namespace literals {
CONSTEXPR Rational operator"" _m(const unsigned long long int n) noexcept
{
return Rational(n, 1, NoReduceTag());
}
CONSTEXPR Rational operator"" _M(const unsigned long long int n) noexcept
{
return Rational(n, 1, NoReduceTag());
}
} // namespace literals
template<class T>
std::ostream& operator<<(std::ostream& os, Ratio<T> x)
{
return os << x.numer() << '/' << x.denom();
}
template<class T>
std::istream& operator>>(std::istream& is, Ratio<T>& x)
{
T numer;
T denom;
std::scanf("%ld/%ld", &numer, &denom);
x = Ratio<T>(numer, denom);
return is;
}
} // namespace rational
#endif<commit_msg>Changed Ratio<T>(float val, unsigned int prec) to from_float and renamed literal overloads to _r and _R respectively.<commit_after>#ifndef _RATIONAL_H
#define _RATIONAL_H
#include <cmath>
#include <cstddef>
#include <iosfwd>
#include <stdexcept>
#include <type_traits>
#include <limits>
#ifndef RATIONAL_NCONSTEXPR
#define CONSTEXPR constexpr
#else
#define CONSTEXPR /* not supported */
#endif
namespace rational {
struct NoReduceTag {};
struct DivideByZeroException : public std::runtime_error {
DivideByZeroException() noexcept :
runtime_error("Division by zero is undefined.")
{ }
};
struct OverflowException : public std::runtime_error {
OverflowException() noexcept :
runtime_error("Arithmetic operation resulted in an overflow.")
{ }
};
template<class T>
CONSTEXPR T cpow(const T base, unsigned const exponent) noexcept
{
return (exponent == 0) ? 1 : (base * pow(base, exponent-1));
}
template<class T>
CONSTEXPR unsigned pow10_cap(T x) noexcept
{
unsigned pow10 = 0;
x = x > T(0) ? x : -x;
do {
++pow10;
x /= 10;
} while(x > 1);
return pow10;
}
template<class T>
T gcd(T a, T b) noexcept {
if(a < T(0)) a = -a;
if(b < T(0)) b = -b;
while(b != T(0)) {
a %= b;
if(a == T(0)) {
return b;
}
b %= a;
}
return a;
}
template<class T>
class Ratio {
public:
static_assert(std::is_integral<T>::value, "Ratio<T>: T must meet the requirements of Integral");
CONSTEXPR Ratio() noexcept :
numer_(0),
denom_(1)
{ }
template<class U>
CONSTEXPR Ratio(const U& u) noexcept :
Ratio(T(u), T(1), NoReduceTag())
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::Ratio<U>(const U): U must meet the requirements of Convertible to T.");
}
Ratio(const T& numer, const T& denom) noexcept :
numer_(numer),
denom_(denom)
{
if(denom == T(0)) {
throw DivideByZeroException();
}
Ratio<T> ret(numer, denom, NoReduceTag());
ret.reduce();
*this = ret;
}
CONSTEXPR Ratio(const T& numer, const T& denom, NoReduceTag) noexcept :
numer_(numer),
denom_(denom)
{ }
CONSTEXPR Ratio(const Ratio<T>& rat) noexcept :
numer_(rat.numer_),
denom_(rat.denom_)
{ }
CONSTEXPR Ratio& operator=(const Ratio<T>& rat) noexcept
{
this->numer_ = rat.numer_;
this->denom_ = rat.denom_;
return *this;
}
template<class U>
CONSTEXPR Ratio(const Ratio<U>& rat) noexcept :
numer_(rat.numer_),
denom_(rat.denom_)
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::Ratio<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
}
template<class U>
Ratio& operator=(const Ratio<U>& rat) noexcept
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::operator=<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
this->numer_ = rat.numer_;
this->denom_ = rat.denom_;
return *this;
}
CONSTEXPR T to_integer() const noexcept
{
return (this->numer_ / this->denom_);
}
template<class Float = float>
CONSTEXPR Float to_float() const noexcept
{
static_assert(std::is_constructible<Float, T>::value,
"Ratio<T>::to_floating<Float>(): T must meet the requirements of Convertible to Float.");
return Float(Float(this->numer_) / Float(this->denom_));
}
template<class Float = float>
Ratio from_float(const Float u&, const unsigned prec)
{
Ratio rat (T(u * cpow(10, prec)), T(cpow(10, prec)));
if((u > 0 && u > rat.numer_)
|| (u < 0 && u < rat.numer_)) {
throw OverflowException();
}
return rat;
}
const T& numer() const noexcept
{
return this->numer_;
}
const T& denom() const noexcept
{
return this->denom_;
}
bool is_integer() const noexcept
{
return this->denom_ == T(1);
}
void reduce() noexcept
{
T g = gcd(this->numer_, this->denom_);
this->numer_ = this->numer_ / g;
this->denom_ = this->denom_ / g;
if(this->denom_ < T(0)) {
this->numer_ = T(0) - this->numer_;
this->denom_ = T(0) - this->denom_;
}
}
Ratio<T> reduced() const noexcept
{
Ratio<T> ret(*this);
ret.reduce();
return ret;
}
Ratio<T> floor() const noexcept
{
if(*this < Ratio<T>(0)) {
T one (1);
return Ratio<T>((this->numer_ - this->denom_ + one) / this->denom_);
} else {
return Ratio<T>(this->numer_ / this->denom_);
}
}
Ratio<T> ceil() const noexcept
{
if(*this < Ratio<T>(0)) {
return Ratio<T>(this->numer_ / this->denom_);
} else {
T one (1);
return Ratio<T>((this->numer_ + this->denom_ - one) / this->denom_);
}
}
Ratio<T> round() const noexcept
{
const Ratio<T> zero(0);
const T one(1);
const T two(one + one);
Ratio<T> fractional = this->fract();
if(fractional < zero) {
fractional = zero - fractional;
}
const bool half_or_larger;
if(fractional.denom() % 2 == 0) {
half_or_larger = fractional.numer_ >= fractional.denom_ / two;
} else {
half_or_larger = fractional.numer_ >= (fractional.denom_ / two) + one;
}
if(half_or_larger) {
Ratio<T> one(1);
if(*this > Ratio<T>(0)) {
return this->trunc() + one;
} else {
return this->trunc() - one;
}
} else {
return this->trunc();
}
}
Ratio<T> trunc() const noexcept
{
return Ratio<T>(this->numer_ / this->denom_);
}
Ratio<T> fract() const noexcept
{
return Ratio<T>(this->numer_ % this->denom_, this->denom_, NoReduceTag());
}
Ratio<T> pow(const Ratio<T>& r, int expon) const noexcept
{
if(expon == 0) {
return Ratio<T>(1);
} else if(expon < 0) {
return std::pow(recip(r), -expon);
} else {
return Ratio<T>(std::pow(r.numer(), expon), std::pow(r.numer(), expon));
}
}
bool is_zero() const noexcept
{
return (this->numer_ == 0);
}
bool is_positive() const noexcept
{
return (this->numer_ > 0);
}
bool is_negative() const noexcept
{
return (this->numer_ < 0);
}
static CONSTEXPR Ratio<T> zero() noexcept
{
return Ratio<T>(0, 1, NoReduceTag());
}
static CONSTEXPR Ratio<T> one() noexcept
{
return Ratio<T>(1, 1, NoReduceTag());
}
static CONSTEXPR Ratio<T> pi() noexcept
{
return Ratio<T>(6283, 2000, NoReduceTag());
}
Ratio<T> abs() const noexcept
{
return (this->is_positive() || this->is_zero() ? *this : -*this);
}
Ratio<T> abs_sub(const Ratio<T>& rhs) const noexcept
{
return abs(*this - rhs);
}
T signum() const noexcept
{
if(this->is_zero()) {
return T(0);
} else if(this->is_positive()) {
return T(1);
} else {
return T(-1);
}
}
template<class U>
explicit CONSTEXPR operator Ratio<U>() const noexcept
{
static_assert(std::is_convertible<U, T>::value,
"Ratio<T>::operator Ratio<U>(): T must meet the requirements of ImplicitlyConvertible to U.");
return Ratio<U>(U(this->numer_), U(this->denom_), NoReduceTag());
}
template<class U>
friend class Ratio;
private:
T numer_;
T denom_;
};
template<class T>
Ratio<T> make_ratio(const T& num) noexcept
{
return Ratio<T>(num);
}
template<class T>
Ratio<T> make_ratio(const T& numer, const T& denom) noexcept
{
return Ratio<T>(numer, denom);
}
template<class T>
Ratio<T> operator+(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.denom()) + (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator-(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.denom()) - (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator%(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.denom()) % (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator*(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return Ratio<T>((lhs.numer() * rhs.numer()), (lhs.denom() * rhs.denom()));
}
template<class T>
Ratio<T> operator/(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return make_ratio((lhs.numer() * rhs.denom()), (lhs.denom() * rhs.numer()));
}
template<class T>
Ratio<T> operator+=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs + rhs;
}
template<class T>
Ratio<T> operator-=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs - rhs;
}
template<class T>
Ratio<T> operator*=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs * rhs;
}
template<class T>
Ratio<T> operator/=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs / rhs;
}
template<class T>
Ratio<T> operator%=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return lhs = lhs % rhs;
}
template<class T>
Ratio<T> operator+(const Ratio<T>& rat) noexcept
{
return Ratio<T>(rat);
}
template<class T>
Ratio<T> operator-(const Ratio<T>& rat) noexcept
{
return Ratio<T>(-rat.numer(), rat.denom(), NoReduceTag());
}
template<class T>
bool operator==(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return (lhs.numer() * lhs.denom()) == (rhs.numer() * rhs.denom());
}
template<class T>
bool operator!=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return !(lhs == rhs);
}
template<class T>
bool operator>(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return (lhs.numer() * lhs.denom()) > (rhs.numer() * rhs.denom());
}
template<class T>
bool operator<(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return (rhs > lhs);
}
template<class T>
bool operator<=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return !(lhs > rhs);
}
template<class T>
bool operator>=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
{
return !(lhs < rhs);
}
template<class T>
Ratio<T>& operator++(Ratio<T>& rat) noexcept
{
return rat = rat + Ratio<T>(1);;
}
template<class T>
Ratio<T>& operator--(Ratio<T>& rat) noexcept
{
return rat = rat - Ratio<T>(1);
}
template<class T>
Ratio<T> operator++(Ratio<T>& rat, int) noexcept
{
Ratio<T> cpy = rat;
++rat;
return cpy;
}
template<class T>
Ratio<T> operator--(Ratio<T>& rat, int) noexcept
{
Ratio<T> cpy = rat;
--rat;
return cpy;
}
typedef Ratio<std::ptrdiff_t> Rational;
typedef Ratio<std::int32_t> Rational32;
typedef Ratio<std::int64_t> Rational64;
namespace literals {
CONSTEXPR Rational operator"" _r(const unsigned long long int n) noexcept
{
return Rational(n, 1, NoReduceTag());
}
CONSTEXPR Rational operator"" _R(const unsigned long long int n) noexcept
{
return Rational(n, 1, NoReduceTag());
}
} // namespace literals
template<class T>
std::ostream& operator<<(std::ostream& os, Ratio<T> x)
{
return os << x.numer() << '/' << x.denom();
}
template<class T>
std::istream& operator>>(std::istream& is, Ratio<T>& x)
{
T numer;
T denom;
std::scanf("%ld/%ld", &numer, &denom);
x = Ratio<T>(numer, denom);
return is;
}
} // namespace rational
#endif<|endoftext|> |
<commit_before>#include "cnn/devices.h"
#include <iostream>
#include "cnn/cuda.h"
using namespace std;
namespace cnn {
Device::~Device() {}
#if HAVE_CUDA
Device_GPU::Device_GPU(int mb, int device_id) :
Device(DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) {
CUDA_CHECK(cudaSetDevice(device_id));
CUBLAS_CHECK(cublasCreate(&cublas_handle));
CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE));
kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float));
kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float));
kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float));
float minusone = -1;
CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice));
float one = 1;
CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice));
float zero = 0;
CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice));
// this is the big memory allocation
size_t byte_count = (size_t)mb << 20;
fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters
//fxs = new AlignedMemoryPool(mb << 20, mem); // memory for node values
//dEdfs = new AlignedMemoryPool(mb << 20, mem); // memory for node gradients
//ps = new AlignedMemoryPool(mb << 20, mem); // memory for parameters
}
Device_GPU::~Device_GPU() {}
#endif
// TODO we should be able to configure this carefully with a configuration
// script
// CPU -- 0 params
// -- 50mb fxs
// -- 50mb dEdfx
Device_CPU::Device_CPU(int mb, bool shared) :
Device(DeviceType::CPU, &cpu_mem), shmem(mem) {
if (shared) shmem = new SharedAllocator();
kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float));
*kSCALAR_MINUSONE = -1;
kSCALAR_ONE = (float*) mem->malloc(sizeof(float));
*kSCALAR_ONE = 1;
kSCALAR_ZERO = (float*) mem->malloc(sizeof(float));
*kSCALAR_ZERO = 0;
// this is the big memory allocation: the pools
size_t byte_count = (size_t)mb << 20;
fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters
//fxs = new AlignedMemoryPool(mb << 20, mem); // memory for node values
//dEdfs = new AlignedMemoryPool(mb << 20, mem); // memory for node gradients
//ps = new AlignedMemoryPool(mb << 20, shmem); // memory for parameters
}
Device_CPU::~Device_CPU() {}
} // namespace cnn
<commit_msg>Removed commented out lines<commit_after>#include "cnn/devices.h"
#include <iostream>
#include "cnn/cuda.h"
using namespace std;
namespace cnn {
Device::~Device() {}
#if HAVE_CUDA
Device_GPU::Device_GPU(int mb, int device_id) :
Device(DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) {
CUDA_CHECK(cudaSetDevice(device_id));
CUBLAS_CHECK(cublasCreate(&cublas_handle));
CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE));
kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float));
kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float));
kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float));
float minusone = -1;
CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice));
float one = 1;
CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice));
float zero = 0;
CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice));
// this is the big memory allocation
size_t byte_count = (size_t)mb << 20;
fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters
}
Device_GPU::~Device_GPU() {}
#endif
// TODO we should be able to configure this carefully with a configuration
// script
// CPU -- 0 params
// -- 50mb fxs
// -- 50mb dEdfx
Device_CPU::Device_CPU(int mb, bool shared) :
Device(DeviceType::CPU, &cpu_mem), shmem(mem) {
if (shared) shmem = new SharedAllocator();
kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float));
*kSCALAR_MINUSONE = -1;
kSCALAR_ONE = (float*) mem->malloc(sizeof(float));
*kSCALAR_ONE = 1;
kSCALAR_ZERO = (float*) mem->malloc(sizeof(float));
*kSCALAR_ZERO = 0;
// this is the big memory allocation: the pools
size_t byte_count = (size_t)mb << 20;
fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters
}
Device_CPU::~Device_CPU() {}
} // namespace cnn
<|endoftext|> |
<commit_before>#ifndef UNIT_CONFIG_HPP_
#define UNIT_CONFIG_HPP_
namespace unit_config {
const float DT = 0.001;
const double PI = 3.14159265358979323846;
// Maximum angular position in the roll and pitch axes (rad)
const float MAX_PITCH_ROLL_POS = 30.0 * PI / 180.0;
// Maximum angular velocity in the roll and pitch axes (rad/s)
const float MAX_PITCH_ROLL_VEL = 100.0 * PI / 180.0;
// Maximum angular acceleration (rad/s^2)
const float MAX_PITCH_ROLL_ACC = 4.0; // TODO: calculate properly
// Sensor offsets
const float GYR_X_OFFSET = 0.0;
const float GYR_Y_OFFSET = 0.0;
const float GYR_Z_OFFSET = 0.0;
const float ACC_X_OFFSET = 0.000;
const float ACC_Y_OFFSET = 0.012;
const float ACC_Z_OFFSET = -0.035;
const float ACCH_X_OFFSET = 0.0;
const float ACCH_Y_OFFSET = 0.0;
const float ACCH_Z_OFFSET = 0.0;
// Initial angular position controller gains
const float ANGPOS_X_KP = 1.0;
const float ANGPOS_X_KI = 0.0;
const float ANGPOS_X_KD = 0.0;
const float ANGPOS_Y_KP = 1.0;
const float ANGPOS_Y_KI = 0.0;
const float ANGPOS_Y_KD = 0.0;
const float ANGPOS_Z_KP = 1.0;
const float ANGPOS_Z_KI = 0.0;
const float ANGPOS_Z_KD = 0.0;
// Initial angular velocity controller gains
const float ANGVEL_X_KP = 1.0;
const float ANGVEL_X_KI = 0.0;
const float ANGVEL_X_KD = 0.0;
const float ANGVEL_Y_KP = 1.0;
const float ANGVEL_Y_KI = 0.0;
const float ANGVEL_Y_KD = 0.0;
const float ANGVEL_Z_KP = 1.0;
const float ANGVEL_Z_KI = 0.0;
const float ANGVEL_Z_KD = 0.0;
// Initial angular acceleration controller gains
const float ANGACC_X_KP = 1.0;
const float ANGACC_X_KI = 0.0;
const float ANGACC_X_KD = 0.0;
const float ANGACC_Y_KP = 1.0;
const float ANGACC_Y_KI = 0.0;
const float ANGACC_Y_KD = 0.0;
const float ANGACC_Z_KP = 1.0;
const float ANGACC_Z_KI = 0.0;
const float ANGACC_Z_KD = 0.0;
}
#endif // UNIT_CONFIG_HPP_
<commit_msg>Calibrate celestep2 accel.<commit_after>#ifndef UNIT_CONFIG_HPP_
#define UNIT_CONFIG_HPP_
namespace unit_config {
const float DT = 0.001;
const double PI = 3.14159265358979323846;
// Maximum angular position in the roll and pitch axes (rad)
const float MAX_PITCH_ROLL_POS = 30.0 * PI / 180.0;
// Maximum angular velocity in the roll and pitch axes (rad/s)
const float MAX_PITCH_ROLL_VEL = 100.0 * PI / 180.0;
// Maximum angular acceleration (rad/s^2)
const float MAX_PITCH_ROLL_ACC = 4.0; // TODO: calculate properly
// Sensor offsets
const float GYR_X_OFFSET = 0.0;
const float GYR_Y_OFFSET = 0.0;
const float GYR_Z_OFFSET = 0.0;
const float ACC_X_OFFSET = 0.011;
const float ACC_Y_OFFSET = -0.018;
const float ACC_Z_OFFSET = -0.240;
const float ACCH_X_OFFSET = 0.0;
const float ACCH_Y_OFFSET = 0.0;
const float ACCH_Z_OFFSET = 0.0;
// Initial angular position controller gains
const float ANGPOS_X_KP = 1.0;
const float ANGPOS_X_KI = 0.0;
const float ANGPOS_X_KD = 0.0;
const float ANGPOS_Y_KP = 1.0;
const float ANGPOS_Y_KI = 0.0;
const float ANGPOS_Y_KD = 0.0;
const float ANGPOS_Z_KP = 1.0;
const float ANGPOS_Z_KI = 0.0;
const float ANGPOS_Z_KD = 0.0;
// Initial angular velocity controller gains
const float ANGVEL_X_KP = 1.0;
const float ANGVEL_X_KI = 0.0;
const float ANGVEL_X_KD = 0.0;
const float ANGVEL_Y_KP = 1.0;
const float ANGVEL_Y_KI = 0.0;
const float ANGVEL_Y_KD = 0.0;
const float ANGVEL_Z_KP = 1.0;
const float ANGVEL_Z_KI = 0.0;
const float ANGVEL_Z_KD = 0.0;
// Initial angular acceleration controller gains
const float ANGACC_X_KP = 1.0;
const float ANGACC_X_KI = 0.0;
const float ANGACC_X_KD = 0.0;
const float ANGACC_Y_KP = 1.0;
const float ANGACC_Y_KI = 0.0;
const float ANGACC_Y_KD = 0.0;
const float ANGACC_Z_KP = 1.0;
const float ANGACC_Z_KI = 0.0;
const float ANGACC_Z_KD = 0.0;
}
#endif // UNIT_CONFIG_HPP_
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Mustafa Serdar Sanli
// Copyright (c) 2015 Markus Kuhn
//
// 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.
// Tests cases for
// "UTF-8 decoder capability and stress test"
// authored by Markus Kuhn
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
//
// a copy of the file can be found under tests/doc/
#include <iostream>
#include "lib/Common.hpp"
#define CATCH_CONFIG_MAIN
#include "third_party/catch.hpp"
using namespace std;
#define PARSE(data) ParseJsonString(reinterpret_cast<const char*>(data), \
reinterpret_cast<const char*>(data) + sizeof(data) )
string ParseJsonString(const char *beg, const char *end)
{
string out;
QuantumJsonImpl__::Parser<const char *> p(beg, end);
p.ParseValueInto(out);
if (p.errorCode != QuantumJsonImpl__::ErrorCode::NoError)
{
throw p.errorCode;
}
return out;
}
TEST_CASE("Case 1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5,
'"', };
string out = PARSE(input);
REQUIRE( out == u8"κόσμε" );
}
TEST_CASE("Case 2.1.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x00,
'"', };
// ErrorCode::ControlCharacterInString;
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 2.1.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xc2, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u0080" );
}
TEST_CASE("Case 2.1.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xe0, 0xa0, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u0800" );
}
TEST_CASE("Case 2.1.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf0, 0x90, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U00010000" );
}
TEST_CASE("Case 2.1.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf8, 0x88, 0x80, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U00200000" );
}
TEST_CASE("Case 2.1.6", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xfc, 0x84, 0x80, 0x80, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U04000000" );
}
TEST_CASE("Case 2.2.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x7f,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u007f" );
}
TEST_CASE("Case 2.2.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xdf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u07ff" );
}
TEST_CASE("Case 2.2.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xef, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\uffff" );
}
TEST_CASE("Case 2.2.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf7, 0xbf, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U001fffff" );
}
TEST_CASE("Case 2.2.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xfb, 0xbf, 0xbf, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U03ffffff" );
}
TEST_CASE("Case 2.2.6", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U7fffffff" );
}
TEST_CASE("Case 2.3.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xed, 0x9f, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\ud7ff" );
}
TEST_CASE("Case 2.3.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xee, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\ue000" );
}
TEST_CASE("Case 2.3.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xef, 0xbf, 0xbd,
'"', };
string out = PARSE(input);
REQUIRE( out == "\ufffd" );
}
TEST_CASE("Case 2.3.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf4, 0x8f, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U0010FFFF" );
}
TEST_CASE("Case 2.3.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf4, 0x90, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U00110000" );
}
// TODO Add case 3.1.1
// TODO Add case 3.1.2
// TODO Add case 3.1.3
// TODO Add case 3.1.4
// TODO Add case 3.1.5
// TODO Add case 3.1.6
// TODO Add case 3.1.7
// TODO Add case 3.1.8
// TODO Add case 3.1.9
// TODO Add case 3.2.1
// TODO Add case 3.2.2
// TODO Add case 3.2.3
// TODO Add case 3.2.4
// TODO Add case 3.2.5
// TODO Add case 3.3.1
// TODO Add case 3.3.2
// TODO Add case 3.3.3
// TODO Add case 3.3.4
// TODO Add case 3.3.5
// TODO Add case 3.3.6
// TODO Add case 3.3.7
// TODO Add case 3.3.8
// TODO Add case 3.3.9
// TODO Add case 3.3.10
// TODO Add case 3.4
// TODO Add case 3.5.1
// TODO Add case 3.5.2
// TODO Add case 3.5.3
// TODO Add case 4.1.1
// TODO Add case 4.1.2
// TODO Add case 4.1.3
// TODO Add case 4.1.4
// TODO Add case 4.1.5
// TODO Add case 4.2.1
// TODO Add case 4.2.2
// TODO Add case 4.2.3
// TODO Add case 4.2.4
// TODO Add case 4.2.5
// TODO Add case 4.3.1
// TODO Add case 4.3.2
// TODO Add case 4.3.3
// TODO Add case 4.3.4
// TODO Add case 4.3.5
// TODO Add case 5.1.1
// TODO Add case 5.1.2
// TODO Add case 5.1.3
// TODO Add case 5.1.4
// TODO Add case 5.1.5
// TODO Add case 5.1.6
// TODO Add case 5.1.7
// TODO Add case 5.2.1
// TODO Add case 5.2.2
// TODO Add case 5.2.3
// TODO Add case 5.2.4
// TODO Add case 5.2.5
// TODO Add case 5.2.6
// TODO Add case 5.2.7
// TODO Add case 5.2.8
// TODO Add case 5.3.1
// TODO Add case 5.3.2
// TODO Add case 5.3.3
// TODO Add case 5.3.4
<commit_msg>Add cases 3.1.x<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Mustafa Serdar Sanli
// Copyright (c) 2015 Markus Kuhn
//
// 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.
// Tests cases for
// "UTF-8 decoder capability and stress test"
// authored by Markus Kuhn
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
//
// a copy of the file can be found under tests/doc/
#include <iostream>
#include "lib/Common.hpp"
#define CATCH_CONFIG_MAIN
#include "third_party/catch.hpp"
using namespace std;
#define PARSE(data) ParseJsonString(reinterpret_cast<const char*>(data), \
reinterpret_cast<const char*>(data) + sizeof(data) )
string ParseJsonString(const char *beg, const char *end)
{
string out;
QuantumJsonImpl__::Parser<const char *> p(beg, end);
p.ParseValueInto(out);
if (p.errorCode != QuantumJsonImpl__::ErrorCode::NoError)
{
throw p.errorCode;
}
return out;
}
TEST_CASE("Case 1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5,
'"', };
string out = PARSE(input);
REQUIRE( out == u8"κόσμε" );
}
TEST_CASE("Case 2.1.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x00,
'"', };
// ErrorCode::ControlCharacterInString;
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 2.1.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xc2, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u0080" );
}
TEST_CASE("Case 2.1.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xe0, 0xa0, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u0800" );
}
TEST_CASE("Case 2.1.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf0, 0x90, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U00010000" );
}
TEST_CASE("Case 2.1.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf8, 0x88, 0x80, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U00200000" );
}
TEST_CASE("Case 2.1.6", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xfc, 0x84, 0x80, 0x80, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U04000000" );
}
TEST_CASE("Case 2.2.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x7f,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u007f" );
}
TEST_CASE("Case 2.2.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xdf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\u07ff" );
}
TEST_CASE("Case 2.2.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xef, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\uffff" );
}
TEST_CASE("Case 2.2.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf7, 0xbf, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U001fffff" );
}
TEST_CASE("Case 2.2.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xfb, 0xbf, 0xbf, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U03ffffff" );
}
TEST_CASE("Case 2.2.6", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U7fffffff" );
}
TEST_CASE("Case 2.3.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xed, 0x9f, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\ud7ff" );
}
TEST_CASE("Case 2.3.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xee, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\ue000" );
}
TEST_CASE("Case 2.3.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xef, 0xbf, 0xbd,
'"', };
string out = PARSE(input);
REQUIRE( out == "\ufffd" );
}
TEST_CASE("Case 2.3.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf4, 0x8f, 0xbf, 0xbf,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U0010FFFF" );
}
TEST_CASE("Case 2.3.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xf4, 0x90, 0x80, 0x80,
'"', };
string out = PARSE(input);
REQUIRE( out == "\U00110000" );
}
TEST_CASE("Case 3.1.1", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.2", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0xbf,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.3", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0xbf,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.4", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0xbf, 0x80,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.5", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0xbf, 0x80, 0xbf,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.6", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0xbf, 0x80, 0xbf, 0x80,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.7", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0xbf, 0x80, 0xbf, 0x80, 0xbf,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.8", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0xbf, 0x80, 0xbf, 0x80, 0xbf, 0x80,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
TEST_CASE("Case 3.1.9", "[utf8,decoder]")
{
unsigned char input[] = { '"',
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
'"', };
REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}
// TODO Add case 3.2.1
// TODO Add case 3.2.2
// TODO Add case 3.2.3
// TODO Add case 3.2.4
// TODO Add case 3.2.5
// TODO Add case 3.3.1
// TODO Add case 3.3.2
// TODO Add case 3.3.3
// TODO Add case 3.3.4
// TODO Add case 3.3.5
// TODO Add case 3.3.6
// TODO Add case 3.3.7
// TODO Add case 3.3.8
// TODO Add case 3.3.9
// TODO Add case 3.3.10
// TODO Add case 3.4
// TODO Add case 3.5.1
// TODO Add case 3.5.2
// TODO Add case 3.5.3
// TODO Add case 4.1.1
// TODO Add case 4.1.2
// TODO Add case 4.1.3
// TODO Add case 4.1.4
// TODO Add case 4.1.5
// TODO Add case 4.2.1
// TODO Add case 4.2.2
// TODO Add case 4.2.3
// TODO Add case 4.2.4
// TODO Add case 4.2.5
// TODO Add case 4.3.1
// TODO Add case 4.3.2
// TODO Add case 4.3.3
// TODO Add case 4.3.4
// TODO Add case 4.3.5
// TODO Add case 5.1.1
// TODO Add case 5.1.2
// TODO Add case 5.1.3
// TODO Add case 5.1.4
// TODO Add case 5.1.5
// TODO Add case 5.1.6
// TODO Add case 5.1.7
// TODO Add case 5.2.1
// TODO Add case 5.2.2
// TODO Add case 5.2.3
// TODO Add case 5.2.4
// TODO Add case 5.2.5
// TODO Add case 5.2.6
// TODO Add case 5.2.7
// TODO Add case 5.2.8
// TODO Add case 5.3.1
// TODO Add case 5.3.2
// TODO Add case 5.3.3
// TODO Add case 5.3.4
<|endoftext|> |
<commit_before><commit_msg>coverity#705773 Resource leak<commit_after><|endoftext|> |
<commit_before>#include <babylon/gamepads/controllers/pose_enabled_controller.h>
#include <babylon/culling/ray.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/ibrowser_gamepad.h>
#include <babylon/maths/tmp_vectors.h>
#include <babylon/meshes/abstract_mesh.h>
namespace BABYLON {
PoseEnabledController::PoseEnabledController(const IBrowserGamepadPtr& iBrowserGamepad)
: Gamepad(iBrowserGamepad->id, iBrowserGamepad->index, iBrowserGamepad)
, isXR{false}
, _mesh{nullptr}
, _deviceToWorld{Matrix::Identity()}
, _pointingPoseNode{nullptr}
, mesh{this, &PoseEnabledController::get_mesh}
, _deviceRoomPosition{Vector3::Zero()}
, _poseControlledCamera{nullptr}
, _workingMatrix{Matrix::Identity()}
{
type = Gamepad::POSE_ENABLED;
controllerType = PoseEnabledControllerType::GENERIC;
devicePosition = Vector3::Zero();
deviceScaleFactor = 1.f;
position = Vector3::Zero();
// Used to convert 6dof controllers to 3dof
_trackPosition = true;
_maxRotationDistFromHeadset = Math::PI / 5.f;
_draggedRoomRotation = 0.f;
_calculatedPosition = Vector3::Zero();
Quaternion::RotationYawPitchRollToRef(Math::PI, 0, 0, _leftHandSystemQuaternion);
}
PoseEnabledController::~PoseEnabledController() = default;
void PoseEnabledController::_disableTrackPosition(const Vector3& fixedPosition)
{
if (_trackPosition) {
_calculatedPosition.copyFrom(fixedPosition);
_trackPosition = false;
}
}
void PoseEnabledController::update()
{
Gamepad::update();
_updatePoseAndMesh();
}
void PoseEnabledController::_updatePoseAndMesh()
{
if (isXR) {
return;
}
const auto& pose = browserGamepad->pose;
if (pose) {
updateFromDevice(*pose);
}
Vector3::TransformCoordinatesToRef(_calculatedPosition, _deviceToWorld, devicePosition);
_deviceToWorld.getRotationMatrixToRef(_workingMatrix);
Quaternion::FromRotationMatrixToRef(_workingMatrix, deviceRotationQuaternion);
deviceRotationQuaternion.multiplyInPlace(_calculatedRotation);
if (_mesh) {
_mesh->position().copyFrom(devicePosition);
if (_mesh->rotationQuaternion()) {
_mesh->rotationQuaternion()->copyFrom(deviceRotationQuaternion);
}
}
}
void PoseEnabledController::updateFromDevice(const DevicePose& poseData)
{
if (isXR) {
return;
}
rawPose = poseData;
if (!poseData.position.empty()) {
_deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1],
-poseData.position[2]);
if (_mesh && _mesh->getScene()->useRightHandedSystem()) {
_deviceRoomPosition.z *= -1.f;
}
_deviceRoomPosition.scaleToRef(deviceScaleFactor, _calculatedPosition);
_calculatedPosition.addInPlace(position);
}
auto& pose = rawPose;
if (!poseData.orientation.empty() && !pose.orientation.empty() && pose.orientation.size() == 4) {
_deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1],
-pose.orientation[2], -pose.orientation[3]);
if (_mesh) {
if (_mesh->getScene()->useRightHandedSystem()) {
_deviceRoomRotationQuaternion.z *= -1.f;
_deviceRoomRotationQuaternion.w *= -1.f;
}
else {
_deviceRoomRotationQuaternion.multiplyToRef(_leftHandSystemQuaternion,
deviceRotationQuaternion);
}
}
// if the camera is set, rotate to the camera's rotation
_deviceRoomRotationQuaternion.multiplyToRef(rotationQuaternion, _calculatedRotation);
}
}
void PoseEnabledController::attachToMesh(const AbstractMeshPtr& iMesh)
{
if (_mesh) {
_mesh->setParent(nullptr);
}
_mesh = iMesh;
if (_poseControlledCamera) {
// _mesh->setParent(_poseControlledCamera);
}
if (!_mesh->rotationQuaternion()) {
_mesh->rotationQuaternion = Quaternion();
}
// Sync controller mesh and pointing pose node's state with controller, this
// is done to avoid a frame where position is 0,0,0 when attaching mesh
if (!isXR) {
_updatePoseAndMesh();
if (_pointingPoseNode) {
std::vector<Node*> parents;
auto obj = static_cast<Node*>(_pointingPoseNode);
while (obj && obj->parent()) {
parents.emplace_back(obj->parent());
obj = obj->parent();
}
std::reverse(parents.begin(), parents.end());
for (auto& p : parents) {
p->computeWorldMatrix(true);
}
}
}
_meshAttachedObservable.notifyObservers(iMesh.get());
}
void PoseEnabledController::attachToPoseControlledCamera(TargetCamera* camera)
{
_poseControlledCamera = camera;
if (_mesh) {
// _mesh->parent = _poseControlledCamera;
}
}
void PoseEnabledController::dispose()
{
if (_mesh) {
_mesh->dispose();
}
_mesh = nullptr;
Gamepad::dispose();
}
AbstractMeshPtr& PoseEnabledController::get_mesh()
{
return _mesh;
}
Ray PoseEnabledController::getForwardRay(float length)
{
if (!mesh()) {
return Ray(Vector3::Zero(), Vector3{0.f, 0.f, 1.f}, length);
}
auto m = _pointingPoseNode ? _pointingPoseNode->getWorldMatrix() : mesh()->getWorldMatrix();
auto origin = m.getTranslation();
Vector3 forward{0.f, 0.f, -1.f};
auto forwardWorld = Vector3::TransformNormal(forward, m);
auto direction = Vector3::Normalize(forwardWorld);
return Ray(origin, direction, length);
}
} // end of namespace BABYLON
<commit_msg>Formatted doc<commit_after>#include <babylon/gamepads/controllers/pose_enabled_controller.h>
#include <babylon/culling/ray.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/ibrowser_gamepad.h>
#include <babylon/maths/tmp_vectors.h>
#include <babylon/meshes/abstract_mesh.h>
namespace BABYLON {
PoseEnabledController::PoseEnabledController(const IBrowserGamepadPtr& iBrowserGamepad)
: Gamepad(iBrowserGamepad->id, iBrowserGamepad->index, iBrowserGamepad)
, isXR{false}
, _mesh{nullptr}
, _deviceToWorld{Matrix::Identity()}
, _pointingPoseNode{nullptr}
, mesh{this, &PoseEnabledController::get_mesh}
, _deviceRoomPosition{Vector3::Zero()}
, _poseControlledCamera{nullptr}
, _workingMatrix{Matrix::Identity()}
{
type = Gamepad::POSE_ENABLED;
controllerType = PoseEnabledControllerType::GENERIC;
devicePosition = Vector3::Zero();
deviceScaleFactor = 1.f;
position = Vector3::Zero();
// Used to convert 6dof controllers to 3dof
_trackPosition = true;
_maxRotationDistFromHeadset = Math::PI / 5.f;
_draggedRoomRotation = 0.f;
_calculatedPosition = Vector3::Zero();
Quaternion::RotationYawPitchRollToRef(Math::PI, 0, 0, _leftHandSystemQuaternion);
}
PoseEnabledController::~PoseEnabledController() = default;
void PoseEnabledController::_disableTrackPosition(const Vector3& fixedPosition)
{
if (_trackPosition) {
_calculatedPosition.copyFrom(fixedPosition);
_trackPosition = false;
}
}
void PoseEnabledController::update()
{
Gamepad::update();
_updatePoseAndMesh();
}
void PoseEnabledController::_updatePoseAndMesh()
{
if (isXR) {
return;
}
const auto& pose = browserGamepad->pose;
if (pose) {
updateFromDevice(*pose);
}
Vector3::TransformCoordinatesToRef(_calculatedPosition, _deviceToWorld, devicePosition);
_deviceToWorld.getRotationMatrixToRef(_workingMatrix);
Quaternion::FromRotationMatrixToRef(_workingMatrix, deviceRotationQuaternion);
deviceRotationQuaternion.multiplyInPlace(_calculatedRotation);
if (_mesh) {
_mesh->position().copyFrom(devicePosition);
if (_mesh->rotationQuaternion()) {
_mesh->rotationQuaternion()->copyFrom(deviceRotationQuaternion);
}
}
}
void PoseEnabledController::updateFromDevice(const DevicePose& poseData)
{
if (isXR) {
return;
}
rawPose = poseData;
if (!poseData.position.empty()) {
_deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1],
-poseData.position[2]);
if (_mesh && _mesh->getScene()->useRightHandedSystem()) {
_deviceRoomPosition.z *= -1.f;
}
_deviceRoomPosition.scaleToRef(deviceScaleFactor, _calculatedPosition);
_calculatedPosition.addInPlace(position);
}
auto& pose = rawPose;
if (!poseData.orientation.empty() && !pose.orientation.empty() && pose.orientation.size() == 4) {
_deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1],
-pose.orientation[2], -pose.orientation[3]);
if (_mesh) {
if (_mesh->getScene()->useRightHandedSystem()) {
_deviceRoomRotationQuaternion.z *= -1.f;
_deviceRoomRotationQuaternion.w *= -1.f;
}
else {
_deviceRoomRotationQuaternion.multiplyToRef(_leftHandSystemQuaternion,
deviceRotationQuaternion);
}
}
// if the camera is set, rotate to the camera's rotation
_deviceRoomRotationQuaternion.multiplyToRef(rotationQuaternion, _calculatedRotation);
}
}
void PoseEnabledController::attachToMesh(const AbstractMeshPtr& iMesh)
{
if (_mesh) {
_mesh->setParent(nullptr);
}
_mesh = iMesh;
if (_poseControlledCamera) {
// _mesh->setParent(_poseControlledCamera);
}
if (!_mesh->rotationQuaternion()) {
_mesh->rotationQuaternion = Quaternion();
}
// Sync controller mesh and pointing pose node's state with controller, this is done to avoid a
// frame where position is 0,0,0 when attaching mesh
if (!isXR) {
_updatePoseAndMesh();
if (_pointingPoseNode) {
std::vector<Node*> parents;
auto obj = static_cast<Node*>(_pointingPoseNode);
while (obj && obj->parent()) {
parents.emplace_back(obj->parent());
obj = obj->parent();
}
std::reverse(parents.begin(), parents.end());
for (auto& p : parents) {
p->computeWorldMatrix(true);
}
}
}
_meshAttachedObservable.notifyObservers(iMesh.get());
}
void PoseEnabledController::attachToPoseControlledCamera(TargetCamera* camera)
{
_poseControlledCamera = camera;
if (_mesh) {
// _mesh->parent = _poseControlledCamera;
}
}
void PoseEnabledController::dispose()
{
if (_mesh) {
_mesh->dispose();
}
_mesh = nullptr;
Gamepad::dispose();
}
AbstractMeshPtr& PoseEnabledController::get_mesh()
{
return _mesh;
}
Ray PoseEnabledController::getForwardRay(float length)
{
if (!mesh()) {
return Ray(Vector3::Zero(), Vector3{0.f, 0.f, 1.f}, length);
}
auto m = _pointingPoseNode ? _pointingPoseNode->getWorldMatrix() : mesh()->getWorldMatrix();
auto origin = m.getTranslation();
Vector3 forward{0.f, 0.f, -1.f};
auto forwardWorld = Vector3::TransformNormal(forward, m);
auto direction = Vector3::Normalize(forwardWorld);
return Ray(origin, direction, length);
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>
#include <cmath> // for std::abs, std::pow, std::fabs
#include <cstdint> // I dont use int, long, long long etc b/c they are ambiguous
#include <iostream> // for std::cin
#include <fstream> // for std::ifstream
#include <sstream> // for std::istringstream
#include <algorithm> // for std::swap, std::copy
// Represents a ring
struct Ring {
int32_t elem[4];
};
// This should in fact be inside a class but this is just an example
std::vector<Ring> rings;
double bestpw[4];
// Computes the stacked power of a set of rings - for a single element
static inline double calc_ring_power( int32_t pw0, int32_t pw1, int32_t pw2, int32_t pw3, int32_t pw4 )
{
double s1 = 0 + std::pow(pw0-2,2);
double s2 = (s1-30) + 5*std::abs(pw1-5);
double s3 = -s2 + pw2%3;
double s4 = std::floor(std::fabs(s3)/2) + std::pow((pw3-7),2);
double s5 = (100-s4) + (10-pw4);
return s5;
}
// Receives the callback from gen_permutations() for each new permutation
void new_permutation( uint32_t pm_count, std::vector<uint32_t>& perm )
{
double pw[4];
for ( uint32_t k = 0; k<4; ++k ) {
pw[k] = calc_ring_power(rings[ perm[0] ].elem[k],
rings[ perm[1] ].elem[k],
rings[ perm[2] ].elem[k],
rings[ perm[3] ].elem[k],
rings[ perm[4] ].elem[k] );
// No good if the power is less than the minimum
if ( pw[k]<80 ) return;
}
// Print the ring IDs
printf( ">> Perm %d: %d %d %d %d %d ",
pm_count, perm[0], perm[1], perm[2], perm[3], perm[4] );
// For each element, compare the current solution to the best solution so far
for ( uint32_t k=0; k<4; ++k ) {
if ( pw[k]>bestpw[k] ) {
bestpw[k] = pw[k];
// print in a highlighted way for fanciness - these are just comments
printf( " [%2.0f] ", pw[k] );
} else {
printf( " %2.0f ", pw[k] );
}
}
printf( "\n" );
}
// Generate all permutations (no order) - this should be N!/(N-R)! permutations
// Taken from https://docs.python.org/2/library/itertools.html#itertools.permutations
void gen_permutations( const uint32_t N, const uint32_t R )
{
// sanity test
if ( (N<1) or (R>N) ) return;
// Create an index of rings and initialize with 1,2,3,4,5...,N
std::vector<uint32_t> idx(N);
for ( uint32_t j=0; j<N; ++j ) idx[j] = j;
// Create a cyclic counter - part of the algorithm
std::vector<uint32_t> cyc(R);
for ( uint32_t j=0; j<R; ++j ) cyc[j] = N-j;
std::vector<uint32_t> cur(R);
std::copy( &idx[0], &idx[R], &cur[0] );
// output the first trivial solution
new_permutation( 0, cur );
// Counts the number of permutations generated so far
uint32_t count = 0;
// We will stop when we could not create anymore permutations
bool gotit;
do {
// assume the worst
gotit = false;
// Initialize index
uint32_t i = R;
while ( i>0 ) {
--i;
cyc[i]--;
if ( cyc[i] == 0 ) {
uint32_t first = idx[i];
for ( uint32_t j=i; j<N-1; ++j ) idx[j] = idx[j+1];
idx[N-1] = first;
cyc[i] = N-i;
}
else {
uint32_t j = cyc[i];
// Swap two elements in the index array
std::swap( idx[i], idx[N-j] );
// copy the first R elements from the index array to the actual solution array
std::copy( &idx[0], &idx[R], &cur[0] );
new_permutation( ++count, cur );
gotit = true;
break;
}
}
} while( gotit );
}
// Processes a file (or stdin)
void process( std::istream& ifs ) {
std::string line;
uint32_t numrings;
// first line has to be the number of rings
std::getline( ifs, line );
std::istringstream iheader( line );
iheader >> numrings;
// Initialize the best solution with zeros
for ( uint32_t j=0; j<4; ++j ) bestpw[j] = 0;
// Resize the vector of rings b/c I hate to be doing push_back()
// If you know the size up front just resize and use it
// It avoids calling malloc() internally
rings.resize( numrings );
// Loop for every ring
for ( uint32_t j=0; j<numrings; ++j ) {
// Read line
std::getline( ifs, line );
// We use a second istream to parse the line
// This is slower but much more convenient
std::istringstream iis( line );
iis >> rings[j].elem[0]
>> rings[j].elem[1]
>> rings[j].elem[2]
>> rings[j].elem[3];
}
// Now that we read all the rings, proceed to create all
// possible permutations and compute the stacked power of
// each of them, keeping the element's best
gen_permutations( numrings, 5 );
// Print the solution
for ( uint32_t k=0; k<4; ++k ) {
printf( "%.0f\n", bestpw[k] );
}
// say yay
}
int main( int argc, char* argv[] )
{
if ( argc>1 ) {
// If we have command line arguments, they should be file names
// We process them one by one
// Notice that argv[0] should be the program name (rings)
for ( uint32_t j=1; j<argc; ++j ) {
// Open the file
std::ifstream ifs( argv[j] );
process( ifs );
}
}
else {
// Otherwise we expect the data to be piped into stdin
// as in `rings < rings.txt`
process( std::cin );
}
}
<commit_msg>Added simpler permutation algorithm<commit_after>
#include <cmath> // for std::abs, std::pow, std::fabs
#include <cstdint> // I dont use int, long, long long etc b/c they are ambiguous
#include <iostream> // for std::cin
#include <fstream> // for std::ifstream
#include <sstream> // for std::istringstream
#include <algorithm> // for std::swap, std::copy
// Represents a ring
struct Ring {
int32_t elem[4];
};
// This should in fact be inside a class but this is just an example
std::vector<Ring> rings;
double bestpw[4];
// Computes the stacked power of a set of rings - for a single element
static inline double calc_ring_power( int32_t pw0, int32_t pw1, int32_t pw2, int32_t pw3, int32_t pw4 )
{
double s1 = 0 + std::pow(pw0-2,2);
double s2 = (s1-30) + 5*std::abs(pw1-5);
double s3 = -s2 + pw2%3;
double s4 = std::floor(std::fabs(s3)/2) + std::pow((pw3-7),2);
double s5 = (100-s4) + (10-pw4);
return s5;
}
// Receives the callback from gen_permutations() for each new permutation
void new_permutation( uint32_t pm_count, std::vector<uint32_t>& perm )
{
double pw[4];
for ( uint32_t k = 0; k<4; ++k ) {
pw[k] = calc_ring_power(rings[ perm[0] ].elem[k],
rings[ perm[1] ].elem[k],
rings[ perm[2] ].elem[k],
rings[ perm[3] ].elem[k],
rings[ perm[4] ].elem[k] );
// No good if the power is less than the minimum
if ( pw[k]<80 ) return;
}
// Print the ring IDs
printf( ">> Perm %d: %d %d %d %d %d ",
pm_count, perm[0], perm[1], perm[2], perm[3], perm[4] );
// For each element, compare the current solution to the best solution so far
for ( uint32_t k=0; k<4; ++k ) {
if ( pw[k]>bestpw[k] ) {
bestpw[k] = pw[k];
// print in a highlighted way for fanciness - these are just comments
printf( " [%2.0f] ", pw[k] );
} else {
printf( " %2.0f ", pw[k] );
}
}
printf( "\n" );
}
// Generate all permutations - this should be N! permutations
// This is VERY wasteful if N is much greater than R
void gen_permutations_wasteful( const uint32_t N, const uint32_t R )
{
// Create an index of rings and initialize with 1,2,3,4,5...,N
std::vector<uint32_t> idx(N);
for ( uint32_t j=0; j<N; ++j ) idx[j] = j;
// output the first trivial solution
std::vector<uint32_t> cur(R);
std::copy( &idx[0], &idx[R], &cur[0] );
new_permutation( 0, cur );
while ( std::next_permutation( &idx[0], &idx[N] ) ) {
std::copy( &idx[0], &idx[R], &cur[0] );
new_permutation( 0, cur );
}
}
// Generate all permutations (no order) - this should be N!/(N-R)! permutations
// Taken from https://docs.python.org/2/library/itertools.html#itertools.permutations
void gen_permutations( const uint32_t N, const uint32_t R )
{
// sanity test
if ( (N<1) or (R>N) ) return;
// Create an index of rings and initialize with 1,2,3,4,5...,N
std::vector<uint32_t> idx(N);
for ( uint32_t j=0; j<N; ++j ) idx[j] = j;
// Create a cyclic counter - part of the algorithm
std::vector<uint32_t> cyc(R);
for ( uint32_t j=0; j<R; ++j ) cyc[j] = N-j;
std::vector<uint32_t> cur(R);
std::copy( &idx[0], &idx[R], &cur[0] );
// output the first trivial solution
new_permutation( 0, cur );
// Counts the number of permutations generated so far
uint32_t count = 0;
// We will stop when we could not create anymore permutations
bool gotit;
do {
// assume the worst
gotit = false;
// Initialize index
uint32_t i = R;
while ( i>0 ) {
--i;
cyc[i]--;
if ( cyc[i] == 0 ) {
uint32_t first = idx[i];
for ( uint32_t j=i; j<N-1; ++j ) idx[j] = idx[j+1];
idx[N-1] = first;
cyc[i] = N-i;
}
else {
uint32_t j = cyc[i];
// Swap two elements in the index array
std::swap( idx[i], idx[N-j] );
// copy the first R elements from the index array to the actual solution array
std::copy( &idx[0], &idx[R], &cur[0] );
new_permutation( ++count, cur );
gotit = true;
break;
}
}
} while( gotit );
}
// Processes a file (or stdin)
void process( std::istream& ifs ) {
std::string line;
uint32_t numrings;
// first line has to be the number of rings
std::getline( ifs, line );
std::istringstream iheader( line );
iheader >> numrings;
// Initialize the best solution with zeros
for ( uint32_t j=0; j<4; ++j ) bestpw[j] = 0;
// Resize the vector of rings b/c I hate to be doing push_back()
// If you know the size up front just resize and use it
// It avoids calling malloc() internally
rings.resize( numrings );
// Loop for every ring
for ( uint32_t j=0; j<numrings; ++j ) {
// Read line
std::getline( ifs, line );
// We use a second istream to parse the line
// This is slower but much more convenient
std::istringstream iis( line );
iis >> rings[j].elem[0]
>> rings[j].elem[1]
>> rings[j].elem[2]
>> rings[j].elem[3];
}
// Now that we read all the rings, proceed to create all
// possible permutations and compute the stacked power of
// each of them, keeping the element's best
gen_permutations_wasteful( numrings, 5 );
// Print the solution
for ( uint32_t k=0; k<4; ++k ) {
printf( "%.0f\n", bestpw[k] );
}
// say yay
}
int main( int argc, char* argv[] )
{
if ( argc>1 ) {
// If we have command line arguments, they should be file names
// We process them one by one
// Notice that argv[0] should be the program name (rings)
for ( uint32_t j=1; j<argc; ++j ) {
// Open the file
std::ifstream ifs( argv[j] );
process( ifs );
}
}
else {
// Otherwise we expect the data to be piped into stdin
// as in `rings < rings.txt`
process( std::cin );
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <credentials/CHIPCert.h>
namespace chip {
namespace Controller {
constexpr const char kOperationalCredentialsIssuerKeypairStorage[] = "ExampleOpCredsCAKey";
using namespace Credentials;
using namespace Crypto;
CHIP_ERROR ExampleOperationalCredentialsIssuer::Initialize(PersistentStorageDelegate & storage)
{
Crypto::P256SerializedKeypair serializedKey;
uint16_t keySize = static_cast<uint16_t>(serializedKey.Capacity());
if (storage.SyncGetKeyValue(kOperationalCredentialsIssuerKeypairStorage, serializedKey, keySize) != CHIP_NO_ERROR)
{
// Storage doesn't have an existing keypair. Let's create one and add it to the storage.
ReturnErrorOnFailure(mIssuer.Initialize());
ReturnErrorOnFailure(mIssuer.Serialize(serializedKey));
keySize = static_cast<uint16_t>(serializedKey.Length());
ReturnErrorOnFailure(storage.SyncSetKeyValue(kOperationalCredentialsIssuerKeypairStorage, serializedKey, keySize));
}
else
{
// Use the keypair from the storage
ReturnErrorOnFailure(mIssuer.Deserialize(serializedKey));
}
mInitialized = true;
return CHIP_NO_ERROR;
}
CHIP_ERROR ExampleOperationalCredentialsIssuer::GenerateNodeOperationalCertificate(const PeerId & peerId, const ByteSpan & csr,
int64_t serialNumber, uint8_t * certBuf,
uint32_t certBufSize, uint32_t & outCertLen)
{
VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE);
X509CertRequestParams request = { serialNumber, mIssuerId, mNow, mNow + mValidity, true, peerId.GetFabricId(),
true, peerId.GetNodeId() };
P256PublicKey pubkey;
ReturnErrorOnFailure(VerifyCertificateSigningRequest(csr.data(), csr.size(), pubkey));
return NewNodeOperationalX509Cert(request, CertificateIssuerLevel::kIssuerIsRootCA, pubkey, mIssuer, certBuf, certBufSize,
outCertLen);
}
CHIP_ERROR ExampleOperationalCredentialsIssuer::GetRootCACertificate(FabricId fabricId, uint8_t * certBuf, uint32_t certBufSize,
uint32_t & outCertLen)
{
VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE);
X509CertRequestParams request = { 0, mIssuerId, mNow, mNow + mValidity, true, fabricId, false, 0 };
return NewRootX509Cert(request, mIssuer, certBuf, certBufSize, outCertLen);
}
} // namespace Controller
} // namespace chip
<commit_msg>Include length of key when it's stored in persistent storage (#6853)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <credentials/CHIPCert.h>
namespace chip {
namespace Controller {
constexpr const char kOperationalCredentialsIssuerKeypairStorage[] = "ExampleOpCredsCAKey";
using namespace Credentials;
using namespace Crypto;
CHIP_ERROR ExampleOperationalCredentialsIssuer::Initialize(PersistentStorageDelegate & storage)
{
Crypto::P256SerializedKeypair serializedKey;
uint16_t keySize = static_cast<uint16_t>(sizeof(serializedKey));
if (storage.SyncGetKeyValue(kOperationalCredentialsIssuerKeypairStorage, &serializedKey, keySize) != CHIP_NO_ERROR)
{
// Storage doesn't have an existing keypair. Let's create one and add it to the storage.
ReturnErrorOnFailure(mIssuer.Initialize());
ReturnErrorOnFailure(mIssuer.Serialize(serializedKey));
ReturnErrorOnFailure(storage.SyncSetKeyValue(kOperationalCredentialsIssuerKeypairStorage, &serializedKey, keySize));
}
else
{
// Use the keypair from the storage
ReturnErrorOnFailure(mIssuer.Deserialize(serializedKey));
}
mInitialized = true;
return CHIP_NO_ERROR;
}
CHIP_ERROR ExampleOperationalCredentialsIssuer::GenerateNodeOperationalCertificate(const PeerId & peerId, const ByteSpan & csr,
int64_t serialNumber, uint8_t * certBuf,
uint32_t certBufSize, uint32_t & outCertLen)
{
VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE);
X509CertRequestParams request = { serialNumber, mIssuerId, mNow, mNow + mValidity, true, peerId.GetFabricId(),
true, peerId.GetNodeId() };
P256PublicKey pubkey;
ReturnErrorOnFailure(VerifyCertificateSigningRequest(csr.data(), csr.size(), pubkey));
return NewNodeOperationalX509Cert(request, CertificateIssuerLevel::kIssuerIsRootCA, pubkey, mIssuer, certBuf, certBufSize,
outCertLen);
}
CHIP_ERROR ExampleOperationalCredentialsIssuer::GetRootCACertificate(FabricId fabricId, uint8_t * certBuf, uint32_t certBufSize,
uint32_t & outCertLen)
{
VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE);
X509CertRequestParams request = { 0, mIssuerId, mNow, mNow + mValidity, true, fabricId, false, 0 };
return NewRootX509Cert(request, mIssuer, certBuf, certBufSize, outCertLen);
}
} // namespace Controller
} // namespace chip
<|endoftext|> |
<commit_before>#include "CommonImport.h"
#include "CommonUtilities.h"
#include "CommonMeshUtilities.h"
#include "CommonAlembic.h"
#include <boost/algorithm/string.hpp>
#include <sstream>
bool parseBool(std::string value){
//std::istringstream(valuePair[1]) >> bExportSelected;
if( value.find("true") != std::string::npos || value.find("1") != std::string::npos ){
return true;
}
else{
return false;
}
}
bool IJobStringParser::parse(const std::string& jobString)
{
std::vector<std::string> tokens;
boost::split(tokens, jobString, boost::is_any_of(";"));
//if(tokens.empty()){
// return false;
//}
for(int j=0; j<tokens.size(); j++){
std::vector<std::string> valuePair;
boost::split(valuePair, tokens[j], boost::is_any_of("="));
if(valuePair.size() != 2){
ESS_LOG_WARNING("Skipping invalid token: "<<tokens[j]);
continue;
}
if(boost::iequals(valuePair[0], "filename")){
filename = valuePair[1];
}
else if(boost::iequals(valuePair[0], "normals")){
importNormals = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "uvs")){
importUVs = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "facesets")){
importFacesets = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "materialIds")){
importMaterialIds = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "attachToExisting")){
attachToExisting = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importStandinProperties")){
importStandinProperties = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importBoundingBoxes")){
importBoundingBoxes = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importVisibilityControllers")){
importVisibilityControllers = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "failOnUnsupported")){
failOnUnsupported = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "filters") || boost::iequals(valuePair[0], "identifiers")){
boost::split(nodesToImport, valuePair[1], boost::is_any_of(","));
}
else if(boost::iequals(valuePair[0], "includeChildren")){
includeChildren = parseBool(valuePair[1]);
}
else
{
ESS_LOG_WARNING("Skipping invalid token: "<<tokens[j]);
continue;
}
}
return true;
}
std::string IJobStringParser::buildJobString()
{
////Note: there are currently some minor differences between the apps. This function is somewhat XSI specific.
std::stringstream stream;
if(!filename.empty()){
stream<<"filename="<<filename<<";";
}
stream<<"normals="<<importNormals<<";uvs="<<importUVs<<";facesets="<<importFacesets;
stream<<";importVisibilityControllers="<<importVisibilityControllers<<";importStandinProperties="<<importStandinProperties;
stream<<";importBoundingBoxes="<<importBoundingBoxes<<";attachToExisting="<<attachToExisting<<";failOnUnsupported="<<failOnUnsupported;
if(!nodesToImport.empty()){
stream<<";identifiers=";
for(int i=0; i<nodesToImport.size(); i++){
stream<<nodesToImport[i];
if(i != nodesToImport.size()-1){
stream<<",";
}
}
}
return stream.str();
}
SceneNode::nodeTypeE getNodeType(Alembic::Abc::IObject iObj)
{
AbcG::MetaData metadata = iObj.getMetaData();
if(AbcG::IXform::matches(metadata)){
return SceneNode::ITRANSFORM;
//Note: this method assumes everything is an ITRANSFORM, this is corrected later on in the the method that builds the common scene graph
}
else if(AbcG::IPolyMesh::matches(metadata) ||
AbcG::ISubD::matches(metadata) ){
return SceneNode::POLYMESH;
}
else if(AbcG::ICamera::matches(metadata)){
return SceneNode::CAMERA;
}
else if(AbcG::IPoints::matches(metadata)){
return SceneNode::PARTICLES;
}
else if(AbcG::ICurves::matches(metadata)){
return SceneNode::CURVES;
}
else if(AbcG::ILight::matches(metadata)){
return SceneNode::LIGHT;
}
else if(AbcG::INuPatch::matches(metadata)){
return SceneNode::SURFACE;
}
return SceneNode::UNKNOWN;
}
struct AlembicISceneBuildElement
{
AbcObjectCache *pObjectCache;
SceneNodePtr parentNode;
AlembicISceneBuildElement(AbcObjectCache *pMyObjectCache, SceneNodePtr node):pObjectCache(pMyObjectCache), parentNode(node)
{}
};
SceneNodeAlembicPtr buildAlembicSceneGraph(AbcArchiveCache *pArchiveCache, AbcObjectCache *pRootObjectCache, int& nNumNodes)
{
std::list<AlembicISceneBuildElement> sceneStack;
Alembic::Abc::IObject rootObj = pRootObjectCache->obj;
SceneNodeAlembicPtr sceneRoot(new SceneNodeAlembic(pRootObjectCache));
sceneRoot->name = rootObj.getName();
sceneRoot->dccIdentifier = rootObj.getFullName();
sceneRoot->type = SceneNode::SCENE_ROOT;
for(size_t j=0; j<pRootObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( pRootObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, sceneRoot));
}
//sceneStack.push_back(AlembicISceneBuildElement(pRootObjectCache, NULL));
int numNodes = 0;
while( !sceneStack.empty() )
{
AlembicISceneBuildElement sElement = sceneStack.back();
Alembic::Abc::IObject iObj = sElement.pObjectCache->obj;
SceneNodePtr parentNode = sElement.parentNode;
sceneStack.pop_back();
numNodes++;
SceneNodeAlembicPtr newNode(new SceneNodeAlembic(sElement.pObjectCache));
newNode->name = iObj.getName();
newNode->dccIdentifier = iObj.getFullName();
newNode->type = getNodeType(iObj);
//select every node by default
newNode->selected = true;
if(parentNode){ //create bi-direction link if there is a parent
newNode->parent = parentNode.get();
parentNode->children.push_back(newNode);
//the parent transforms of geometry nodes should be to be external transforms
//(we don't a transform's type until we have seen what type(s) of child it has)
if( NodeCategory::get(iObj) == NodeCategory::GEOMETRY ){
if(parentNode->type == SceneNode::ITRANSFORM){
parentNode->type = SceneNode::ETRANSFORM;
}
else{
ESS_LOG_WARNING("node "<<iObj.getFullName()<<" does not have a parent transform.");
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(size_t j=0; j<sElement.pObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( sElement.pObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, newNode));
}
}
nNumNodes = numNodes;
return sceneRoot;
}
struct AttachStackElement
{
SceneNodeAppPtr currAppNode;
SceneNodeAlembicPtr currFileNode;
AttachStackElement(SceneNodeAppPtr appNode, SceneNodeAlembicPtr fileNode): currAppNode(appNode), currFileNode(fileNode)
{}
};
bool AttachSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams)
{
//TODO: how to account for filtering?
//it would break the sibling namespace assumption. Perhaps we should require that all parent nodes of selected are imported.
//We would then not traverse unselected children
std::list<AttachStackElement> sceneStack;
for(SceneChildIterator it = appRoot->children.begin(); it != appRoot->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back(AttachStackElement(appNode, fileRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
while( !sceneStack.empty() )
{
AttachStackElement sElement = sceneStack.back();
SceneNodeAppPtr currAppNode = sElement.currAppNode;
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAlembicPtr newFileNode = currFileNode;
//Each set of siblings names in an Alembic file exist within a namespace
//This is not true for 3DS Max scene graphs, so we check for such conflicts using the "attached appNode flag"
bool bChildAttached = false;
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(currAppNode->name == fileNode->name){
ESS_LOG_WARNING("nodeMatch: "<<(*it)->name<<" = "<<fileNode->name);
if(fileNode->isAttached()){
ESS_LOG_ERROR("More than one match for node "<<(*it)->name);
return false;
}
else{
bChildAttached = currAppNode->replaceData(fileNode, jobParams, newFileNode);
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currAppNode->children.begin(); it != currAppNode->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back( AttachStackElement( appNode, newFileNode ) );
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
return true;
}
struct ImportStackElement
{
SceneNodeAlembicPtr currFileNode;
SceneNodeAppPtr parentAppNode;
ImportStackElement(SceneNodeAlembicPtr node, SceneNodeAppPtr parent):currFileNode(node), parentAppNode(parent)
{}
};
bool ImportSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams)
{
//TODO skip unselected children, if thats we how we do filtering.
//compare to application scene graph to see if we need to rename nodes (or maybe we might throw an error)
std::list<ImportStackElement> sceneStack;
for(SceneChildIterator it = fileRoot->children.begin(); it != fileRoot->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
sceneStack.push_back(ImportStackElement(fileNode, appRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
while( !sceneStack.empty() )
{
ImportStackElement sElement = sceneStack.back();
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
SceneNodeAppPtr parentAppNode = sElement.parentAppNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAppPtr newAppNode;
bool bContinue = parentAppNode->addChild(currFileNode, jobParams, newAppNode);
if(!bContinue){
return false;
}
if(newAppNode){
ESS_LOG_WARNING("newAppNode: "<<newAppNode->name<<" useCount: "<<newAppNode.use_count());
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(!fileNode->isSupported()) continue;
if( fileNode->isMerged() ){
//The child node was merged with its parent, so skip this child, and add its children
//(Although this case is technically possible, I think it will not be common)
SceneNodePtr& mergedChild = *it;
for(SceneChildIterator cit = mergedChild->children.begin(); cit != mergedChild->children.end(); cit++){
SceneNodeAlembicPtr cfileNode = reinterpret<SceneNode, SceneNodeAlembic>(*cit);
sceneStack.push_back( ImportStackElement( cfileNode, newAppNode ) );
}
}
else{
sceneStack.push_back( ImportStackElement( fileNode, newAppNode ) );
}
}
}
else{
ESS_LOG_WARNING("newAppNode useCount: "<<newAppNode.use_count());
if( currFileNode->children.empty() == false ) {
EC_LOG_WARNING("Unsupported node: " << currFileNode->name << " has children that have not been imported." );
}
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
return true;
}
<commit_msg>add profiling, remove some debug messages!<commit_after>#include "CommonImport.h"
#include "CommonUtilities.h"
#include "CommonMeshUtilities.h"
#include "CommonAlembic.h"
#include <boost/algorithm/string.hpp>
#include <sstream>
bool parseBool(std::string value){
//std::istringstream(valuePair[1]) >> bExportSelected;
if( value.find("true") != std::string::npos || value.find("1") != std::string::npos ){
return true;
}
else{
return false;
}
}
bool IJobStringParser::parse(const std::string& jobString)
{
std::vector<std::string> tokens;
boost::split(tokens, jobString, boost::is_any_of(";"));
//if(tokens.empty()){
// return false;
//}
for(int j=0; j<tokens.size(); j++){
std::vector<std::string> valuePair;
boost::split(valuePair, tokens[j], boost::is_any_of("="));
if(valuePair.size() != 2){
ESS_LOG_WARNING("Skipping invalid token: "<<tokens[j]);
continue;
}
if(boost::iequals(valuePair[0], "filename")){
filename = valuePair[1];
}
else if(boost::iequals(valuePair[0], "normals")){
importNormals = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "uvs")){
importUVs = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "facesets")){
importFacesets = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "materialIds")){
importMaterialIds = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "attachToExisting")){
attachToExisting = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importStandinProperties")){
importStandinProperties = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importBoundingBoxes")){
importBoundingBoxes = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importVisibilityControllers")){
importVisibilityControllers = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "failOnUnsupported")){
failOnUnsupported = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "filters") || boost::iequals(valuePair[0], "identifiers")){
boost::split(nodesToImport, valuePair[1], boost::is_any_of(","));
}
else if(boost::iequals(valuePair[0], "includeChildren")){
includeChildren = parseBool(valuePair[1]);
}
else
{
ESS_LOG_WARNING("Skipping invalid token: "<<tokens[j]);
continue;
}
}
return true;
}
std::string IJobStringParser::buildJobString()
{
////Note: there are currently some minor differences between the apps. This function is somewhat XSI specific.
std::stringstream stream;
if(!filename.empty()){
stream<<"filename="<<filename<<";";
}
stream<<"normals="<<importNormals<<";uvs="<<importUVs<<";facesets="<<importFacesets;
stream<<";importVisibilityControllers="<<importVisibilityControllers<<";importStandinProperties="<<importStandinProperties;
stream<<";importBoundingBoxes="<<importBoundingBoxes<<";attachToExisting="<<attachToExisting<<";failOnUnsupported="<<failOnUnsupported;
if(!nodesToImport.empty()){
stream<<";identifiers=";
for(int i=0; i<nodesToImport.size(); i++){
stream<<nodesToImport[i];
if(i != nodesToImport.size()-1){
stream<<",";
}
}
}
return stream.str();
}
SceneNode::nodeTypeE getNodeType(Alembic::Abc::IObject iObj)
{
AbcG::MetaData metadata = iObj.getMetaData();
if(AbcG::IXform::matches(metadata)){
return SceneNode::ITRANSFORM;
//Note: this method assumes everything is an ITRANSFORM, this is corrected later on in the the method that builds the common scene graph
}
else if(AbcG::IPolyMesh::matches(metadata) ||
AbcG::ISubD::matches(metadata) ){
return SceneNode::POLYMESH;
}
else if(AbcG::ICamera::matches(metadata)){
return SceneNode::CAMERA;
}
else if(AbcG::IPoints::matches(metadata)){
return SceneNode::PARTICLES;
}
else if(AbcG::ICurves::matches(metadata)){
return SceneNode::CURVES;
}
else if(AbcG::ILight::matches(metadata)){
return SceneNode::LIGHT;
}
else if(AbcG::INuPatch::matches(metadata)){
return SceneNode::SURFACE;
}
return SceneNode::UNKNOWN;
}
struct AlembicISceneBuildElement
{
AbcObjectCache *pObjectCache;
SceneNodePtr parentNode;
AlembicISceneBuildElement(AbcObjectCache *pMyObjectCache, SceneNodePtr node):pObjectCache(pMyObjectCache), parentNode(node)
{}
};
SceneNodeAlembicPtr buildAlembicSceneGraph(AbcArchiveCache *pArchiveCache, AbcObjectCache *pRootObjectCache, int& nNumNodes)
{
ESS_PROFILE_SCOPE("buildAlembicSceneGraph");
std::list<AlembicISceneBuildElement> sceneStack;
Alembic::Abc::IObject rootObj = pRootObjectCache->obj;
SceneNodeAlembicPtr sceneRoot(new SceneNodeAlembic(pRootObjectCache));
sceneRoot->name = rootObj.getName();
sceneRoot->dccIdentifier = rootObj.getFullName();
sceneRoot->type = SceneNode::SCENE_ROOT;
for(size_t j=0; j<pRootObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( pRootObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, sceneRoot));
}
//sceneStack.push_back(AlembicISceneBuildElement(pRootObjectCache, NULL));
int numNodes = 0;
while( !sceneStack.empty() )
{
AlembicISceneBuildElement sElement = sceneStack.back();
Alembic::Abc::IObject iObj = sElement.pObjectCache->obj;
SceneNodePtr parentNode = sElement.parentNode;
sceneStack.pop_back();
numNodes++;
SceneNodeAlembicPtr newNode(new SceneNodeAlembic(sElement.pObjectCache));
newNode->name = iObj.getName();
newNode->dccIdentifier = iObj.getFullName();
newNode->type = getNodeType(iObj);
//select every node by default
newNode->selected = true;
if(parentNode){ //create bi-direction link if there is a parent
newNode->parent = parentNode.get();
parentNode->children.push_back(newNode);
//the parent transforms of geometry nodes should be to be external transforms
//(we don't a transform's type until we have seen what type(s) of child it has)
if( NodeCategory::get(iObj) == NodeCategory::GEOMETRY ){
if(parentNode->type == SceneNode::ITRANSFORM){
parentNode->type = SceneNode::ETRANSFORM;
}
else{
ESS_LOG_WARNING("node "<<iObj.getFullName()<<" does not have a parent transform.");
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(size_t j=0; j<sElement.pObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( sElement.pObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, newNode));
}
}
nNumNodes = numNodes;
return sceneRoot;
}
struct AttachStackElement
{
SceneNodeAppPtr currAppNode;
SceneNodeAlembicPtr currFileNode;
AttachStackElement(SceneNodeAppPtr appNode, SceneNodeAlembicPtr fileNode): currAppNode(appNode), currFileNode(fileNode)
{}
};
bool AttachSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams)
{
//TODO: how to account for filtering?
//it would break the sibling namespace assumption. Perhaps we should require that all parent nodes of selected are imported.
//We would then not traverse unselected children
std::list<AttachStackElement> sceneStack;
for(SceneChildIterator it = appRoot->children.begin(); it != appRoot->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back(AttachStackElement(appNode, fileRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
while( !sceneStack.empty() )
{
AttachStackElement sElement = sceneStack.back();
SceneNodeAppPtr currAppNode = sElement.currAppNode;
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAlembicPtr newFileNode = currFileNode;
//Each set of siblings names in an Alembic file exist within a namespace
//This is not true for 3DS Max scene graphs, so we check for such conflicts using the "attached appNode flag"
bool bChildAttached = false;
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(currAppNode->name == fileNode->name){
ESS_LOG_WARNING("nodeMatch: "<<(*it)->name<<" = "<<fileNode->name);
if(fileNode->isAttached()){
ESS_LOG_ERROR("More than one match for node "<<(*it)->name);
return false;
}
else{
bChildAttached = currAppNode->replaceData(fileNode, jobParams, newFileNode);
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currAppNode->children.begin(); it != currAppNode->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back( AttachStackElement( appNode, newFileNode ) );
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
return true;
}
struct ImportStackElement
{
SceneNodeAlembicPtr currFileNode;
SceneNodeAppPtr parentAppNode;
ImportStackElement(SceneNodeAlembicPtr node, SceneNodeAppPtr parent):currFileNode(node), parentAppNode(parent)
{}
};
bool ImportSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams)
{
ESS_PROFILE_SCOPE("ImportSceneFile");
//TODO skip unselected children, if thats we how we do filtering.
//compare to application scene graph to see if we need to rename nodes (or maybe we might throw an error)
std::list<ImportStackElement> sceneStack;
for(SceneChildIterator it = fileRoot->children.begin(); it != fileRoot->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
sceneStack.push_back(ImportStackElement(fileNode, appRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
while( !sceneStack.empty() )
{
ImportStackElement sElement = sceneStack.back();
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
SceneNodeAppPtr parentAppNode = sElement.parentAppNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAppPtr newAppNode;
bool bContinue = parentAppNode->addChild(currFileNode, jobParams, newAppNode);
if(!bContinue){
return false;
}
if(newAppNode){
//ESS_LOG_WARNING("newAppNode: "<<newAppNode->name<<" useCount: "<<newAppNode.use_count());
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(!fileNode->isSupported()) continue;
if( fileNode->isMerged() ){
//The child node was merged with its parent, so skip this child, and add its children
//(Although this case is technically possible, I think it will not be common)
SceneNodePtr& mergedChild = *it;
for(SceneChildIterator cit = mergedChild->children.begin(); cit != mergedChild->children.end(); cit++){
SceneNodeAlembicPtr cfileNode = reinterpret<SceneNode, SceneNodeAlembic>(*cit);
sceneStack.push_back( ImportStackElement( cfileNode, newAppNode ) );
}
}
else{
sceneStack.push_back( ImportStackElement( fileNode, newAppNode ) );
}
}
}
else{
//ESS_LOG_WARNING("newAppNode useCount: "<<newAppNode.use_count());
if( currFileNode->children.empty() == false ) {
EC_LOG_WARNING("Unsupported node: " << currFileNode->name << " has children that have not been imported." );
}
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#include "jansson_handle.hpp"
#include "base/exception.hpp"
#include "base/string_utils.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include <boost/optional.hpp>
#include "3party/jansson/src/jansson.h"
namespace base
{
struct JSONDecRef
{
void operator()(json_t * root) const
{
if (root)
json_decref(root);
}
};
using JSONPtr = std::unique_ptr<json_t, JSONDecRef>;
inline JSONPtr NewJSONObject() { return JSONPtr(json_object()); }
inline JSONPtr NewJSONArray() { return JSONPtr(json_array()); }
inline JSONPtr NewJSONString(std::string const & s) { return JSONPtr(json_string(s.c_str())); }
inline JSONPtr NewJSONInt(json_int_t value) { return JSONPtr(json_integer(value)); }
inline JSONPtr NewJSONReal(double value) { return JSONPtr(json_real(value)); }
inline JSONPtr NewJSONBool(bool value) { return JSONPtr(value ? json_true() : json_false()); }
inline JSONPtr NewJSONNull() { return JSONPtr(json_null()); }
class Json
{
public:
DECLARE_EXCEPTION(Exception, RootException);
Json() = default;
explicit Json(std::string const & s) { ParseFrom(s); }
explicit Json(char const * s) { ParseFrom(s); }
explicit Json(JSONPtr && json) { m_handle.AttachNew(json.release()); }
Json GetDeepCopy() const
{
Json copy;
copy.m_handle.AttachNew(get_deep_copy());
return copy;
}
void ParseFrom(std::string const & s) { ParseFrom(s.c_str()); }
void ParseFrom(char const * s)
{
json_error_t jsonError;
m_handle.AttachNew(json_loads(s, 0, &jsonError));
if (!m_handle)
MYTHROW(Exception, (jsonError.line, jsonError.text));
}
json_t * get() const { return m_handle.get(); }
json_t * get_deep_copy() const { return json_deep_copy(get()); }
private:
JsonHandle m_handle;
};
JSONPtr LoadFromString(std::string const & str);
std::string DumpToString(JSONPtr const & json, size_t flags = 0);
json_t * GetJSONObligatoryField(json_t * root, std::string const & field);
json_t const * GetJSONObligatoryField(json_t const * root, std::string const & field);
json_t * GetJSONObligatoryField(json_t * root, char const * field);
json_t const * GetJSONObligatoryField(json_t const * root, char const * field);
json_t * GetJSONOptionalField(json_t * root, std::string const & field);
json_t const * GetJSONOptionalField(json_t const * root, std::string const & field);
json_t * GetJSONOptionalField(json_t * root, char const * field);
json_t const * GetJSONOptionalField(json_t const * root, char const * field);
template <class First>
inline json_t const * GetJSONObligatoryFieldByPath(json_t const * root, First && path)
{
return GetJSONObligatoryField(root, std::forward<First>(path));
}
template <class First, class... Paths>
inline json_t const * GetJSONObligatoryFieldByPath(json_t const * root, First && path,
Paths &&... paths)
{
json_t const * newRoot = GetJSONObligatoryFieldByPath(root, std::forward<First>(path));
return GetJSONObligatoryFieldByPath(newRoot, std::forward<Paths>(paths)...);
}
bool JSONIsNull(json_t const * root);
} // namespace base
template <typename T>
T FromJSON(json_t const * root)
{
T result{};
FromJSON(root, result);
return result;
}
inline void FromJSON(json_t * root, json_t *& value) { value = root; }
inline void FromJSON(json_t const * root, json_t const *& value) { value = root; }
void FromJSON(json_t const * root, double & result);
void FromJSON(json_t const * root, bool & result);
template <typename T, typename std::enable_if<std::is_integral<T>::value, void>::type * = nullptr>
void FromJSON(json_t const * root, T & result)
{
if (!json_is_number(root))
MYTHROW(base::Json::Exception, ("Object must contain a json number."));
result = static_cast<T>(json_integer_value(root));
}
std::string FromJSONToString(json_t const * root);
template <typename T>
T FromJSONObject(json_t const * root, char const * field)
{
auto const * json = base::GetJSONObligatoryField(root, field);
try
{
return FromJSON<T>(json);
}
catch (base::Json::Exception const & e)
{
MYTHROW(base::Json::Exception, ("An error occured while parsing field", field, e.Msg()));
}
}
template <typename T>
void FromJSONObject(json_t * root, std::string const & field, T & result)
{
auto * json = base::GetJSONObligatoryField(root, field);
try
{
FromJSON(json, result);
}
catch (base::Json::Exception const & e)
{
MYTHROW(base::Json::Exception, ("An error occured while parsing field", field, e.Msg()));
}
}
template <typename T>
boost::optional<T> FromJSONObjectOptional(json_t const * root, char const * field)
{
auto * json = base::GetJSONOptionalField(root, field);
if (!json)
return {};
boost::optional<T> result{T{}};
FromJSON(json, *result);
return result;
}
template <typename T>
void FromJSONObjectOptionalField(json_t const * root, std::string const & field, T & result)
{
auto * json = base::GetJSONOptionalField(root, field);
if (!json)
{
result = T{};
return;
}
FromJSON(json, result);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value, void>::type * = nullptr>
inline base::JSONPtr ToJSON(T value)
{
return base::NewJSONInt(value);
}
inline base::JSONPtr ToJSON(double value) { return base::NewJSONReal(value); }
inline base::JSONPtr ToJSON(bool value) { return base::NewJSONBool(value); }
inline base::JSONPtr ToJSON(char const * s) { return base::NewJSONString(s); }
template <typename T>
void ToJSONArray(json_t & root, T const & value)
{
json_array_append_new(&root, ToJSON(value).release());
}
inline void ToJSONArray(json_t & parent, base::JSONPtr & child)
{
json_array_append_new(&parent, child.release());
}
inline void ToJSONArray(json_t & parent, json_t & child) { json_array_append_new(&parent, &child); }
template <typename T>
void ToJSONObject(json_t & root, char const * field, T const & value)
{
json_object_set_new(&root, field, ToJSON(value).release());
}
inline void ToJSONObject(json_t & parent, char const * field, base::JSONPtr && child)
{
json_object_set_new(&parent, field, child.release());
}
inline void ToJSONObject(json_t & parent, char const * field, base::JSONPtr & child)
{
json_object_set_new(&parent, field, child.release());
}
inline void ToJSONObject(json_t & parent, char const * field, json_t & child)
{
json_object_set_new(&parent, field, &child);
}
template <typename T>
void ToJSONObject(json_t & root, std::string const & field, T const & value)
{
ToJSONObject(root, field.c_str(), value);
}
inline void ToJSONObject(json_t & parent, std::string const & field, base::JSONPtr && child)
{
ToJSONObject(parent, field.c_str(), std::move(child));
}
inline void ToJSONObject(json_t & parent, std::string const & field, base::JSONPtr & child)
{
ToJSONObject(parent, field.c_str(), child);
}
inline void ToJSONObject(json_t & parent, std::string const & field, json_t & child)
{
ToJSONObject(parent, field.c_str(), child);
}
template <typename T>
void FromJSONObject(json_t * root, std::string const & field, std::vector<T> & result)
{
auto * arr = base::GetJSONObligatoryField(root, field);
if (!json_is_array(arr))
MYTHROW(base::Json::Exception, ("The field", field, "must contain a json array."));
size_t sz = json_array_size(arr);
result.resize(sz);
for (size_t i = 0; i < sz; ++i)
FromJSON(json_array_get(arr, i), result[i]);
}
// The function tries to parse array of values from a value
// corresponding to |field| in a json object corresponding to |root|.
// Returns true when the value is non-null and array is successfully
// parsed. Returns false when there is no such |field| in the |root|
// or the value is null. Also, the method may throw an exception in
// case of json parsing errors.
template <typename T>
bool FromJSONObjectOptional(json_t * root, std::string const & field, std::vector<T> & result)
{
auto * arr = base::GetJSONOptionalField(root, field);
if (!arr || base::JSONIsNull(arr))
{
result.clear();
return false;
}
if (!json_is_array(arr))
MYTHROW(base::Json::Exception, ("The field", field, "must contain a json array."));
size_t const sz = json_array_size(arr);
result.resize(sz);
for (size_t i = 0; i < sz; ++i)
FromJSON(json_array_get(arr, i), result[i]);
return true;
}
template <typename T>
void ToJSONObject(json_t & root, char const * field, std::vector<T> const & values)
{
auto arr = base::NewJSONArray();
for (auto const & value : values)
json_array_append_new(arr.get(), ToJSON(value).release());
json_object_set_new(&root, field, arr.release());
}
template <typename T>
void ToJSONObject(json_t & root, std::string const & field, std::vector<T> const & values)
{
ToJSONObject(root, field.c_str(), values);
}
template <typename T>
void FromJSONObjectOptionalField(json_t * root, std::string const & field, std::vector<T> & result)
{
FromJSONObjectOptionalField(const_cast<json_t *>(root), field, result);
}
template <typename T>
void FromJSONObjectOptionalField(json_t const * root, std::string const & field, std::vector<T> & result)
{
json_t const * arr = base::GetJSONOptionalField(root, field);
if (!arr)
{
result.clear();
return;
}
if (!json_is_array(arr))
MYTHROW(base::Json::Exception, ("The field", field, "must contain a json array."));
size_t sz = json_array_size(arr);
result.resize(sz);
for (size_t i = 0; i < sz; ++i)
FromJSON(json_array_get(arr, i), result[i]);
}
struct JSONFreeDeleter
{
void operator()(char * buffer) const { free(buffer); }
};
namespace std
{
void FromJSON(json_t const * root, std::string & result);
inline base::JSONPtr ToJSON(std::string const & s) { return base::NewJSONString(s); }
} // namespace std
namespace strings
{
void FromJSON(json_t const * root, UniString & result);
base::JSONPtr ToJSON(UniString const & s);
} // namespace strings
<commit_msg>[myjansson] Fix const_cast<commit_after>#pragma once
#include "jansson_handle.hpp"
#include "base/exception.hpp"
#include "base/string_utils.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include <boost/optional.hpp>
#include "3party/jansson/src/jansson.h"
namespace base
{
struct JSONDecRef
{
void operator()(json_t * root) const
{
if (root)
json_decref(root);
}
};
using JSONPtr = std::unique_ptr<json_t, JSONDecRef>;
inline JSONPtr NewJSONObject() { return JSONPtr(json_object()); }
inline JSONPtr NewJSONArray() { return JSONPtr(json_array()); }
inline JSONPtr NewJSONString(std::string const & s) { return JSONPtr(json_string(s.c_str())); }
inline JSONPtr NewJSONInt(json_int_t value) { return JSONPtr(json_integer(value)); }
inline JSONPtr NewJSONReal(double value) { return JSONPtr(json_real(value)); }
inline JSONPtr NewJSONBool(bool value) { return JSONPtr(value ? json_true() : json_false()); }
inline JSONPtr NewJSONNull() { return JSONPtr(json_null()); }
class Json
{
public:
DECLARE_EXCEPTION(Exception, RootException);
Json() = default;
explicit Json(std::string const & s) { ParseFrom(s); }
explicit Json(char const * s) { ParseFrom(s); }
explicit Json(JSONPtr && json) { m_handle.AttachNew(json.release()); }
Json GetDeepCopy() const
{
Json copy;
copy.m_handle.AttachNew(get_deep_copy());
return copy;
}
void ParseFrom(std::string const & s) { ParseFrom(s.c_str()); }
void ParseFrom(char const * s)
{
json_error_t jsonError;
m_handle.AttachNew(json_loads(s, 0, &jsonError));
if (!m_handle)
MYTHROW(Exception, (jsonError.line, jsonError.text));
}
json_t * get() const { return m_handle.get(); }
json_t * get_deep_copy() const { return json_deep_copy(get()); }
private:
JsonHandle m_handle;
};
JSONPtr LoadFromString(std::string const & str);
std::string DumpToString(JSONPtr const & json, size_t flags = 0);
json_t * GetJSONObligatoryField(json_t * root, std::string const & field);
json_t const * GetJSONObligatoryField(json_t const * root, std::string const & field);
json_t * GetJSONObligatoryField(json_t * root, char const * field);
json_t const * GetJSONObligatoryField(json_t const * root, char const * field);
json_t * GetJSONOptionalField(json_t * root, std::string const & field);
json_t const * GetJSONOptionalField(json_t const * root, std::string const & field);
json_t * GetJSONOptionalField(json_t * root, char const * field);
json_t const * GetJSONOptionalField(json_t const * root, char const * field);
template <class First>
inline json_t const * GetJSONObligatoryFieldByPath(json_t const * root, First && path)
{
return GetJSONObligatoryField(root, std::forward<First>(path));
}
template <class First, class... Paths>
inline json_t const * GetJSONObligatoryFieldByPath(json_t const * root, First && path,
Paths &&... paths)
{
json_t const * newRoot = GetJSONObligatoryFieldByPath(root, std::forward<First>(path));
return GetJSONObligatoryFieldByPath(newRoot, std::forward<Paths>(paths)...);
}
bool JSONIsNull(json_t const * root);
} // namespace base
template <typename T>
T FromJSON(json_t const * root)
{
T result{};
FromJSON(root, result);
return result;
}
inline void FromJSON(json_t * root, json_t *& value) { value = root; }
inline void FromJSON(json_t const * root, json_t const *& value) { value = root; }
void FromJSON(json_t const * root, double & result);
void FromJSON(json_t const * root, bool & result);
template <typename T, typename std::enable_if<std::is_integral<T>::value, void>::type * = nullptr>
void FromJSON(json_t const * root, T & result)
{
if (!json_is_number(root))
MYTHROW(base::Json::Exception, ("Object must contain a json number."));
result = static_cast<T>(json_integer_value(root));
}
std::string FromJSONToString(json_t const * root);
template <typename T>
T FromJSONObject(json_t const * root, char const * field)
{
auto const * json = base::GetJSONObligatoryField(root, field);
try
{
return FromJSON<T>(json);
}
catch (base::Json::Exception const & e)
{
MYTHROW(base::Json::Exception, ("An error occured while parsing field", field, e.Msg()));
}
}
template <typename T>
void FromJSONObject(json_t * root, std::string const & field, T & result)
{
auto * json = base::GetJSONObligatoryField(root, field);
try
{
FromJSON(json, result);
}
catch (base::Json::Exception const & e)
{
MYTHROW(base::Json::Exception, ("An error occured while parsing field", field, e.Msg()));
}
}
template <typename T>
boost::optional<T> FromJSONObjectOptional(json_t const * root, char const * field)
{
auto * json = base::GetJSONOptionalField(root, field);
if (!json)
return {};
boost::optional<T> result{T{}};
FromJSON(json, *result);
return result;
}
template <typename T>
void FromJSONObjectOptionalField(json_t const * root, std::string const & field, T & result)
{
auto * json = base::GetJSONOptionalField(root, field);
if (!json)
{
result = T{};
return;
}
FromJSON(json, result);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value, void>::type * = nullptr>
inline base::JSONPtr ToJSON(T value)
{
return base::NewJSONInt(value);
}
inline base::JSONPtr ToJSON(double value) { return base::NewJSONReal(value); }
inline base::JSONPtr ToJSON(bool value) { return base::NewJSONBool(value); }
inline base::JSONPtr ToJSON(char const * s) { return base::NewJSONString(s); }
template <typename T>
void ToJSONArray(json_t & root, T const & value)
{
json_array_append_new(&root, ToJSON(value).release());
}
inline void ToJSONArray(json_t & parent, base::JSONPtr & child)
{
json_array_append_new(&parent, child.release());
}
inline void ToJSONArray(json_t & parent, json_t & child) { json_array_append_new(&parent, &child); }
template <typename T>
void ToJSONObject(json_t & root, char const * field, T const & value)
{
json_object_set_new(&root, field, ToJSON(value).release());
}
inline void ToJSONObject(json_t & parent, char const * field, base::JSONPtr && child)
{
json_object_set_new(&parent, field, child.release());
}
inline void ToJSONObject(json_t & parent, char const * field, base::JSONPtr & child)
{
json_object_set_new(&parent, field, child.release());
}
inline void ToJSONObject(json_t & parent, char const * field, json_t & child)
{
json_object_set_new(&parent, field, &child);
}
template <typename T>
void ToJSONObject(json_t & root, std::string const & field, T const & value)
{
ToJSONObject(root, field.c_str(), value);
}
inline void ToJSONObject(json_t & parent, std::string const & field, base::JSONPtr && child)
{
ToJSONObject(parent, field.c_str(), std::move(child));
}
inline void ToJSONObject(json_t & parent, std::string const & field, base::JSONPtr & child)
{
ToJSONObject(parent, field.c_str(), child);
}
inline void ToJSONObject(json_t & parent, std::string const & field, json_t & child)
{
ToJSONObject(parent, field.c_str(), child);
}
template <typename T>
void FromJSONObject(json_t * root, std::string const & field, std::vector<T> & result)
{
auto * arr = base::GetJSONObligatoryField(root, field);
if (!json_is_array(arr))
MYTHROW(base::Json::Exception, ("The field", field, "must contain a json array."));
size_t sz = json_array_size(arr);
result.resize(sz);
for (size_t i = 0; i < sz; ++i)
FromJSON(json_array_get(arr, i), result[i]);
}
// The function tries to parse array of values from a value
// corresponding to |field| in a json object corresponding to |root|.
// Returns true when the value is non-null and array is successfully
// parsed. Returns false when there is no such |field| in the |root|
// or the value is null. Also, the method may throw an exception in
// case of json parsing errors.
template <typename T>
bool FromJSONObjectOptional(json_t * root, std::string const & field, std::vector<T> & result)
{
auto * arr = base::GetJSONOptionalField(root, field);
if (!arr || base::JSONIsNull(arr))
{
result.clear();
return false;
}
if (!json_is_array(arr))
MYTHROW(base::Json::Exception, ("The field", field, "must contain a json array."));
size_t const sz = json_array_size(arr);
result.resize(sz);
for (size_t i = 0; i < sz; ++i)
FromJSON(json_array_get(arr, i), result[i]);
return true;
}
template <typename T>
void ToJSONObject(json_t & root, char const * field, std::vector<T> const & values)
{
auto arr = base::NewJSONArray();
for (auto const & value : values)
json_array_append_new(arr.get(), ToJSON(value).release());
json_object_set_new(&root, field, arr.release());
}
template <typename T>
void ToJSONObject(json_t & root, std::string const & field, std::vector<T> const & values)
{
ToJSONObject(root, field.c_str(), values);
}
template <typename T>
void FromJSONObjectOptionalField(json_t * root, std::string const & field, std::vector<T> & result)
{
FromJSONObjectOptionalField(const_cast<json_t const *>(root), field, result);
}
template <typename T>
void FromJSONObjectOptionalField(json_t const * root, std::string const & field, std::vector<T> & result)
{
json_t const * arr = base::GetJSONOptionalField(root, field);
if (!arr)
{
result.clear();
return;
}
if (!json_is_array(arr))
MYTHROW(base::Json::Exception, ("The field", field, "must contain a json array."));
size_t sz = json_array_size(arr);
result.resize(sz);
for (size_t i = 0; i < sz; ++i)
FromJSON(json_array_get(arr, i), result[i]);
}
struct JSONFreeDeleter
{
void operator()(char * buffer) const { free(buffer); }
};
namespace std
{
void FromJSON(json_t const * root, std::string & result);
inline base::JSONPtr ToJSON(std::string const & s) { return base::NewJSONString(s); }
} // namespace std
namespace strings
{
void FromJSON(json_t const * root, UniString & result);
base::JSONPtr ToJSON(UniString const & s);
} // namespace strings
<|endoftext|> |
<commit_before>
#include <cstdlib>
#include <boost/test/unit_test.hpp>
#include <cucumber-cpp/defs.hpp>
#include <QApplication>
#include <QTest>
#include <CalculatorWidget.h>
static int argc = 0;
static QApplication app(argc, 0);
static int milliseconds = -1;
int millisecondsToWait() {
if (milliseconds < 0)
{
char* envVariable = getenv("CUKE_CALCQT_WAIT");
milliseconds = (0 != envVariable) ? atoi(envVariable) : 0;
}
return milliseconds;
}
std::istream& operator>> (std::istream& in, QString& val) { std::string s; in >> s; val = s.c_str(); return in; }
std::ostream& operator<< (std::ostream& out, const QString& val) { out << val.toAscii().data(); return out; }
GIVEN("^I just turned on the calculator$") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
calculator->move(0, 0);
calculator->show();
QTest::qWaitForWindowShown(calculator.get());
QTest::qWait(millisecondsToWait());
}
WHEN("^I press (\\d+)$") {
REGEX_PARAM(unsigned int, n);
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_0 + n, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press add") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Plus, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press calculate") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Return, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press clear") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Escape, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press subtract") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Minus, Qt::NoModifier, millisecondsToWait());
}
THEN("^the display should be empty$") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
BOOST_CHECK_EQUAL(calculator->display().size(), 0);
QTest::qWait(millisecondsToWait());
}
THEN("^the display should show (.*)$") {
REGEX_PARAM(QString, expected);
cucumber::ScenarioScope<CalculatorWidget> calculator;
BOOST_CHECK_EQUAL(expected, calculator->display());
QTest::qWait(millisecondsToWait());
}
<commit_msg>renamed delay env variable to CALCQT_STEP_DELAY<commit_after>
#include <cstdlib>
#include <boost/test/unit_test.hpp>
#include <cucumber-cpp/defs.hpp>
#include <QApplication>
#include <QTest>
#include <CalculatorWidget.h>
static int argc = 0;
static QApplication app(argc, 0);
static int milliseconds = -1;
int millisecondsToWait() {
if (milliseconds < 0)
{
char* envVariable = getenv("CALCQT_STEP_DELAY");
milliseconds = (0 != envVariable) ? atoi(envVariable) : 0;
}
return milliseconds;
}
std::istream& operator>> (std::istream& in, QString& val) { std::string s; in >> s; val = s.c_str(); return in; }
std::ostream& operator<< (std::ostream& out, const QString& val) { out << val.toAscii().data(); return out; }
GIVEN("^I just turned on the calculator$") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
calculator->move(0, 0);
calculator->show();
QTest::qWaitForWindowShown(calculator.get());
QTest::qWait(millisecondsToWait());
}
WHEN("^I press (\\d+)$") {
REGEX_PARAM(unsigned int, n);
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_0 + n, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press add") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Plus, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press calculate") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Return, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press clear") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Escape, Qt::NoModifier, millisecondsToWait());
}
WHEN("^I press subtract") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
QTest::keyClick(calculator.get(), Qt::Key_Minus, Qt::NoModifier, millisecondsToWait());
}
THEN("^the display should be empty$") {
cucumber::ScenarioScope<CalculatorWidget> calculator;
BOOST_CHECK_EQUAL(calculator->display().size(), 0);
QTest::qWait(millisecondsToWait());
}
THEN("^the display should show (.*)$") {
REGEX_PARAM(QString, expected);
cucumber::ScenarioScope<CalculatorWidget> calculator;
BOOST_CHECK_EQUAL(expected, calculator->display());
QTest::qWait(millisecondsToWait());
}
<|endoftext|> |
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Ruben Van Boxem
*
* 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.
**/
/*
* Signal
* Registers observers.
* Notifies registered observers.
*/
#include <algorithm>
#include <functional>
#include <mutex>
#include <vector>
namespace skui
{
namespace core
{
namespace implementation
{
template<typename... ArgTypes>
class signal_base
{
public:
using function_type = void(*)(ArgTypes...);
using slot_type = std::function<void(ArgTypes...)>;
signal_base() = default;
signal_base(const signal_base& other) : slots(other.slots) {}
signal_base(signal_base&& other) : slots(std::move(other.slots)) {}
signal_base& operator=(signal_base other) { swap(slots, other.slots); return *this; }
void connect(slot_type&& slot)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.emplace_back(slot);
}
bool disconnect(slot_type&& slot)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
auto function_pointer = slot.template target<function_type>();
const auto result_it = std::find_if(begin(slots), end(slots),
[&function_pointer](slot_type& connected_slot)
{
return function_pointer == connected_slot.template target<function_type>();
});
if(result_it != end(slots))
{
slots.erase(result_it);
return true;
}
return false;
}
void disconnect_all()
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.clear();
}
protected:
// mutable here allows to connect to a const object's signals
mutable std::vector<slot_type> slots;
mutable std::mutex slots_mutex;
};
}
template<typename... ArgTypes>
class signal : public implementation::signal_base<ArgTypes...>
{
public:
signal() = default;
void emit(ArgTypes... arguments) const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& slot : this->slots)
{
slot(arguments...);
}
}
};
// Parameterless specialization
template<> class signal<> : public implementation::signal_base<>
{
public:
signal() = default;
void emit() const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& slot : this->slots)
{
slot();
}
}
};
}
}
<commit_msg>Add object (void*) pointer in preparation to disconnecting member slots.<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Ruben Van Boxem
*
* 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.
**/
/*
* Signal
* Registers observers.
* Notifies registered observers.
*/
#include <algorithm>
#include <functional>
#include <mutex>
#include <utility>
#include <vector>
namespace skui
{
namespace core
{
namespace implementation
{
template<typename... ArgTypes>
class signal_base
{
public:
using function_type = void(*)(ArgTypes...);
using slot_type = std::function<void(ArgTypes...)>;
signal_base() = default;
signal_base(const signal_base& other) : slots(other.slots) {}
signal_base(signal_base&& other) : slots(std::move(other.slots)) {}
signal_base& operator=(signal_base other) { swap(slots, other.slots); return *this; }
void connect(slot_type&& slot)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.emplace_back(nullptr, slot);
}
bool disconnect(slot_type&& slot)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
auto function_pointer = slot.template target<function_type>();
const auto result_it = std::find_if(begin(slots), end(slots),
[&function_pointer](std::pair<void*, slot_type>& object_slot)
{
return function_pointer == object_slot.second.template target<function_type>();
});
if(result_it != end(slots))
{
slots.erase(result_it);
return true;
}
return false;
}
void disconnect_all()
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.clear();
}
protected:
// mutable here allows to connect to a const object's signals
mutable std::vector<std::pair<void*, slot_type>> slots;
mutable std::mutex slots_mutex;
};
}
template<typename... ArgTypes>
class signal : public implementation::signal_base<ArgTypes...>
{
public:
signal() = default;
void emit(ArgTypes... arguments) const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
object_slot.second(arguments...);
}
}
};
// Parameterless specialization
template<> class signal<> : public implementation::signal_base<>
{
public:
signal() = default;
void emit() const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot_pair : this->slots)
{
object_slot_pair.second();
}
}
};
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "manipulator/details/base.hpp"
#include "manipulator/details/types.hpp"
#include <json/json.hpp>
#include <unordered_set>
#include <vector>
namespace krbn {
namespace manipulator {
namespace details {
class basic final : public base {
public:
class manipulated_original_event final {
public:
manipulated_original_event(device_id device_id,
const event_queue::queued_event::event& original_event,
const std::unordered_set<modifier_flag> from_modifiers) : device_id_(device_id),
original_event_(original_event),
from_modifiers_(from_modifiers) {
}
device_id get_device_id(void) const {
return device_id_;
}
const event_queue::queued_event::event& get_original_event(void) const {
return original_event_;
}
const std::unordered_set<modifier_flag>& get_from_modifiers(void) const {
return from_modifiers_;
}
bool operator==(const manipulated_original_event& other) const {
// Do not compare `from_modifiers_`.
return get_device_id() == other.get_device_id() &&
get_original_event() == other.get_original_event();
}
private:
device_id device_id_;
event_queue::queued_event::event original_event_;
std::unordered_set<modifier_flag> from_modifiers_;
};
basic(const nlohmann::json& json) : base(),
from_(json.find("from") != std::end(json) ? json["from"] : nlohmann::json()) {
{
const std::string key = "to";
if (json.find(key) != std::end(json) && json[key].is_array()) {
for (const auto& j : json[key]) {
to_.emplace_back(j);
}
}
}
}
basic(const from_event_definition& from,
const to_event_definition& to) : from_(from),
to_({to}) {
}
virtual ~basic(void) {
}
virtual void manipulate(event_queue::queued_event& front_input_event,
const event_queue& input_event_queue,
event_queue& output_event_queue,
uint64_t time_stamp) {
if (!front_input_event.get_valid()) {
return;
}
bool is_target = false;
if (auto key_code = front_input_event.get_event().get_key_code()) {
if (from_.get_key_code() == key_code) {
is_target = true;
}
}
if (auto pointing_button = front_input_event.get_event().get_pointing_button()) {
if (from_.get_pointing_button() == pointing_button) {
is_target = true;
}
}
if (is_target) {
std::unordered_set<modifier_flag> from_modifiers;
if (front_input_event.get_event_type() == event_type::key_down) {
if (!valid_) {
is_target = false;
}
if (auto modifiers = from_.test_modifiers(output_event_queue.get_modifier_flag_manager())) {
from_modifiers = *modifiers;
} else {
is_target = false;
}
if (is_target) {
manipulated_original_events_.emplace_back(front_input_event.get_device_id(),
front_input_event.get_original_event(),
from_modifiers);
}
} else {
// event_type::key_up
// Check original_event in order to determine the correspond key_down is manipulated.
auto it = std::find_if(std::begin(manipulated_original_events_),
std::end(manipulated_original_events_),
[&](const auto& manipulated_original_event) {
return manipulated_original_event.get_device_id() == front_input_event.get_device_id() &&
manipulated_original_event.get_original_event() == front_input_event.get_original_event();
});
if (it != std::end(manipulated_original_events_)) {
from_modifiers = it->get_from_modifiers();
manipulated_original_events_.erase(it);
} else {
is_target = false;
}
}
if (is_target) {
front_input_event.set_valid(false);
uint64_t time_stamp_delay = 0;
bool persist_from_modifier_manipulation = false;
// Release from_modifiers
if (front_input_event.get_event_type() == event_type::key_down) {
for (const auto& m : from_modifiers) {
if (auto key_code = types::get_key_code(m)) {
event_queue::queued_event event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
event_queue::queued_event::event(*key_code),
event_type::key_up,
front_input_event.get_original_event(),
true);
output_event_queue.push_back_event(event);
}
}
}
// Send events
for (size_t i = 0; i < to_.size(); ++i) {
if (auto event = to_[i].to_event()) {
if (front_input_event.get_event_type() == event_type::key_down) {
enqueue_to_modifiers(to_[i],
event_type::key_down,
front_input_event,
time_stamp_delay,
output_event_queue);
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
*event,
event_type::key_down,
front_input_event.get_original_event());
if (i != to_.size() - 1) {
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
*event,
event_type::key_up,
front_input_event.get_original_event());
if (auto key_code = event->get_key_code()) {
if (types::get_modifier_flag(*key_code) != modifier_flag::zero) {
persist_from_modifier_manipulation = true;
}
}
}
enqueue_to_modifiers(to_[i],
event_type::key_up,
front_input_event,
time_stamp_delay,
output_event_queue);
} else {
// event_type::key_up
if (i == to_.size() - 1) {
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
*event,
event_type::key_up,
front_input_event.get_original_event());
}
}
}
}
// Restore from_modifiers
if ((front_input_event.get_event_type() == event_type::key_down) ||
(front_input_event.get_event_type() == event_type::key_up && persist_from_modifier_manipulation)) {
for (const auto& m : from_modifiers) {
if (auto key_code = types::get_key_code(m)) {
event_queue::queued_event event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
event_queue::queued_event::event(*key_code),
event_type::key_down,
front_input_event.get_original_event(),
!persist_from_modifier_manipulation);
output_event_queue.push_back_event(event);
}
}
}
output_event_queue.increase_time_stamp_delay(time_stamp_delay - 1);
}
}
}
virtual bool active(void) const {
return !manipulated_original_events_.empty();
}
virtual void handle_device_ungrabbed_event(device_id device_id,
const event_queue& output_event_queue,
uint64_t time_stamp) {
manipulated_original_events_.erase(std::remove_if(std::begin(manipulated_original_events_),
std::end(manipulated_original_events_),
[&](const auto& e) {
return e.get_device_id() == device_id;
}),
std::end(manipulated_original_events_));
}
const from_event_definition& get_from(void) const {
return from_;
}
const std::vector<to_event_definition>& get_to(void) const {
return to_;
}
void enqueue_to_modifiers(const to_event_definition& to,
event_type event_type,
const event_queue::queued_event& front_input_event,
uint64_t& time_stamp_delay,
event_queue& output_event_queue) {
for (const auto& modifier : to.get_modifiers()) {
// `event_definition::get_modifiers` might return two modifier_flags.
// (eg. `modifier_flag::left_shift` and `modifier_flag::right_shift` for `modifier::shift`.)
// We use the first modifier_flag.
auto modifier_flags = event_definition::get_modifier_flags(modifier);
if (!modifier_flags.empty()) {
auto modifier_flag = modifier_flags.front();
if (auto key_code = types::get_key_code(modifier_flag)) {
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
event_queue::queued_event::event(*key_code),
event_type,
front_input_event.get_original_event(),
true);
}
}
}
}
private:
from_event_definition from_;
std::vector<to_event_definition> to_;
std::vector<manipulated_original_event> manipulated_original_events_;
};
} // namespace details
} // namespace manipulator
} // namespace krbn
<commit_msg>call increase_time_stamp_delay only when time_stamp_delay > 0<commit_after>#pragma once
#include "manipulator/details/base.hpp"
#include "manipulator/details/types.hpp"
#include <json/json.hpp>
#include <unordered_set>
#include <vector>
namespace krbn {
namespace manipulator {
namespace details {
class basic final : public base {
public:
class manipulated_original_event final {
public:
manipulated_original_event(device_id device_id,
const event_queue::queued_event::event& original_event,
const std::unordered_set<modifier_flag> from_modifiers) : device_id_(device_id),
original_event_(original_event),
from_modifiers_(from_modifiers) {
}
device_id get_device_id(void) const {
return device_id_;
}
const event_queue::queued_event::event& get_original_event(void) const {
return original_event_;
}
const std::unordered_set<modifier_flag>& get_from_modifiers(void) const {
return from_modifiers_;
}
bool operator==(const manipulated_original_event& other) const {
// Do not compare `from_modifiers_`.
return get_device_id() == other.get_device_id() &&
get_original_event() == other.get_original_event();
}
private:
device_id device_id_;
event_queue::queued_event::event original_event_;
std::unordered_set<modifier_flag> from_modifiers_;
};
basic(const nlohmann::json& json) : base(),
from_(json.find("from") != std::end(json) ? json["from"] : nlohmann::json()) {
{
const std::string key = "to";
if (json.find(key) != std::end(json) && json[key].is_array()) {
for (const auto& j : json[key]) {
to_.emplace_back(j);
}
}
}
}
basic(const from_event_definition& from,
const to_event_definition& to) : from_(from),
to_({to}) {
}
virtual ~basic(void) {
}
virtual void manipulate(event_queue::queued_event& front_input_event,
const event_queue& input_event_queue,
event_queue& output_event_queue,
uint64_t time_stamp) {
if (!front_input_event.get_valid()) {
return;
}
bool is_target = false;
if (auto key_code = front_input_event.get_event().get_key_code()) {
if (from_.get_key_code() == key_code) {
is_target = true;
}
}
if (auto pointing_button = front_input_event.get_event().get_pointing_button()) {
if (from_.get_pointing_button() == pointing_button) {
is_target = true;
}
}
if (is_target) {
std::unordered_set<modifier_flag> from_modifiers;
if (front_input_event.get_event_type() == event_type::key_down) {
if (!valid_) {
is_target = false;
}
if (auto modifiers = from_.test_modifiers(output_event_queue.get_modifier_flag_manager())) {
from_modifiers = *modifiers;
} else {
is_target = false;
}
if (is_target) {
manipulated_original_events_.emplace_back(front_input_event.get_device_id(),
front_input_event.get_original_event(),
from_modifiers);
}
} else {
// event_type::key_up
// Check original_event in order to determine the correspond key_down is manipulated.
auto it = std::find_if(std::begin(manipulated_original_events_),
std::end(manipulated_original_events_),
[&](const auto& manipulated_original_event) {
return manipulated_original_event.get_device_id() == front_input_event.get_device_id() &&
manipulated_original_event.get_original_event() == front_input_event.get_original_event();
});
if (it != std::end(manipulated_original_events_)) {
from_modifiers = it->get_from_modifiers();
manipulated_original_events_.erase(it);
} else {
is_target = false;
}
}
if (is_target) {
front_input_event.set_valid(false);
uint64_t time_stamp_delay = 0;
bool persist_from_modifier_manipulation = false;
// Release from_modifiers
if (front_input_event.get_event_type() == event_type::key_down) {
for (const auto& m : from_modifiers) {
if (auto key_code = types::get_key_code(m)) {
event_queue::queued_event event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
event_queue::queued_event::event(*key_code),
event_type::key_up,
front_input_event.get_original_event(),
true);
output_event_queue.push_back_event(event);
}
}
}
// Send events
for (size_t i = 0; i < to_.size(); ++i) {
if (auto event = to_[i].to_event()) {
if (front_input_event.get_event_type() == event_type::key_down) {
enqueue_to_modifiers(to_[i],
event_type::key_down,
front_input_event,
time_stamp_delay,
output_event_queue);
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
*event,
event_type::key_down,
front_input_event.get_original_event());
if (i != to_.size() - 1) {
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
*event,
event_type::key_up,
front_input_event.get_original_event());
if (auto key_code = event->get_key_code()) {
if (types::get_modifier_flag(*key_code) != modifier_flag::zero) {
persist_from_modifier_manipulation = true;
}
}
}
enqueue_to_modifiers(to_[i],
event_type::key_up,
front_input_event,
time_stamp_delay,
output_event_queue);
} else {
// event_type::key_up
if (i == to_.size() - 1) {
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
*event,
event_type::key_up,
front_input_event.get_original_event());
}
}
}
}
// Restore from_modifiers
if ((front_input_event.get_event_type() == event_type::key_down) ||
(front_input_event.get_event_type() == event_type::key_up && persist_from_modifier_manipulation)) {
for (const auto& m : from_modifiers) {
if (auto key_code = types::get_key_code(m)) {
event_queue::queued_event event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
event_queue::queued_event::event(*key_code),
event_type::key_down,
front_input_event.get_original_event(),
!persist_from_modifier_manipulation);
output_event_queue.push_back_event(event);
}
}
}
if (time_stamp_delay > 0) {
output_event_queue.increase_time_stamp_delay(time_stamp_delay - 1);
}
}
}
}
virtual bool active(void) const {
return !manipulated_original_events_.empty();
}
virtual void handle_device_ungrabbed_event(device_id device_id,
const event_queue& output_event_queue,
uint64_t time_stamp) {
manipulated_original_events_.erase(std::remove_if(std::begin(manipulated_original_events_),
std::end(manipulated_original_events_),
[&](const auto& e) {
return e.get_device_id() == device_id;
}),
std::end(manipulated_original_events_));
}
const from_event_definition& get_from(void) const {
return from_;
}
const std::vector<to_event_definition>& get_to(void) const {
return to_;
}
void enqueue_to_modifiers(const to_event_definition& to,
event_type event_type,
const event_queue::queued_event& front_input_event,
uint64_t& time_stamp_delay,
event_queue& output_event_queue) {
for (const auto& modifier : to.get_modifiers()) {
// `event_definition::get_modifiers` might return two modifier_flags.
// (eg. `modifier_flag::left_shift` and `modifier_flag::right_shift` for `modifier::shift`.)
// We use the first modifier_flag.
auto modifier_flags = event_definition::get_modifier_flags(modifier);
if (!modifier_flags.empty()) {
auto modifier_flag = modifier_flags.front();
if (auto key_code = types::get_key_code(modifier_flag)) {
output_event_queue.emplace_back_event(front_input_event.get_device_id(),
front_input_event.get_time_stamp() + time_stamp_delay++,
event_queue::queued_event::event(*key_code),
event_type,
front_input_event.get_original_event(),
true);
}
}
}
}
private:
from_event_definition from_;
std::vector<to_event_definition> to_;
std::vector<manipulated_original_event> manipulated_original_events_;
};
} // namespace details
} // namespace manipulator
} // namespace krbn
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/lincoln/protocol/brakeinfo_74.h"
#include "gtest/gtest.h"
namespace apollo {
namespace canbus {
namespace lincoln {
class Brakeinfo74Test : public ::testing::Test {
public:
virtual void SetUp() {}
};
TEST_F(Brakeinfo74Test, simple) {
Brakeinfo74 brakeinfo;
uint8_t data[8] = {0x64U};
int32_t length = 8;
ChassisDetail cd;
brakeinfo.Parse(data, length, &cd);
EXPECT_FALSE(cd.esp().is_abs_active());
EXPECT_FALSE(cd.esp().is_abs_enabled());
EXPECT_FALSE(cd.esp().is_stab_active());
EXPECT_FALSE(cd.esp().is_stab_enabled());
EXPECT_FALSE(cd.esp().is_trac_active());
EXPECT_FALSE(cd.esp().is_trac_enabled());
EXPECT_EQ(cd.epb().parking_brake_status(), Epb::PBRAKE_OFF);
EXPECT_DOUBLE_EQ(cd.brake().brake_torque_req(), 400.0);
EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_INACTIVE);
EXPECT_DOUBLE_EQ(cd.brake().brake_torque_act(), 0.0);
EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_OFF);
EXPECT_DOUBLE_EQ(cd.brake().wheel_torque_act(), 0.0);
EXPECT_FALSE(cd.vehicle_spd().is_vehicle_standstill());
EXPECT_DOUBLE_EQ(cd.vehicle_spd().acc_est(), 0.0);
}
} // namespace lincoln
} // namespace apollo
} // namespace canbus
<commit_msg>Use full length test data in brakeinfo_74_test<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/lincoln/protocol/brakeinfo_74.h"
#include "gtest/gtest.h"
namespace apollo {
namespace canbus {
namespace lincoln {
class Brakeinfo74Test : public ::testing::Test {
public:
virtual void SetUp() {}
};
TEST_F(Brakeinfo74Test, simple) {
Brakeinfo74 brakeinfo;
uint8_t data[8] = {0x64U, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};
int32_t length = 8;
ChassisDetail cd;
brakeinfo.Parse(data, length, &cd);
EXPECT_TRUE(cd.esp().is_abs_active());
EXPECT_FALSE(cd.esp().is_abs_enabled());
EXPECT_TRUE(cd.esp().is_stab_active());
EXPECT_FALSE(cd.esp().is_stab_enabled());
EXPECT_FALSE(cd.esp().is_trac_active());
EXPECT_FALSE(cd.esp().is_trac_enabled());
EXPECT_EQ(cd.epb().parking_brake_status(), Epb::PBRAKE_OFF);
EXPECT_DOUBLE_EQ(cd.brake().brake_torque_req(), 2448.0);
EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_INACTIVE);
EXPECT_DOUBLE_EQ(cd.brake().brake_torque_act(), 4108.0);
EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_OFF);
EXPECT_DOUBLE_EQ(cd.brake().wheel_torque_act(), 18500.0);
EXPECT_FALSE(cd.vehicle_spd().is_vehicle_standstill());
EXPECT_DOUBLE_EQ(cd.vehicle_spd().acc_est(), 0.665);
}
} // namespace lincoln
} // namespace apollo
} // namespace canbus
<|endoftext|> |
<commit_before><commit_msg>Bugfix: pass variables of correct type to `VariableStruct` constructor.<commit_after><|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 "net/base/x509_util.h"
#include "net/base/x509_util_nss.h"
#include <cert.h>
#include <secoid.h>
#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "crypto/ec_private_key.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_verifier.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) {
SECItem der_cert;
der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
der_cert.len = length;
der_cert.type = siDERCertBuffer;
// Parse into a certificate structure.
return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL,
PR_FALSE, PR_TRUE);
}
void VerifyCertificateSignature(const std::string& der_cert,
const std::vector<uint8>& der_spki) {
crypto::ScopedPLArenaPool arena;
CERTSignedData sd;
memset(&sd, 0, sizeof(sd));
SECItem der_cert_item = {
siDERCertBuffer,
reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())),
der_cert.size()
};
SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd,
SEC_ASN1_GET(CERT_SignedDataTemplate),
&der_cert_item);
ASSERT_EQ(SECSuccess, rv);
// The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier
// wants the DER encoded form, so re-encode it again.
SECItem* signature_algorithm = SEC_ASN1EncodeItem(
arena.get(),
NULL,
&sd.signatureAlgorithm,
SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
ASSERT_TRUE(signature_algorithm);
crypto::SignatureVerifier verifier;
bool ok = verifier.VerifyInit(
signature_algorithm->data,
signature_algorithm->len,
sd.signature.data,
sd.signature.len / 8, // Signature is a BIT STRING, convert to bytes.
&der_spki[0],
der_spki.size());
ASSERT_TRUE(ok);
verifier.VerifyUpdate(sd.data.data,
sd.data.len);
ok = verifier.VerifyFinal();
EXPECT_TRUE(ok);
}
void VerifyOriginBoundCert(const std::string& origin,
const std::string& der_cert) {
// Origin Bound Cert OID.
static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6";
// Create object neccessary for extension lookup call.
SECItem extension_object = {
siAsciiString,
(unsigned char*)origin.data(),
origin.size()
};
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes(
der_cert.data(), der_cert.size());
ASSERT_TRUE(cert);
EXPECT_EQ("anonymous.invalid", cert->subject().GetDisplayName());
EXPECT_FALSE(cert->HasExpired());
// IA5Encode and arena allocate SECItem.
PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
SECItem* expected = SEC_ASN1EncodeItem(arena,
NULL,
&extension_object,
SEC_ASN1_GET(SEC_IA5StringTemplate));
ASSERT_NE(static_cast<SECItem*>(NULL), expected);
// Create OID SECItem.
SECItem ob_cert_oid = { siDEROID, NULL, 0 };
SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid,
oid_string, 0);
ASSERT_EQ(SECSuccess, ok);
SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid);
ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag);
// This test is run on Mac and Win where X509Certificate::os_cert_handle isn't
// an NSS type, so we have to manually create a NSS certificate object so we
// can use CERT_FindCertExtension.
CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes(
der_cert.data(), der_cert.size());
// Lookup Origin Bound Cert extension in generated cert.
SECItem actual = { siBuffer, NULL, 0 };
ok = CERT_FindCertExtension(nss_cert,
ob_cert_oid_tag,
&actual);
CERT_DestroyCertificate(nss_cert);
ASSERT_EQ(SECSuccess, ok);
// Compare expected and actual extension values.
PRBool result = SECITEM_ItemsAreEqual(expected, &actual);
ASSERT_TRUE(result);
// Do Cleanup.
SECITEM_FreeItem(&actual, PR_FALSE);
PORT_FreeArena(arena, PR_FALSE);
}
} // namespace
// This test creates an origin-bound cert from a RSA private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertRSA) {
// Create a sample ASCII weborigin.
std::string origin = "http://weborigin.com:443";
scoped_ptr<crypto::RSAPrivateKey> private_key(
crypto::RSAPrivateKey::Create(1024));
std::string der_cert;
ASSERT_TRUE(x509_util::CreateOriginBoundCertRSA(private_key.get(),
origin, 1,
base::TimeDelta::FromDays(1),
&der_cert));
VerifyOriginBoundCert(origin, der_cert);
std::vector<uint8> spki;
ASSERT_TRUE(private_key->ExportPublicKey(&spki));
VerifyCertificateSignature(der_cert, spki);
}
// This test creates an origin-bound cert from an EC private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertEC) {
// Create a sample ASCII weborigin.
std::string origin = "http://weborigin.com:443";
scoped_ptr<crypto::ECPrivateKey> private_key(
crypto::ECPrivateKey::Create());
std::string der_cert;
ASSERT_TRUE(x509_util::CreateOriginBoundCertEC(private_key.get(),
origin, 1,
base::TimeDelta::FromDays(1),
&der_cert));
VerifyOriginBoundCert(origin, der_cert);
#if !defined(OS_WIN) && !defined(OS_MACOSX)
// signature_verifier_win and signature_verifier_mac can't handle EC certs.
std::vector<uint8> spki;
ASSERT_TRUE(private_key->ExportPublicKey(&spki));
VerifyCertificateSignature(der_cert, spki);
#endif
}
} // namespace net
<commit_msg>Fix leak in X509UtilNSSTest VerifyCertificateSignature.<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 "net/base/x509_util.h"
#include "net/base/x509_util_nss.h"
#include <cert.h>
#include <secoid.h>
#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "crypto/ec_private_key.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_verifier.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) {
SECItem der_cert;
der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
der_cert.len = length;
der_cert.type = siDERCertBuffer;
// Parse into a certificate structure.
return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL,
PR_FALSE, PR_TRUE);
}
void VerifyCertificateSignature(const std::string& der_cert,
const std::vector<uint8>& der_spki) {
crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
CERTSignedData sd;
memset(&sd, 0, sizeof(sd));
SECItem der_cert_item = {
siDERCertBuffer,
reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())),
der_cert.size()
};
SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd,
SEC_ASN1_GET(CERT_SignedDataTemplate),
&der_cert_item);
ASSERT_EQ(SECSuccess, rv);
// The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier
// wants the DER encoded form, so re-encode it again.
SECItem* signature_algorithm = SEC_ASN1EncodeItem(
arena.get(),
NULL,
&sd.signatureAlgorithm,
SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
ASSERT_TRUE(signature_algorithm);
crypto::SignatureVerifier verifier;
bool ok = verifier.VerifyInit(
signature_algorithm->data,
signature_algorithm->len,
sd.signature.data,
sd.signature.len / 8, // Signature is a BIT STRING, convert to bytes.
&der_spki[0],
der_spki.size());
ASSERT_TRUE(ok);
verifier.VerifyUpdate(sd.data.data,
sd.data.len);
ok = verifier.VerifyFinal();
EXPECT_TRUE(ok);
}
void VerifyOriginBoundCert(const std::string& origin,
const std::string& der_cert) {
// Origin Bound Cert OID.
static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6";
// Create object neccessary for extension lookup call.
SECItem extension_object = {
siAsciiString,
(unsigned char*)origin.data(),
origin.size()
};
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes(
der_cert.data(), der_cert.size());
ASSERT_TRUE(cert);
EXPECT_EQ("anonymous.invalid", cert->subject().GetDisplayName());
EXPECT_FALSE(cert->HasExpired());
// IA5Encode and arena allocate SECItem.
PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
SECItem* expected = SEC_ASN1EncodeItem(arena,
NULL,
&extension_object,
SEC_ASN1_GET(SEC_IA5StringTemplate));
ASSERT_NE(static_cast<SECItem*>(NULL), expected);
// Create OID SECItem.
SECItem ob_cert_oid = { siDEROID, NULL, 0 };
SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid,
oid_string, 0);
ASSERT_EQ(SECSuccess, ok);
SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid);
ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag);
// This test is run on Mac and Win where X509Certificate::os_cert_handle isn't
// an NSS type, so we have to manually create a NSS certificate object so we
// can use CERT_FindCertExtension.
CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes(
der_cert.data(), der_cert.size());
// Lookup Origin Bound Cert extension in generated cert.
SECItem actual = { siBuffer, NULL, 0 };
ok = CERT_FindCertExtension(nss_cert,
ob_cert_oid_tag,
&actual);
CERT_DestroyCertificate(nss_cert);
ASSERT_EQ(SECSuccess, ok);
// Compare expected and actual extension values.
PRBool result = SECITEM_ItemsAreEqual(expected, &actual);
ASSERT_TRUE(result);
// Do Cleanup.
SECITEM_FreeItem(&actual, PR_FALSE);
PORT_FreeArena(arena, PR_FALSE);
}
} // namespace
// This test creates an origin-bound cert from a RSA private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertRSA) {
// Create a sample ASCII weborigin.
std::string origin = "http://weborigin.com:443";
scoped_ptr<crypto::RSAPrivateKey> private_key(
crypto::RSAPrivateKey::Create(1024));
std::string der_cert;
ASSERT_TRUE(x509_util::CreateOriginBoundCertRSA(private_key.get(),
origin, 1,
base::TimeDelta::FromDays(1),
&der_cert));
VerifyOriginBoundCert(origin, der_cert);
std::vector<uint8> spki;
ASSERT_TRUE(private_key->ExportPublicKey(&spki));
VerifyCertificateSignature(der_cert, spki);
}
// This test creates an origin-bound cert from an EC private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertEC) {
// Create a sample ASCII weborigin.
std::string origin = "http://weborigin.com:443";
scoped_ptr<crypto::ECPrivateKey> private_key(
crypto::ECPrivateKey::Create());
std::string der_cert;
ASSERT_TRUE(x509_util::CreateOriginBoundCertEC(private_key.get(),
origin, 1,
base::TimeDelta::FromDays(1),
&der_cert));
VerifyOriginBoundCert(origin, der_cert);
#if !defined(OS_WIN) && !defined(OS_MACOSX)
// signature_verifier_win and signature_verifier_mac can't handle EC certs.
std::vector<uint8> spki;
ASSERT_TRUE(private_key->ExportPublicKey(&spki));
VerifyCertificateSignature(der_cert, spki);
#endif
}
} // namespace net
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: bootstrap.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kr $ $Date: 2001-10-05 08:00:21 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <list>
#include <stdio.h>
#include <osl/process.h>
#include <osl/file.h>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <osl/file.hxx>
#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/byteseq.hxx>
#include "macro.hxx"
// I need C++ for static variables and for lists (stl) !
// If we don't want C++, we need another solution for static vars !
using namespace ::rtl;
using namespace ::osl;
struct rtl_bootstrap_NameValue
{
::rtl::OUString sName;
::rtl::OUString sValue;
};
typedef ::std::list< struct rtl_bootstrap_NameValue > NameValueList;
static sal_Bool getFromCommandLineArgs( rtl_uString **ppValue , rtl_uString *pName )
{
static NameValueList *pNameValueList = 0;
if( ! pNameValueList )
{
static NameValueList nameValueList;
sal_Int32 nArgCount = osl_getCommandArgCount();
for(sal_Int32 i = 0; i < nArgCount; ++ i)
{
rtl_uString *pArg = 0;
osl_getCommandArg( i, &pArg );
if( ('-' == pArg->buffer[0] || '/' == pArg->buffer[0] ) &&
'e' == pArg->buffer[1] &&
'n' == pArg->buffer[2] &&
'v' == pArg->buffer[3] &&
':' == pArg->buffer[4] )
{
sal_Int32 nIndex = rtl_ustr_indexOfChar( pArg->buffer, '=' );
if( nIndex >= 0 )
{
struct rtl_bootstrap_NameValue nameValue;
nameValue.sName = OUString( &(pArg->buffer[5]), nIndex - 5 );
nameValue.sValue = OUString( &(pArg->buffer[nIndex+1]) );
if( i == nArgCount-1 &&
nameValue.sValue.getLength() &&
nameValue.sValue[nameValue.sValue.getLength()-1] == 13 )
{
// avoid the 13 linefeed for the last argument,
// when the executable is started from a script,
// that was edited on windows
nameValue.sValue = nameValue.sValue.copy(0,nameValue.sValue.getLength()-1);
}
nameValueList.push_back( nameValue );
}
}
rtl_uString_release( pArg );
}
pNameValueList = &nameValueList;
}
sal_Bool found = sal_False;
OUString name( pName );
for( NameValueList::iterator ii = pNameValueList->begin() ;
ii != pNameValueList->end() ;
++ii )
{
if( (*ii).sName.equals(name) )
{
rtl_uString_assign( ppValue, (*ii).sValue.pData );
found = sal_True;
break;
}
}
return found;
}
static ::rtl::OUString &getIniFileNameImpl()
{
static OUString *pStaticName = 0;
if( ! pStaticName )
{
OUString fileName;
OUString sVarName(RTL_CONSTASCII_USTRINGPARAM("INIFILENAME"));
if(!getFromCommandLineArgs(&fileName.pData, sVarName.pData))
{
osl_getExecutableFile(&fileName.pData);
// get rid of a potential executable extension
OUString progExt = OUString::createFromAscii(".bin");
if(fileName.getLength() > progExt.getLength()
&& fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());
progExt = OUString::createFromAscii(".exe");
if(fileName.getLength() > progExt.getLength()
&& fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());
// append config file suffix
fileName += OUString(RTL_CONSTASCII_USTRINGPARAM(SAL_CONFIGFILE("")));
}
static OUString theFileName;
if(fileName.getLength())
theFileName = fileName;
pStaticName = &theFileName;
}
return *pStaticName;
}
static void getFileSize( oslFileHandle handle, sal_uInt64 *pSize )
{
sal_uInt64 nOldPos=0;
OSL_VERIFY( osl_File_E_None == osl_getFilePos( handle, &nOldPos ) &&
osl_File_E_None == osl_setFilePos( handle, osl_Pos_End , 0 ) &&
osl_File_E_None == osl_getFilePos( handle, pSize ) &&
osl_File_E_None == osl_setFilePos( handle, osl_Pos_Absolut, nOldPos ) );
}
static void getFromEnvironment( rtl_uString **ppValue, rtl_uString *pName )
{
if( osl_Process_E_None != osl_getEnvironment( pName , ppValue ) )
{
// osl behaves different on win or unx.
if( *ppValue )
{
rtl_uString_release( *ppValue );
*ppValue = 0;
}
}
}
static void getFromList(NameValueList *pNameValueList, rtl_uString **ppValue, rtl_uString *pName)
{
OUString name(pName);
for(NameValueList::iterator ii = pNameValueList->begin();
ii != pNameValueList->end();
++ii)
{
if( (*ii).sName.equals(name) )
{
rtl_uString_assign( ppValue, (*ii).sValue.pData );
break;
}
}
}
static sal_Bool getValue(NameValueList *pNameValueList, rtl_uString * pName, rtl_uString ** ppValue, rtl_uString * pDefault)
{
static const OUString sysUserConfig(RTL_CONSTASCII_USTRINGPARAM("SYSUSERCONFIG"));
static const OUString sysUserHome(RTL_CONSTASCII_USTRINGPARAM("SYSUSERHOME"));
sal_Bool result = sal_True;
// we have build ins:
if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserConfig.pData->buffer, sysUserConfig.pData->length))
{
oslSecurity security = osl_getCurrentSecurity();
osl_getConfigDir(security, ppValue);
osl_freeSecurityHandle(security);
}
else if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserHome.pData->buffer, sysUserHome.pData->length))
{
oslSecurity security = osl_getCurrentSecurity();
osl_getHomeDir(security, ppValue);
osl_freeSecurityHandle(security);
}
else
{
getFromCommandLineArgs(ppValue, pName);
if(!*ppValue)
{
getFromList(pNameValueList, ppValue, pName);
if( ! *ppValue )
{
getFromEnvironment( ppValue, pName );
if( ! *ppValue )
{
result = sal_False;
if(pDefault)
rtl_uString_assign( ppValue , pDefault );
}
}
}
}
#ifdef DEBUG
OString sName = OUStringToOString(OUString(pName), RTL_TEXTENCODING_ASCII_US);
OString sValue;
if(*ppValue)
sValue = OUStringToOString(OUString(*ppValue), RTL_TEXTENCODING_ASCII_US);
OSL_TRACE("bootstrap.cxx::getValue - name:%s value:%s\n", sName.getStr(), sValue.getStr());
#endif
return result;
}
typedef struct Bootstrap_Impl {
NameValueList _nameValueList;
OUString _iniName;
} Bootstrap_Impl;
static void fillFromIniFile(Bootstrap_Impl * pBootstrap_Impl)
{
OUString iniName = pBootstrap_Impl->_iniName;
#ifdef DEBUG
OString sFile = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
OSL_TRACE("bootstrap.cxx::fillFromIniFile - %s\n", sFile.getStr());
#endif
oslFileHandle handle;
if(iniName.getLength()
&& osl_File_E_None == osl_openFile(iniName.pData, &handle, osl_File_OpenFlag_Read))
{
ByteSequence seq;
sal_uInt64 nSize = 0;
getFileSize(handle, &nSize);
while( sal_True )
{
sal_uInt64 nPos;
if(osl_File_E_None != osl_getFilePos(handle, &nPos)
|| nPos >= nSize)
break;
if(osl_File_E_None != osl_readLine(handle , (sal_Sequence ** ) &seq))
break;
OString line((const sal_Char *)seq.getConstArray(), seq.getLength());
sal_Int32 nIndex = line.indexOf('=');
struct rtl_bootstrap_NameValue nameValue;
if(nIndex >= 1 && nIndex +1 < line.getLength())
{
nameValue.sName = OStringToOUString(line.copy(0,nIndex).trim(),
RTL_TEXTENCODING_ASCII_US);
nameValue.sValue = OStringToOUString(line.copy(nIndex+1).trim(),
RTL_TEXTENCODING_UTF8);
OString name_tmp = OUStringToOString(nameValue.sName, RTL_TEXTENCODING_ASCII_US);
OString value_tmp = OUStringToOString(nameValue.sValue, RTL_TEXTENCODING_UTF8);
OSL_TRACE("bootstrap.cxx: pushing: name=%s value=%s\n", name_tmp.getStr(), value_tmp.getStr());
pBootstrap_Impl->_nameValueList.push_back(nameValue);
}
}
osl_closeFile(handle);
}
#ifdef DEBUG
else
{
OString file_tmp = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
OSL_TRACE("bootstrap.cxx: couldn't open file: %s", file_tmp.getStr());
}
#endif
}
extern "C"
{
rtlBootstrapHandle SAL_CALL rtl_bootstrap_args_open(rtl_uString * pIniName)
{
OUString workDir;
OUString iniName = OUString(pIniName);
osl_getProcessWorkingDir(&workDir.pData);
FileBase::getAbsoluteFileURL(workDir, iniName, iniName);
Bootstrap_Impl * pBootstrap_Impl = new Bootstrap_Impl;
pBootstrap_Impl->_iniName = iniName;
fillFromIniFile(pBootstrap_Impl);
return pBootstrap_Impl;
}
void SAL_CALL rtl_bootstrap_args_close(rtlBootstrapHandle handle)
{
delete (Bootstrap_Impl *)handle;
}
sal_Bool SAL_CALL rtl_bootstrap_get_from_handle(rtlBootstrapHandle handle, rtl_uString *pName, rtl_uString **ppValue, rtl_uString *pDefault)
{
MutexGuard guard(Mutex::getGlobalMutex());
sal_Bool found = sal_False;
if(ppValue && pName)
{
if(handle) {
if(*ppValue) {
rtl_uString_release(*ppValue);
*ppValue = 0;
}
found = getValue(&((Bootstrap_Impl *)handle)->_nameValueList, pName, ppValue, pDefault);
if(*ppValue)
{
OUString result = expandMacros(&((Bootstrap_Impl *)handle)->_nameValueList, OUString(*ppValue));
rtl_uString_assign(ppValue, result.pData );
}
if(!found) {
// fall back to executable rc
if(((Bootstrap_Impl *)handle)->_iniName != getIniFileNameImpl())
found = rtl_bootstrap_get(pName, ppValue, pDefault);
}
if(!*ppValue)
rtl_uString_new(ppValue);
}
else
found = rtl_bootstrap_get(pName, ppValue, pDefault);
}
return found;
}
void SAL_CALL rtl_bootstrap_get_iniName_from_handle(rtlBootstrapHandle handle, rtl_uString ** ppIniName)
{
if(ppIniName)
if(handle)
rtl_uString_assign(ppIniName, ((Bootstrap_Impl *)handle)->_iniName.pData);
else {
const OUString & iniName = getIniFileNameImpl();
rtl_uString_assign(ppIniName, iniName.pData);
}
}
void SAL_CALL rtl_bootstrap_setIniFileName( rtl_uString *pName )
{
MutexGuard guard( Mutex::getGlobalMutex() );
OUString & file = getIniFileNameImpl();
file = pName;
}
sal_Bool SAL_CALL rtl_bootstrap_get( rtl_uString *pName, rtl_uString **ppValue , rtl_uString *pDefault )
{
MutexGuard guard( Mutex::getGlobalMutex() );
static Bootstrap_Impl * pBootstrap_Impl = 0;
if(!pBootstrap_Impl)
{
static Bootstrap_Impl bootstrap_Impl;
bootstrap_Impl._iniName = getIniFileNameImpl();
fillFromIniFile(&bootstrap_Impl);
pBootstrap_Impl = &bootstrap_Impl;
}
return rtl_bootstrap_get_from_handle(pBootstrap_Impl, pName, ppValue, pDefault);
}
}
<commit_msg>added SYSBINDIR as predefined macro (#88338#)<commit_after>/*************************************************************************
*
* $RCSfile: bootstrap.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kr $ $Date: 2001-10-11 12:56:45 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <list>
#include <stdio.h>
#include <osl/process.h>
#include <osl/file.h>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <osl/file.hxx>
#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/byteseq.hxx>
#include "macro.hxx"
// I need C++ for static variables and for lists (stl) !
// If we don't want C++, we need another solution for static vars !
using namespace ::rtl;
using namespace ::osl;
struct rtl_bootstrap_NameValue
{
::rtl::OUString sName;
::rtl::OUString sValue;
};
typedef ::std::list< struct rtl_bootstrap_NameValue > NameValueList;
static sal_Bool getFromCommandLineArgs( rtl_uString **ppValue , rtl_uString *pName )
{
static NameValueList *pNameValueList = 0;
if( ! pNameValueList )
{
static NameValueList nameValueList;
sal_Int32 nArgCount = osl_getCommandArgCount();
for(sal_Int32 i = 0; i < nArgCount; ++ i)
{
rtl_uString *pArg = 0;
osl_getCommandArg( i, &pArg );
if( ('-' == pArg->buffer[0] || '/' == pArg->buffer[0] ) &&
'e' == pArg->buffer[1] &&
'n' == pArg->buffer[2] &&
'v' == pArg->buffer[3] &&
':' == pArg->buffer[4] )
{
sal_Int32 nIndex = rtl_ustr_indexOfChar( pArg->buffer, '=' );
if( nIndex >= 0 )
{
struct rtl_bootstrap_NameValue nameValue;
nameValue.sName = OUString( &(pArg->buffer[5]), nIndex - 5 );
nameValue.sValue = OUString( &(pArg->buffer[nIndex+1]) );
if( i == nArgCount-1 &&
nameValue.sValue.getLength() &&
nameValue.sValue[nameValue.sValue.getLength()-1] == 13 )
{
// avoid the 13 linefeed for the last argument,
// when the executable is started from a script,
// that was edited on windows
nameValue.sValue = nameValue.sValue.copy(0,nameValue.sValue.getLength()-1);
}
nameValueList.push_back( nameValue );
}
}
rtl_uString_release( pArg );
}
pNameValueList = &nameValueList;
}
sal_Bool found = sal_False;
OUString name( pName );
for( NameValueList::iterator ii = pNameValueList->begin() ;
ii != pNameValueList->end() ;
++ii )
{
if( (*ii).sName.equals(name) )
{
rtl_uString_assign( ppValue, (*ii).sValue.pData );
found = sal_True;
break;
}
}
return found;
}
static ::rtl::OUString &getIniFileNameImpl()
{
static OUString *pStaticName = 0;
if( ! pStaticName )
{
OUString fileName;
OUString sVarName(RTL_CONSTASCII_USTRINGPARAM("INIFILENAME"));
if(!getFromCommandLineArgs(&fileName.pData, sVarName.pData))
{
osl_getExecutableFile(&fileName.pData);
// get rid of a potential executable extension
OUString progExt = OUString::createFromAscii(".bin");
if(fileName.getLength() > progExt.getLength()
&& fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());
progExt = OUString::createFromAscii(".exe");
if(fileName.getLength() > progExt.getLength()
&& fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());
// append config file suffix
fileName += OUString(RTL_CONSTASCII_USTRINGPARAM(SAL_CONFIGFILE("")));
}
static OUString theFileName;
if(fileName.getLength())
theFileName = fileName;
pStaticName = &theFileName;
}
return *pStaticName;
}
static void getFileSize( oslFileHandle handle, sal_uInt64 *pSize )
{
sal_uInt64 nOldPos=0;
OSL_VERIFY( osl_File_E_None == osl_getFilePos( handle, &nOldPos ) &&
osl_File_E_None == osl_setFilePos( handle, osl_Pos_End , 0 ) &&
osl_File_E_None == osl_getFilePos( handle, pSize ) &&
osl_File_E_None == osl_setFilePos( handle, osl_Pos_Absolut, nOldPos ) );
}
static void getFromEnvironment( rtl_uString **ppValue, rtl_uString *pName )
{
if( osl_Process_E_None != osl_getEnvironment( pName , ppValue ) )
{
// osl behaves different on win or unx.
if( *ppValue )
{
rtl_uString_release( *ppValue );
*ppValue = 0;
}
}
}
static void getFromList(NameValueList *pNameValueList, rtl_uString **ppValue, rtl_uString *pName)
{
OUString name(pName);
for(NameValueList::iterator ii = pNameValueList->begin();
ii != pNameValueList->end();
++ii)
{
if( (*ii).sName.equals(name) )
{
rtl_uString_assign( ppValue, (*ii).sValue.pData );
break;
}
}
}
static sal_Bool getValue(NameValueList *pNameValueList, rtl_uString * pName, rtl_uString ** ppValue, rtl_uString * pDefault)
{
static const OUString sysUserConfig(RTL_CONSTASCII_USTRINGPARAM("SYSUSERCONFIG"));
static const OUString sysUserHome (RTL_CONSTASCII_USTRINGPARAM("SYSUSERHOME"));
static const OUString sysBinDir (RTL_CONSTASCII_USTRINGPARAM("SYSBINDIR"));
sal_Bool result = sal_True;
// we have build ins:
if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserConfig.pData->buffer, sysUserConfig.pData->length))
{
oslSecurity security = osl_getCurrentSecurity();
osl_getConfigDir(security, ppValue);
osl_freeSecurityHandle(security);
}
else if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserHome.pData->buffer, sysUserHome.pData->length))
{
oslSecurity security = osl_getCurrentSecurity();
osl_getHomeDir(security, ppValue);
osl_freeSecurityHandle(security);
}
else if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysBinDir.pData->buffer, sysBinDir.pData->length))
osl_getProcessWorkingDir(ppValue);
else
{
getFromCommandLineArgs(ppValue, pName);
if(!*ppValue)
{
getFromList(pNameValueList, ppValue, pName);
if( ! *ppValue )
{
getFromEnvironment( ppValue, pName );
if( ! *ppValue )
{
result = sal_False;
if(pDefault)
rtl_uString_assign( ppValue , pDefault );
}
}
}
}
#ifdef DEBUG
OString sName = OUStringToOString(OUString(pName), RTL_TEXTENCODING_ASCII_US);
OString sValue;
if(*ppValue)
sValue = OUStringToOString(OUString(*ppValue), RTL_TEXTENCODING_ASCII_US);
OSL_TRACE("bootstrap.cxx::getValue - name:%s value:%s\n", sName.getStr(), sValue.getStr());
#endif
return result;
}
typedef struct Bootstrap_Impl {
NameValueList _nameValueList;
OUString _iniName;
} Bootstrap_Impl;
static void fillFromIniFile(Bootstrap_Impl * pBootstrap_Impl)
{
OUString iniName = pBootstrap_Impl->_iniName;
#ifdef DEBUG
OString sFile = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
OSL_TRACE("bootstrap.cxx::fillFromIniFile - %s\n", sFile.getStr());
#endif
oslFileHandle handle;
if(iniName.getLength()
&& osl_File_E_None == osl_openFile(iniName.pData, &handle, osl_File_OpenFlag_Read))
{
ByteSequence seq;
sal_uInt64 nSize = 0;
getFileSize(handle, &nSize);
while( sal_True )
{
sal_uInt64 nPos;
if(osl_File_E_None != osl_getFilePos(handle, &nPos)
|| nPos >= nSize)
break;
if(osl_File_E_None != osl_readLine(handle , (sal_Sequence ** ) &seq))
break;
OString line((const sal_Char *)seq.getConstArray(), seq.getLength());
sal_Int32 nIndex = line.indexOf('=');
struct rtl_bootstrap_NameValue nameValue;
if(nIndex >= 1 && nIndex +1 < line.getLength())
{
nameValue.sName = OStringToOUString(line.copy(0,nIndex).trim(),
RTL_TEXTENCODING_ASCII_US);
nameValue.sValue = OStringToOUString(line.copy(nIndex+1).trim(),
RTL_TEXTENCODING_UTF8);
OString name_tmp = OUStringToOString(nameValue.sName, RTL_TEXTENCODING_ASCII_US);
OString value_tmp = OUStringToOString(nameValue.sValue, RTL_TEXTENCODING_UTF8);
OSL_TRACE("bootstrap.cxx: pushing: name=%s value=%s\n", name_tmp.getStr(), value_tmp.getStr());
pBootstrap_Impl->_nameValueList.push_back(nameValue);
}
}
osl_closeFile(handle);
}
#ifdef DEBUG
else
{
OString file_tmp = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
OSL_TRACE("bootstrap.cxx: couldn't open file: %s", file_tmp.getStr());
}
#endif
}
extern "C"
{
rtlBootstrapHandle SAL_CALL rtl_bootstrap_args_open(rtl_uString * pIniName)
{
OUString workDir;
OUString iniName = OUString(pIniName);
osl_getProcessWorkingDir(&workDir.pData);
FileBase::getAbsoluteFileURL(workDir, iniName, iniName);
Bootstrap_Impl * pBootstrap_Impl = new Bootstrap_Impl;
pBootstrap_Impl->_iniName = iniName;
fillFromIniFile(pBootstrap_Impl);
return pBootstrap_Impl;
}
void SAL_CALL rtl_bootstrap_args_close(rtlBootstrapHandle handle)
{
delete (Bootstrap_Impl *)handle;
}
sal_Bool SAL_CALL rtl_bootstrap_get_from_handle(rtlBootstrapHandle handle, rtl_uString *pName, rtl_uString **ppValue, rtl_uString *pDefault)
{
MutexGuard guard(Mutex::getGlobalMutex());
sal_Bool found = sal_False;
if(ppValue && pName)
{
if(handle) {
if(*ppValue) {
rtl_uString_release(*ppValue);
*ppValue = 0;
}
found = getValue(&((Bootstrap_Impl *)handle)->_nameValueList, pName, ppValue, pDefault);
if(*ppValue)
{
OUString result = expandMacros(&((Bootstrap_Impl *)handle)->_nameValueList, OUString(*ppValue));
rtl_uString_assign(ppValue, result.pData );
}
if(!found) {
// fall back to executable rc
if(((Bootstrap_Impl *)handle)->_iniName != getIniFileNameImpl())
found = rtl_bootstrap_get(pName, ppValue, pDefault);
}
if(!*ppValue)
rtl_uString_new(ppValue);
}
else
found = rtl_bootstrap_get(pName, ppValue, pDefault);
}
return found;
}
void SAL_CALL rtl_bootstrap_get_iniName_from_handle(rtlBootstrapHandle handle, rtl_uString ** ppIniName)
{
if(ppIniName)
if(handle)
rtl_uString_assign(ppIniName, ((Bootstrap_Impl *)handle)->_iniName.pData);
else {
const OUString & iniName = getIniFileNameImpl();
rtl_uString_assign(ppIniName, iniName.pData);
}
}
void SAL_CALL rtl_bootstrap_setIniFileName( rtl_uString *pName )
{
MutexGuard guard( Mutex::getGlobalMutex() );
OUString & file = getIniFileNameImpl();
file = pName;
}
sal_Bool SAL_CALL rtl_bootstrap_get( rtl_uString *pName, rtl_uString **ppValue , rtl_uString *pDefault )
{
MutexGuard guard( Mutex::getGlobalMutex() );
static Bootstrap_Impl * pBootstrap_Impl = 0;
if(!pBootstrap_Impl)
{
static Bootstrap_Impl bootstrap_Impl;
bootstrap_Impl._iniName = getIniFileNameImpl();
fillFromIniFile(&bootstrap_Impl);
pBootstrap_Impl = &bootstrap_Impl;
}
return rtl_bootstrap_get_from_handle(pBootstrap_Impl, pName, ppValue, pDefault);
}
}
<|endoftext|> |
<commit_before>#include "dock.h"
#include "mainwindow.h"
#include "connection.h"
#include "dockmanagerconfig.h"
#include "dockdelegates.h"
#include "controlbar_dockmanager.h"
#include "serialize.h"
#include <ui_controlbarcommon.h>
#include <QScrollBar>
/*#include <ui_controlbarlogs.h>
#include <ui_controlbarplots.h>
#include <ui_controlbartables.h>
#include <ui_controlbargantts.h>*/
DockManager::DockManager (MainWindow * mw, QStringList const & path)
: DockManagerView(mw), ActionAble(path)
, m_main_window(mw)
, m_dockwidget(0)
, m_control_bar(0)
, m_model(0)
, m_config(g_traceServerName)
{
qDebug("%s", __FUNCTION__);
resizeColumnToContents(0);
QString const name = path.join("/");
DockWidget * const dock = new DockWidget(*this, name, m_main_window);
dock->setObjectName(name);
dock->setWindowTitle(name);
dock->setAllowedAreas(Qt::AllDockWidgetAreas);
m_main_window->addDockWidget(Qt::BottomDockWidgetArea, dock);
dock->setAttribute(Qt::WA_DeleteOnClose, false);
dock->setWidget(this);
//if (visible)
// m_main_window->restoreDockWidget(dock);
m_dockwidget = dock;
connect(m_dockwidget, SIGNAL(widgetVisibilityChanged()), m_main_window, SLOT(onDockManagerVisibilityChanged(bool)));
m_control_bar = new ControlBarCommon();
connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int)));
connect(m_dockwidget, SIGNAL(dockClosed()), mw, SLOT(onDockManagerClosed()));
setAllColumnsShowFocus(false);
setExpandsOnDoubleClick(false);
//setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
//setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored);
//header()->setSectionResizeMode(0, QHeaderView::Interactive);
header()->setStretchLastSection(false);
setEditTriggers(QAbstractItemView::NoEditTriggers);
//setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
setItemDelegateForColumn(e_Column_ControlWidget, new ControlWidgetDelegate(*this, this));
setStyleSheet("QTreeView::item{ selection-background-color: #FFE7BA } QTreeView::item{ selection-color: #000000 }");
//horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { border: 1px solid grey; height: 15px; } QScrollBar::handle:horizontal { background: white; min-width: 10px; }");
/*
setStyleSheet(QString::fromUtf8("QScrollBar:vertical {
" border: 1px solid #999999;"
" background:white;"
" width:10px; "
" margin: 0px 0px 0px 0px;"
"}"
"QScrollBar::handle:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));"
" min-height: 0px;"
""
"}"
"QScrollBar::add-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));"
" height: px;"
" subcontrol-position: bottom;"
" subcontrol-origin: margin;"
"}"
"QScrollBar::sub-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));"
" height: 0px;"
" subcontrol-position: top;"
" subcontrol-origin: margin;"
"}"
""));
*/
}
void DockManager::loadConfig (QString const & cfgpath)
{
QString const fname = cfgpath + "/" + g_dockManagerTag;
DockManagerConfig config2(g_traceServerName);
if (!::loadConfigTemplate(config2, fname))
{
m_config.defaultConfig();
}
else
{
m_config = config2;
config2.m_data.root = 0; // @TODO: promyslet.. takle na to urcite zapomenu
}
m_model = new DockManagerModel(*this, this, &m_config.m_data);
setModel(m_model);
bool const on = true;
addActionAble(*this, on, false, true);
}
void DockManager::applyConfig ()
{
for (size_t i = 0, ie = m_config.m_columns_sizes.size(); i < ie; ++i)
header()->resizeSection(static_cast<int>(i), m_config.m_columns_sizes[i]);
if (m_model)
m_model->syncExpandState(this);
}
void DockManager::saveConfig (QString const & path)
{
QString const fname = path + "/" + g_dockManagerTag;
::saveConfigTemplate(m_config, fname);
}
DockManager::~DockManager ()
{
removeActionAble(*this);
}
DockWidget * DockManager::mkDockWidget (DockedWidgetBase & dwb, bool visible)
{
return mkDockWidget(dwb, visible, Qt::BottomDockWidgetArea);
}
DockWidget * DockManager::mkDockWidget (ActionAble & aa, bool visible, Qt::DockWidgetArea area)
{
qDebug("%s", __FUNCTION__);
Q_ASSERT(aa.path().size() > 0);
QString const name = aa.path().join("/");
DockWidget * const dock = new DockWidget(*this, name, m_main_window);
dock->setObjectName(name);
dock->setWindowTitle(name);
dock->setAllowedAreas(Qt::AllDockWidgetAreas);
//dock->setWidget(docked_widget); // @NOTE: commented, it is set by caller
m_main_window->addDockWidget(area, dock);
dock->setAttribute(Qt::WA_DeleteOnClose, false);
if (visible)
m_main_window->restoreDockWidget(dock);
return dock;
}
void DockManager::onWidgetClosed (DockWidget * w)
{
qDebug("%s w=%08x", __FUNCTION__, w);
}
QModelIndex DockManager::addActionAble (ActionAble & aa, bool on, bool close_button, bool control_widget)
{
qDebug("%s aa=%s show=%i", __FUNCTION__, aa.joinedPath().toStdString().c_str(), on);
QModelIndex const idx = m_model->insertItemWithPath(aa.path(), on);
QString const & name = aa.joinedPath();
m_actionables.insert(name, &aa);
m_model->initData(idx, QVariant(on ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole);
if (close_button)
{
QModelIndex const jdx = m_model->index(idx.row(), e_Column_Close, idx.parent());
openPersistentEditor(jdx);
}
if (control_widget)
{
QModelIndex const kdx = m_model->index(idx.row(), e_Column_ControlWidget, idx.parent());
openPersistentEditor(kdx);
}
return idx;
}
QModelIndex DockManager::addActionAble (ActionAble & aa, bool on)
{
return addActionAble(aa, on, true, true);
}
ActionAble const * DockManager::findActionAble (QString const & dst_joined) const
{
actionables_t::const_iterator it = m_actionables.find(dst_joined);
if (it != m_actionables.end() && it.key() == dst_joined)
return *it;
return 0;
}
ActionAble * DockManager::findActionAble (QString const & dst_joined)
{
actionables_t::iterator it = m_actionables.find(dst_joined);
if (it != m_actionables.end() && it.key() == dst_joined)
return *it;
return 0;
}
void DockManager::removeActionAble (ActionAble & aa)
{
qDebug("%s aa=%s", __FUNCTION__, aa.joinedPath().toStdString().c_str());
actionables_t::iterator it = m_actionables.find(aa.joinedPath());
if (it != m_actionables.end() && it.key() == aa.joinedPath())
{
QModelIndex const idx = m_model->testItemWithPath(aa.path());
if (idx.isValid())
for (int j = 1; j < e_max_dockmgr_column; ++j)
closePersistentEditor(m_model->index(idx.row(), j, idx.parent()));
m_actionables.erase(it);
}
}
void DockManager::onColumnResized (int idx, int , int new_size)
{
if (idx < 0) return;
size_t const curr_sz = m_config.m_columns_sizes.size();
if (idx < curr_sz)
{
//qDebug("%s this=0x%08x hsize[%i]=%i", __FUNCTION__, this, idx, new_size);
}
else
{
m_config.m_columns_sizes.resize(idx + 1);
for (size_t i = curr_sz; i < idx + 1; ++i)
m_config.m_columns_sizes[i] = 32;
}
m_config.m_columns_sizes[idx] = new_size;
}
bool DockManager::handleAction (Action * a, E_ActionHandleType sync)
{
QStringList const & src_path = a->m_src_path;
QStringList const & dst_path = a->m_dst_path;
QStringList const & my_addr = path();
if (dst_path.size() == 0)
{
qWarning("DockManager::handleAction empty dst");
return false;
}
Q_ASSERT(my_addr.size() == 1);
int const lvl = dst_path.indexOf(my_addr.at(0), a->m_dst_curr_level);
if (lvl == -1)
{
qWarning("DockManager::handleAction message not for me");
return false;
}
else if (lvl == dst_path.size() - 1)
{
// message just for me! gr8!
a->m_dst_curr_level = lvl;
a->m_dst = this;
return true;
}
else
{
// message for my children
a->m_dst_curr_level = lvl + 1;
if (a->m_dst_curr_level >= 0 && a->m_dst_curr_level < dst_path.size())
{
QString const dst_joined = dst_path.join("/");
actionables_t::iterator it = m_actionables.find(dst_joined);
if (it != m_actionables.end() && it.key() == dst_joined)
{
qDebug("delivering action to: %s", dst_joined.toStdString().c_str());
ActionAble * const next_hop = it.value();
next_hop->handleAction(a, sync); //@NOTE: e_Close can invalidate iterator
}
else
{
//@TODO: find least common subpath
}
}
else
{
qWarning("DockManager::handleAction hmm? what?");
}
}
return false;
}
void DockManager::onCloseButton ()
{
QVariant v = QObject::sender()->property("idx");
if (v.canConvert<QModelIndex>())
{
QModelIndex const idx = v.value<QModelIndex>();
if (TreeModel<DockedInfo>::node_t * const n = m_model->getItemFromIndex(idx))
{
QStringList const & dst_path = n->data.m_path;
Action a;
a.m_type = e_Close;
a.m_src_path = path();
a.m_src = this;
a.m_dst_path = dst_path;
handleAction(&a, e_Sync);
}
}
}
<commit_msg>* fixed destruction of dockmanager<commit_after>#include "dock.h"
#include "mainwindow.h"
#include "connection.h"
#include "dockmanagerconfig.h"
#include "dockdelegates.h"
#include "controlbar_dockmanager.h"
#include "serialize.h"
#include <ui_controlbarcommon.h>
#include <QScrollBar>
/*#include <ui_controlbarlogs.h>
#include <ui_controlbarplots.h>
#include <ui_controlbartables.h>
#include <ui_controlbargantts.h>*/
DockManager::DockManager (MainWindow * mw, QStringList const & path)
: DockManagerView(mw), ActionAble(path)
, m_main_window(mw)
, m_dockwidget(0)
, m_control_bar(0)
, m_model(0)
, m_config(g_traceServerName)
{
qDebug("%s", __FUNCTION__);
resizeColumnToContents(0);
QString const name = path.join("/");
DockWidget * const dock = new DockWidget(*this, name, m_main_window);
dock->setObjectName(name);
dock->setWindowTitle(name);
dock->setAllowedAreas(Qt::AllDockWidgetAreas);
m_main_window->addDockWidget(Qt::BottomDockWidgetArea, dock);
dock->setAttribute(Qt::WA_DeleteOnClose, false);
dock->setWidget(this);
//if (visible)
// m_main_window->restoreDockWidget(dock);
m_dockwidget = dock;
connect(m_dockwidget, SIGNAL(widgetVisibilityChanged()), m_main_window, SLOT(onDockManagerVisibilityChanged(bool)));
m_control_bar = new ControlBarCommon();
connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int)));
connect(m_dockwidget, SIGNAL(dockClosed()), mw, SLOT(onDockManagerClosed()));
setAllColumnsShowFocus(false);
setExpandsOnDoubleClick(false);
//setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
//setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored);
//header()->setSectionResizeMode(0, QHeaderView::Interactive);
header()->setStretchLastSection(false);
setEditTriggers(QAbstractItemView::NoEditTriggers);
//setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
setItemDelegateForColumn(e_Column_ControlWidget, new ControlWidgetDelegate(*this, this));
setStyleSheet("QTreeView::item{ selection-background-color: #FFE7BA } QTreeView::item{ selection-color: #000000 }");
//horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { border: 1px solid grey; height: 15px; } QScrollBar::handle:horizontal { background: white; min-width: 10px; }");
/*
setStyleSheet(QString::fromUtf8("QScrollBar:vertical {
" border: 1px solid #999999;"
" background:white;"
" width:10px; "
" margin: 0px 0px 0px 0px;"
"}"
"QScrollBar::handle:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));"
" min-height: 0px;"
""
"}"
"QScrollBar::add-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));"
" height: px;"
" subcontrol-position: bottom;"
" subcontrol-origin: margin;"
"}"
"QScrollBar::sub-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));"
" height: 0px;"
" subcontrol-position: top;"
" subcontrol-origin: margin;"
"}"
""));
*/
}
void DockManager::loadConfig (QString const & cfgpath)
{
QString const fname = cfgpath + "/" + g_dockManagerTag;
DockManagerConfig config2(g_traceServerName);
if (!::loadConfigTemplate(config2, fname))
{
m_config.defaultConfig();
}
else
{
m_config = config2;
config2.m_data.root = 0; // @TODO: promyslet.. takle na to urcite zapomenu
}
m_model = new DockManagerModel(*this, this, &m_config.m_data);
setModel(m_model);
bool const on = true;
addActionAble(*this, on, false, true);
}
void DockManager::applyConfig ()
{
for (size_t i = 0, ie = m_config.m_columns_sizes.size(); i < ie; ++i)
header()->resizeSection(static_cast<int>(i), m_config.m_columns_sizes[i]);
if (m_model)
m_model->syncExpandState(this);
}
void DockManager::saveConfig (QString const & path)
{
QString const fname = path + "/" + g_dockManagerTag;
::saveConfigTemplate(m_config, fname);
}
DockManager::~DockManager ()
{
setParent(0);
m_dockwidget->setWidget(0);
delete m_dockwidget;
m_dockwidget= 0;
removeActionAble(*this);
}
DockWidget * DockManager::mkDockWidget (DockedWidgetBase & dwb, bool visible)
{
return mkDockWidget(dwb, visible, Qt::BottomDockWidgetArea);
}
DockWidget * DockManager::mkDockWidget (ActionAble & aa, bool visible, Qt::DockWidgetArea area)
{
qDebug("%s", __FUNCTION__);
Q_ASSERT(aa.path().size() > 0);
QString const name = aa.path().join("/");
DockWidget * const dock = new DockWidget(*this, name, m_main_window);
dock->setObjectName(name);
dock->setWindowTitle(name);
dock->setAllowedAreas(Qt::AllDockWidgetAreas);
//dock->setWidget(docked_widget); // @NOTE: commented, it is set by caller
m_main_window->addDockWidget(area, dock);
dock->setAttribute(Qt::WA_DeleteOnClose, false);
if (visible)
m_main_window->restoreDockWidget(dock);
return dock;
}
void DockManager::onWidgetClosed (DockWidget * w)
{
qDebug("%s w=%08x", __FUNCTION__, w);
}
QModelIndex DockManager::addActionAble (ActionAble & aa, bool on, bool close_button, bool control_widget)
{
qDebug("%s aa=%s show=%i", __FUNCTION__, aa.joinedPath().toStdString().c_str(), on);
QModelIndex const idx = m_model->insertItemWithPath(aa.path(), on);
QString const & name = aa.joinedPath();
m_actionables.insert(name, &aa);
m_model->initData(idx, QVariant(on ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole);
if (close_button)
{
QModelIndex const jdx = m_model->index(idx.row(), e_Column_Close, idx.parent());
openPersistentEditor(jdx);
}
if (control_widget)
{
QModelIndex const kdx = m_model->index(idx.row(), e_Column_ControlWidget, idx.parent());
openPersistentEditor(kdx);
}
return idx;
}
QModelIndex DockManager::addActionAble (ActionAble & aa, bool on)
{
return addActionAble(aa, on, true, true);
}
ActionAble const * DockManager::findActionAble (QString const & dst_joined) const
{
actionables_t::const_iterator it = m_actionables.find(dst_joined);
if (it != m_actionables.end() && it.key() == dst_joined)
return *it;
return 0;
}
ActionAble * DockManager::findActionAble (QString const & dst_joined)
{
actionables_t::iterator it = m_actionables.find(dst_joined);
if (it != m_actionables.end() && it.key() == dst_joined)
return *it;
return 0;
}
void DockManager::removeActionAble (ActionAble & aa)
{
qDebug("%s aa=%s", __FUNCTION__, aa.joinedPath().toStdString().c_str());
actionables_t::iterator it = m_actionables.find(aa.joinedPath());
if (it != m_actionables.end() && it.key() == aa.joinedPath())
{
QModelIndex const idx = m_model->testItemWithPath(aa.path());
if (idx.isValid())
for (int j = 1; j < e_max_dockmgr_column; ++j)
closePersistentEditor(m_model->index(idx.row(), j, idx.parent()));
m_actionables.erase(it);
}
}
void DockManager::onColumnResized (int idx, int , int new_size)
{
if (idx < 0) return;
size_t const curr_sz = m_config.m_columns_sizes.size();
if (idx < curr_sz)
{
//qDebug("%s this=0x%08x hsize[%i]=%i", __FUNCTION__, this, idx, new_size);
}
else
{
m_config.m_columns_sizes.resize(idx + 1);
for (size_t i = curr_sz; i < idx + 1; ++i)
m_config.m_columns_sizes[i] = 32;
}
m_config.m_columns_sizes[idx] = new_size;
}
bool DockManager::handleAction (Action * a, E_ActionHandleType sync)
{
QStringList const & src_path = a->m_src_path;
QStringList const & dst_path = a->m_dst_path;
QStringList const & my_addr = path();
if (dst_path.size() == 0)
{
qWarning("DockManager::handleAction empty dst");
return false;
}
Q_ASSERT(my_addr.size() == 1);
int const lvl = dst_path.indexOf(my_addr.at(0), a->m_dst_curr_level);
if (lvl == -1)
{
qWarning("DockManager::handleAction message not for me");
return false;
}
else if (lvl == dst_path.size() - 1)
{
// message just for me! gr8!
a->m_dst_curr_level = lvl;
a->m_dst = this;
return true;
}
else
{
// message for my children
a->m_dst_curr_level = lvl + 1;
if (a->m_dst_curr_level >= 0 && a->m_dst_curr_level < dst_path.size())
{
QString const dst_joined = dst_path.join("/");
actionables_t::iterator it = m_actionables.find(dst_joined);
if (it != m_actionables.end() && it.key() == dst_joined)
{
qDebug("delivering action to: %s", dst_joined.toStdString().c_str());
ActionAble * const next_hop = it.value();
next_hop->handleAction(a, sync); //@NOTE: e_Close can invalidate iterator
}
else
{
//@TODO: find least common subpath
}
}
else
{
qWarning("DockManager::handleAction hmm? what?");
}
}
return false;
}
void DockManager::onCloseButton ()
{
QVariant v = QObject::sender()->property("idx");
if (v.canConvert<QModelIndex>())
{
QModelIndex const idx = v.value<QModelIndex>();
if (TreeModel<DockedInfo>::node_t * const n = m_model->getItemFromIndex(idx))
{
QStringList const & dst_path = n->data.m_path;
Action a;
a.m_type = e_Close;
a.m_src_path = path();
a.m_src = this;
a.m_dst_path = dst_path;
handleAction(&a, e_Sync);
}
}
}
<|endoftext|> |
<commit_before>#include <ncurses.h>
int main()
{
initscr();
endwin();
return 0;
}
<commit_msg>NCusrses igh<commit_after>#include <ncurses.h>
int main()
{
initscr();
endwin();
// end
return 0;
}
<|endoftext|> |
<commit_before>#include "bot/InputOutput.hxx"
#include "bot/HypothesisSpace.hxx"
#include "bot/ObjectFeatureExtractor.hxx"
#include "bot/AverageObject.hxx"
#include "bot/SingletsGenerator.hxx"
#include "bot/MultipletsGenerator.hxx"
#include "bot/CPLEXSolverSystem.hxx"
#include "bot/TrackingPredictor.hxx"
#include "vigra/hdf5impex.hxx"
#include "bot/SolutionCoder.hxx"
#include "bot/TrainingData.hxx"
#include "bot/TrackingTrainer.hxx"
#include "bot/HDF5ReaderWriter.hxx"
using namespace bot;
int main()
{
std::string filename("dcelliq-sequence-training.h5");
// load the image sequence
std::vector<Matrix2D > images, segmentations;
TrainingData training;
HDF5ReaderWriter::load(filename, images, segmentations);
std::cout << "****Loading the images/segmentations****" << std::endl;
HDF5ReaderWriter::load(filename, training);
std::cout << "****Loading the training data****" << std::endl;
// get the context
Context context(images);
std::cout << "****Computing the Context****" << std::endl << context << std::endl << std::endl;
// load the configuration
HypothesisSpace space("../data/event-configuration-cell.ini");
EventConfiguration conf = space.configuration();
// create singlets/muliplets and extract object features
std::cout << "****Extracting singlets and multiplets****" << std::endl;
SingletsSequence singlets_vec;
SingletsSequence avg_singlet_vec;
MultipletsSequence multiplets_vec;
SingletsGenerator singletsGenerator;
MultipletsGenerator multipletsGenerator(conf.k(), conf.d_max());
ObjectFeatureExtractor extractor(conf.get_feature_names(), context);
for (int32 indT = 0; indT < images.size(); indT ++) {
// generate singlets and multiplets
Singlets singlets = singletsGenerator(images[indT], segmentations[indT]);
Multiplets multiplets = multipletsGenerator(images[indT], segmentations[indT], singlets);
// extract features for them
extractor(singlets);
extractor(multiplets);
// save
singlets_vec.push_back(singlets);
avg_singlet_vec.push_back(AverageObject::average(singlets));
multiplets_vec.push_back(multiplets);
std::cout << "#T = " << indT
<< ": #singlets = " << singlets.size()
<< ": #multiplets = " << multiplets.size() << std::endl;
}
// generate hypotheses and extract joint features
space(singlets_vec, avg_singlet_vec, multiplets_vec);
const std::vector<FramePair >& framepairs = space.framepairs();
// parse the training data
std::cout << "****Parsing the training data****" << std::endl;
SolutionCoder coder;
int32 nTr = training.times().size();
for (int32 ind = 0; ind < nTr; ind ++) {
int32 time = training.times()[ind];
std::cout << "****time = " << time << "****" << std::endl;
const LabelAssociations& association = training.associations()[ind];
const std::vector<Event >& events = framepairs[time].events();
const Singlets& singlets1 = singlets_vec[time];
const Singlets& singlets2 = singlets_vec[time+1];
const Multiplets& multiplets1 = multiplets_vec[time];
const Multiplets& multiplets2 = multiplets_vec[time+1];
Solution solution;
coder.decode(
association,
events,
singlets1, singlets2,
multiplets1, multiplets2,
solution);
training.solutions().push_back(solution);
}
// start the training
TrackingTrainer trainer;
const std::vector<Matrix2D > null_vector;
std::vector<Matrix2D > weights = conf.weights(0.5);
std::string msg = trainer(training, framepairs, weights, true);
std::cout << "Training returns: " << msg << std::endl;
conf.weights() = weights;
// print the final weights
std::cout << "Learned weights: " << std::endl;
conf.print();
// printe intermediate results: weights, epsilons, losses
std::cout << "Weights: " << std::endl << trainer.weights() << std::endl << std::endl;
std::cout << "Epsilons: " << std::endl << trainer.epsilons() << std::endl << std::endl;
std::cout << "Losses: " << std::endl << trainer.losses() << std::endl << std::endl;
return 0;
}
<commit_msg>Silenced compiler warning<commit_after>#include "bot/InputOutput.hxx"
#include "bot/HypothesisSpace.hxx"
#include "bot/ObjectFeatureExtractor.hxx"
#include "bot/AverageObject.hxx"
#include "bot/SingletsGenerator.hxx"
#include "bot/MultipletsGenerator.hxx"
#include "bot/CPLEXSolverSystem.hxx"
#include "bot/TrackingPredictor.hxx"
#include "vigra/hdf5impex.hxx"
#include "bot/SolutionCoder.hxx"
#include "bot/TrainingData.hxx"
#include "bot/TrackingTrainer.hxx"
#include "bot/HDF5ReaderWriter.hxx"
using namespace bot;
int main()
{
std::string filename("dcelliq-sequence-training.h5");
// load the image sequence
std::vector<Matrix2D > images, segmentations;
TrainingData training;
HDF5ReaderWriter::load(filename, images, segmentations);
std::cout << "****Loading the images/segmentations****" << std::endl;
HDF5ReaderWriter::load(filename, training);
std::cout << "****Loading the training data****" << std::endl;
// get the context
Context context(images);
std::cout << "****Computing the Context****" << std::endl << context << std::endl << std::endl;
// load the configuration
HypothesisSpace space("event-configuration-cell.ini");
EventConfiguration conf = space.configuration();
// create singlets/muliplets and extract object features
std::cout << "****Extracting singlets and multiplets****" << std::endl;
SingletsSequence singlets_vec;
SingletsSequence avg_singlet_vec;
MultipletsSequence multiplets_vec;
SingletsGenerator singletsGenerator;
MultipletsGenerator multipletsGenerator(conf.k(), conf.d_max());
ObjectFeatureExtractor extractor(conf.get_feature_names(), context);
for (int32 indT = 0; indT < static_cast<int32>(images.size()); indT ++) {
// generate singlets and multiplets
Singlets singlets = singletsGenerator(images[indT], segmentations[indT]);
Multiplets multiplets = multipletsGenerator(images[indT], segmentations[indT], singlets);
// extract features for them
extractor(singlets);
extractor(multiplets);
// save
singlets_vec.push_back(singlets);
avg_singlet_vec.push_back(AverageObject::average(singlets));
multiplets_vec.push_back(multiplets);
std::cout << "#T = " << indT
<< ": #singlets = " << singlets.size()
<< ": #multiplets = " << multiplets.size() << std::endl;
}
// generate hypotheses and extract joint features
space(singlets_vec, avg_singlet_vec, multiplets_vec);
const std::vector<FramePair >& framepairs = space.framepairs();
// parse the training data
std::cout << "****Parsing the training data****" << std::endl;
SolutionCoder coder;
int32 nTr = training.times().size();
for (int32 ind = 0; ind < nTr; ind ++) {
int32 time = training.times()[ind];
std::cout << "****time = " << time << "****" << std::endl;
const LabelAssociations& association = training.associations()[ind];
const std::vector<Event >& events = framepairs[time].events();
const Singlets& singlets1 = singlets_vec[time];
const Singlets& singlets2 = singlets_vec[time+1];
const Multiplets& multiplets1 = multiplets_vec[time];
const Multiplets& multiplets2 = multiplets_vec[time+1];
Solution solution;
coder.decode(
association,
events,
singlets1, singlets2,
multiplets1, multiplets2,
solution);
training.solutions().push_back(solution);
}
// start the training
TrackingTrainer trainer;
const std::vector<Matrix2D > null_vector;
std::vector<Matrix2D > weights = conf.weights(0.5);
std::string msg = trainer(training, framepairs, weights, true);
std::cout << "Training returns: " << msg << std::endl;
conf.weights() = weights;
// print the final weights
std::cout << "Learned weights: " << std::endl;
conf.print();
// printe intermediate results: weights, epsilons, losses
std::cout << "Weights: " << std::endl << trainer.weights() << std::endl << std::endl;
std::cout << "Epsilons: " << std::endl << trainer.epsilons() << std::endl << std::endl;
std::cout << "Losses: " << std::endl << trainer.losses() << std::endl << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <ncurses.h>
int main()
{
initscr();
endwin();
return 0;
}
<commit_msg>NCusrses igh<commit_after>#include <ncurses.h>
int main()
{
initscr();
endwin();
// end
return 0;
}
<|endoftext|> |
<commit_before>#include "symboltable.hpp"
#include "exception.hpp"
#include "configuration.hpp"
#include "version.h"
#include "builtin/array.hpp"
#include "builtin/encoding.hpp"
#include "builtin/exception.hpp"
#include "builtin/string.hpp"
#include "builtin/symbol.hpp"
#include <iostream>
#include <iomanip>
namespace rubinius {
SymbolTable::Kind SymbolTable::detect_kind(const char* str, size_t size) {
const char one = str[0];
// A constant begins with an uppercase letter.
if(one >= 'A' && one <= 'Z') {
// Make sure that the rest of it is only alphanumerics
for(size_t i = 1; i < size; i++) {
if((isalnum(str[i]) || str[i] == '_') == false)
return SymbolTable::Normal;
}
return SymbolTable::Constant;
}
if(one == '@') {
// A class variable begins with @@
if(size > 1 && str[1] == '@') {
return SymbolTable::CVar;
}
// An instance variable can't start with a digit
if(size > 1 && ISDIGIT(str[1])) {
return SymbolTable::Normal;
}
// An instance variable begins with @
return SymbolTable::IVar;
}
// A system variable begins with __
if(size > 2 && one == '_' && str[1] == '_') {
return SymbolTable::System;
}
// Everything else is normal
return SymbolTable::Normal;
}
SymbolTable::Kind SymbolTable::kind(STATE, const Symbol* sym) const {
return kinds[sym->index()];
}
size_t SymbolTable::add(std::string str, int enc) {
bytes_used_ += (str.size() + sizeof(str));
strings.push_back(str);
encodings.push_back(enc);
kinds.push_back(detect_kind(str.data(), str.size()));
return strings.size() - 1;
}
Symbol* SymbolTable::lookup(STATE, const char* str, size_t length) {
if(length == 0 && LANGUAGE_18_ENABLED) {
Exception::argument_error(state, "Cannot create a symbol from an empty string");
return NULL;
}
return lookup(str, length, Encoding::eAscii, state->hash_seed());
}
Symbol* SymbolTable::lookup(STATE, const char* str, size_t length, int enc) {
if(length == 0 && LANGUAGE_18_ENABLED) {
Exception::argument_error(state, "Cannot create a symbol from an empty string");
return NULL;
}
return lookup(str, length, enc, state->hash_seed());
}
struct SpecialOperator {
const char* name;
const char* symbol;
};
// These are a set of special operators that MRI
// changes the symbol value of.
static SpecialOperator SpecialOperators[] = {
{"+(binary)", "+"},
{"-(binary)", "-"},
{"+(unary)", "+@"},
{"-(unary)", "-@"},
{"!(unary)", "!"},
{"~(unary)", "~"},
{"!@", "!"},
{"~@", "~"}
};
const static int cNumSpecialOperators = 8;
static const char* find_special(const char* check, size_t length) {
for(int i = 0; i < cNumSpecialOperators; i++) {
SpecialOperator* op = &SpecialOperators[i];
if(*op->name == *check && strncmp(op->name, check, length) == 0) {
return op->symbol;
}
}
return 0;
}
Symbol* SymbolTable::lookup(SharedState* shared, const std::string& str) {
return lookup(str.data(), str.size(), Encoding::eAscii, shared->hash_seed);
}
Symbol* SymbolTable::lookup(STATE, const std::string& str) {
return lookup(str.data(), str.size(), Encoding::eAscii, state->hash_seed());
}
Symbol* SymbolTable::lookup(const char* str, size_t length, int enc, uint32_t seed) {
size_t sym;
if(const char* op = find_special(str, length)) {
str = op;
length = strlen(str);
}
hashval hash = String::hash_str((unsigned char*)str, length, seed);
// Symbols can be looked up by multiple threads at the same time.
// This is fast operation, so we protect this with a spinlock.
{
utilities::thread::SpinLock::LockGuard guard(lock_);
SymbolMap::iterator entry = symbols.find(hash);
if(entry == symbols.end()) {
sym = add(std::string(str, length), enc);
SymbolIds v(1, sym);
symbols[hash] = v;
} else {
SymbolIds& v = entry->second;
for(SymbolIds::const_iterator i = v.begin(); i != v.end(); ++i) {
std::string& s = strings[*i];
int e = encodings[*i];
if(!strncmp(s.data(), str, length) && enc == e) return Symbol::from_index(*i);
}
sym = add(std::string(str, length), enc);
v.push_back(sym);
}
}
return Symbol::from_index(sym);
}
Symbol* SymbolTable::lookup(STATE, String* str) {
if(str->nil_p()) {
Exception::argument_error(state, "Cannot look up Symbol from nil");
return NULL;
}
// Since we also explicitly use the size, we can safely
// use byte_address() here.
const char* bytes = (const char*) str->byte_address();
size_t size = str->byte_size();
int enc = str->encoding(state)->index();
if(LANGUAGE_18_ENABLED) {
for(size_t i = 0; i < size; i++) {
if(bytes[i] == 0) {
Exception::argument_error(state,
"cannot create a symbol from a string containing `\\0'");
return NULL;
}
}
enc = Encoding::eAscii;
} else {
if(CBOOL(str->ascii_only_p(state))) {
enc = Encoding::eAscii;
}
}
return lookup(bytes, size, enc, state->hash_seed());
}
String* SymbolTable::lookup_string(STATE, const Symbol* sym) {
if(sym->nil_p()) {
Exception::argument_error(state, "Cannot look up Symbol from nil");
return NULL;
}
size_t sym_index = sym->index();
if(sym_index >= strings.size()) {
return NULL;
}
std::string& str = strings[sym_index];
int enc = encodings[sym_index];
String* s = String::create(state, str.data(), str.size());
s->encoding(state, Encoding::from_index(state, enc));
return s;
}
std::string& SymbolTable::lookup_cppstring(const Symbol* sym) {
return strings[sym->index()];
}
int SymbolTable::lookup_encoding(const Symbol* sym) {
return encodings[sym->index()];
}
std::string SymbolTable::lookup_debug_string(const Symbol* sym) {
std::string str = lookup_cppstring(sym);
std::ostringstream os;
unsigned char* cstr = (unsigned char*) str.data();
size_t size = str.size();
for(size_t i = 0; i < size; ++i) {
if(isprint(cstr[i]) && isascii(cstr[i])) {
os << cstr[i];
} else {
os << "\\x" << std::setw(2) << std::setfill('0') << std::hex << (unsigned int)cstr[i];
}
}
return os.str();
}
size_t SymbolTable::size() const {
return strings.size();
}
size_t SymbolTable::byte_size() const {
size_t total = 0;
for(SymbolStrings::const_iterator i = strings.begin();
i != strings.end();
++i) {
total += i->size();
total += sizeof(std::string);
}
return total;
}
Array* SymbolTable::all_as_array(STATE) {
size_t idx = 0;
Array* ary = Array::create(state, this->size());
for(SymbolMap::iterator s = symbols.begin(); s != symbols.end(); ++s) {
for(SymbolIds::iterator i = s->second.begin(); i != s->second.end(); ++i) {
ary->set(state, idx++, Symbol::from_index(state, *i));
}
}
return ary;
}
}
<commit_msg>Throw exception in 1.8 mode for empty string<commit_after>#include "symboltable.hpp"
#include "exception.hpp"
#include "configuration.hpp"
#include "version.h"
#include "builtin/array.hpp"
#include "builtin/encoding.hpp"
#include "builtin/exception.hpp"
#include "builtin/string.hpp"
#include "builtin/symbol.hpp"
#include <iostream>
#include <iomanip>
namespace rubinius {
SymbolTable::Kind SymbolTable::detect_kind(const char* str, size_t size) {
const char one = str[0];
// A constant begins with an uppercase letter.
if(one >= 'A' && one <= 'Z') {
// Make sure that the rest of it is only alphanumerics
for(size_t i = 1; i < size; i++) {
if((isalnum(str[i]) || str[i] == '_') == false)
return SymbolTable::Normal;
}
return SymbolTable::Constant;
}
if(one == '@') {
// A class variable begins with @@
if(size > 1 && str[1] == '@') {
return SymbolTable::CVar;
}
// An instance variable can't start with a digit
if(size > 1 && ISDIGIT(str[1])) {
return SymbolTable::Normal;
}
// An instance variable begins with @
return SymbolTable::IVar;
}
// A system variable begins with __
if(size > 2 && one == '_' && str[1] == '_') {
return SymbolTable::System;
}
// Everything else is normal
return SymbolTable::Normal;
}
SymbolTable::Kind SymbolTable::kind(STATE, const Symbol* sym) const {
return kinds[sym->index()];
}
size_t SymbolTable::add(std::string str, int enc) {
bytes_used_ += (str.size() + sizeof(str));
strings.push_back(str);
encodings.push_back(enc);
kinds.push_back(detect_kind(str.data(), str.size()));
return strings.size() - 1;
}
Symbol* SymbolTable::lookup(STATE, const char* str, size_t length) {
if(length == 0 && LANGUAGE_18_ENABLED) {
Exception::argument_error(state, "Cannot create a symbol from an empty string");
return NULL;
}
return lookup(str, length, Encoding::eAscii, state->hash_seed());
}
Symbol* SymbolTable::lookup(STATE, const char* str, size_t length, int enc) {
if(length == 0 && LANGUAGE_18_ENABLED) {
Exception::argument_error(state, "Cannot create a symbol from an empty string");
return NULL;
}
return lookup(str, length, enc, state->hash_seed());
}
struct SpecialOperator {
const char* name;
const char* symbol;
};
// These are a set of special operators that MRI
// changes the symbol value of.
static SpecialOperator SpecialOperators[] = {
{"+(binary)", "+"},
{"-(binary)", "-"},
{"+(unary)", "+@"},
{"-(unary)", "-@"},
{"!(unary)", "!"},
{"~(unary)", "~"},
{"!@", "!"},
{"~@", "~"}
};
const static int cNumSpecialOperators = 8;
static const char* find_special(const char* check, size_t length) {
for(int i = 0; i < cNumSpecialOperators; i++) {
SpecialOperator* op = &SpecialOperators[i];
if(*op->name == *check && strncmp(op->name, check, length) == 0) {
return op->symbol;
}
}
return 0;
}
Symbol* SymbolTable::lookup(SharedState* shared, const std::string& str) {
return lookup(str.data(), str.size(), Encoding::eAscii, shared->hash_seed);
}
Symbol* SymbolTable::lookup(STATE, const std::string& str) {
return lookup(str.data(), str.size(), Encoding::eAscii, state->hash_seed());
}
Symbol* SymbolTable::lookup(const char* str, size_t length, int enc, uint32_t seed) {
size_t sym;
if(const char* op = find_special(str, length)) {
str = op;
length = strlen(str);
}
hashval hash = String::hash_str((unsigned char*)str, length, seed);
// Symbols can be looked up by multiple threads at the same time.
// This is fast operation, so we protect this with a spinlock.
{
utilities::thread::SpinLock::LockGuard guard(lock_);
SymbolMap::iterator entry = symbols.find(hash);
if(entry == symbols.end()) {
sym = add(std::string(str, length), enc);
SymbolIds v(1, sym);
symbols[hash] = v;
} else {
SymbolIds& v = entry->second;
for(SymbolIds::const_iterator i = v.begin(); i != v.end(); ++i) {
std::string& s = strings[*i];
int e = encodings[*i];
if(!strncmp(s.data(), str, length) && enc == e) return Symbol::from_index(*i);
}
sym = add(std::string(str, length), enc);
v.push_back(sym);
}
}
return Symbol::from_index(sym);
}
Symbol* SymbolTable::lookup(STATE, String* str) {
if(str->nil_p()) {
Exception::argument_error(state, "Cannot look up Symbol from nil");
return NULL;
}
// Since we also explicitly use the size, we can safely
// use byte_address() here.
const char* bytes = (const char*) str->byte_address();
size_t size = str->byte_size();
int enc = str->encoding(state)->index();
if(LANGUAGE_18_ENABLED) {
if(size == 0) {
Exception::argument_error(state, "Cannot create a symbol from an empty string");
return NULL;
}
if(strnlen(bytes, size) < size) {
Exception::argument_error(state,
"cannot create a symbol from a string containing `\\0'");
return NULL;
}
enc = Encoding::eAscii;
} else {
if(CBOOL(str->ascii_only_p(state))) {
enc = Encoding::eAscii;
}
}
return lookup(bytes, size, enc, state->hash_seed());
}
String* SymbolTable::lookup_string(STATE, const Symbol* sym) {
if(sym->nil_p()) {
Exception::argument_error(state, "Cannot look up Symbol from nil");
return NULL;
}
size_t sym_index = sym->index();
if(sym_index >= strings.size()) {
return NULL;
}
std::string& str = strings[sym_index];
int enc = encodings[sym_index];
String* s = String::create(state, str.data(), str.size());
s->encoding(state, Encoding::from_index(state, enc));
return s;
}
std::string& SymbolTable::lookup_cppstring(const Symbol* sym) {
return strings[sym->index()];
}
int SymbolTable::lookup_encoding(const Symbol* sym) {
return encodings[sym->index()];
}
std::string SymbolTable::lookup_debug_string(const Symbol* sym) {
std::string str = lookup_cppstring(sym);
std::ostringstream os;
unsigned char* cstr = (unsigned char*) str.data();
size_t size = str.size();
for(size_t i = 0; i < size; ++i) {
if(isprint(cstr[i]) && isascii(cstr[i])) {
os << cstr[i];
} else {
os << "\\x" << std::setw(2) << std::setfill('0') << std::hex << (unsigned int)cstr[i];
}
}
return os.str();
}
size_t SymbolTable::size() const {
return strings.size();
}
size_t SymbolTable::byte_size() const {
size_t total = 0;
for(SymbolStrings::const_iterator i = strings.begin();
i != strings.end();
++i) {
total += i->size();
total += sizeof(std::string);
}
return total;
}
Array* SymbolTable::all_as_array(STATE) {
size_t idx = 0;
Array* ary = Array::create(state, this->size());
for(SymbolMap::iterator s = symbols.begin(); s != symbols.end(); ++s) {
for(SymbolIds::iterator i = s->second.begin(); i != s->second.end(); ++i) {
ary->set(state, idx++, Symbol::from_index(state, *i));
}
}
return ary;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.