text stringlengths 54 60.6k |
|---|
<commit_before>/**
* @author pinkasfeld joseph
* Copyright (c) Aldebaran Robotics 2010, 2011 All Rights Reserved.
*/
#include "allaser.h"
#include <iostream>
#include <alcommon/alproxy.h>
#include <alproxies/almemoryproxy.h>
#include <boost/shared_ptr.hpp>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <sstream>
#include <pthread.h>
#include <signal.h>
#include <cmath>
#include <qi/log.hpp>
#if defined (__linux__)
#include <sys/prctl.h>
#endif
extern "C" {
# include "urg_ctrl.h"
# include "scip_handler.h"
}
#define MODE_ON 0
#define MODE_OFF 1
#define SEND_MODE_ON 2
#define SEND_MODE_OFF 3
#define MIDDLE_ANGLE 384
#define DEFAULT_MIN_ANGLE 43
#define DEFAULT_MAX_ANGLE 725
#define MIN_ANGLE_LASER 43
#define MAX_ANGLE_LASER 725
#define RESOLUTION_LASER 1024
#define MIN_LENGTH_LASER 20
#define MAX_LENGTH_LASER 5600
#include <sys/time.h>
using namespace AL;
using namespace std;
pthread_t urgThreadId;
boost::shared_ptr<ALMemoryProxy> gSTM;
static int mode = MODE_ON;
static urg_t urg;
static int angle_min = DEFAULT_MIN_ANGLE;
static int angle_max = DEFAULT_MAX_ANGLE;
static int length_min = MIN_LENGTH_LASER;
static int length_max = MAX_LENGTH_LASER;
static void urg_exit(urg_t *urg, const char *message) {
qiLogInfo("hardware.allaser", "%s: %s\n", message, urg_error(urg));
urg_disconnect(urg);
qiLogInfo("hardware.allaser", "urg_exit\n");
pthread_exit((void *)NULL);
}
#define URG_DEFAULT_SPEED (19200)
#define URG_FAST_SPEED (500000)
void * urgThread(void * arg) {
#if defined (__linux__)
// thread name
prctl(PR_SET_NAME, "ALLaser::urgThread", 0, 0, 0);
#endif
ALValue urgdata;
long *data = NULL;
int data_max;
int ret;
int n;
int i,imemory,refTime,end,sampleTime, beginThread;
std::string valueName="Device/Laser/Value";
/* Connection */
connectToLaser();
/* Reserve the Receive data buffer */
data_max = urg_dataMax(&urg);
data = (long*)malloc(sizeof(long) * data_max);
if (data == NULL) {
perror("data buffer");
pthread_exit((void *)NULL);
}
/* prepare ALValue for ALMemory*/
urgdata.arraySetSize(data_max);
for (i=0; i< data_max;i++)
{
urgdata[i].arraySetSize(4);
urgdata[i][0]= (int)0;
urgdata[i][1]= (double)0.0;
urgdata[i][2]= (int)0;
urgdata[i][3]= (int)0;
}
/* insert ALvalue in ALMemory*/
gSTM->insertData(valueName,urgdata);
gSTM->insertData("Device/Laser/LaserEnable",(bool)1);
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)*(DEFAULT_MIN_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)*(DEFAULT_MAX_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MinLength",(float)(length_min));
gSTM->insertData("Device/Laser/MaxLength",(float)(length_max));
stringstream ss;
ss << "ALLaser running";
qiLogInfo("hardware.laser") << ss.str() << std::endl;
while(1)
{
if(mode==SEND_MODE_ON){
ret = urg_laserOn(&urg);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
mode=MODE_ON;
/* Connection */
connectToLaser();
}
if(mode==SEND_MODE_OFF){
scip_qt(&urg.serial_, NULL, ScipNoWaitReply);
mode=MODE_OFF;
}
if(mode==MODE_ON){
/* Request Data using GD-Command */
ret = urg_requestData(&urg, URG_GD, angle_min, angle_max);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
refTime = getLocalTime();
/* Obtain Data */
n = urg_receiveData(&urg, data, data_max);
if (n < 0) {
urg_exit(&urg, "urg_receiveData()");
}
end= getLocalTime();
sampleTime=end-refTime;
imemory=0;
for (i = 0; i < n; ++i) {
int x, y;
double angle=index2rad(i);
int length = data[i];
if((length>=length_min)&&(length<=length_max)){
x = (int)((double)length * cos(angle));
y = (int)((double)length * sin(angle));
urgdata[imemory][0]= length;
urgdata[imemory][1]= angle;
urgdata[imemory][2]= x;
urgdata[imemory][3]= y;
imemory++;
}
}
for(;imemory<data_max;imemory++){
urgdata[imemory][0]= 0;
urgdata[imemory][1]= 0;
urgdata[imemory][2]= 0;
urgdata[imemory][3]= 0;
}
gSTM->insertData(valueName,urgdata);
usleep(1000);
}else{
usleep(10000);
}
}
urg_disconnect(&urg);
free(data);
}
//______________________________________________
// constructor
//______________________________________________
ALLaser::ALLaser(boost::shared_ptr<ALBroker> pBroker, const std::string& pName ): ALModule(pBroker, pName )
{
setModuleDescription( "Allow control over Hokuyo laser when available on Nao's head." );
functionName("laserOFF", "ALLaser", "Disable laser light");
BIND_METHOD( ALLaser::laserOFF );
functionName("laserON", "ALLaser", "Enable laser light and sampling");
BIND_METHOD( ALLaser::laserON );
functionName("setOpeningAngle", "ALLaser", "Set openning angle of the laser");
addParam("angle_min_f", "float containing the min value in rad, this value must be upper than -2.35619449 ");
addParam("angle_max_f", "float containing the max value in rad, this value must be lower than 2.092349795 ");
addMethodExample( "python",
"# Set the opening angle at -90/90 degres\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setOpeningAngle(-1.570796327,1.570796327)\n"
);
BIND_METHOD( ALLaser::setOpeningAngle );
functionName("setDetectingLength", "ALLaser", "Set detection threshold of the laser");
addParam("length_min_l", "int containing the min length that the laser will detect(mm), this value must be upper than 20 mm");
addParam("length_max_l", "int containing the max length that the laser will detect(mm), this value must be lower than 5600 mm");
addMethodExample( "python",
"# Set detection threshold at 500/3000 mm\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setDetectingLength(500,3000)\n"
);
BIND_METHOD( ALLaser::setDetectingLength );
// get broker on DCM and ALMemory
try {
gSTM = getParentBroker()->getMemoryProxy();
} catch(ALError& e) {
qiLogError("hardware.allaser") << "Could not connect to Memory. Error: " << e.what() << std::endl;
}
pthread_create(&urgThreadId, NULL, urgThread, NULL);
}
//______________________________________________
// destructor
//______________________________________________
ALLaser::~ALLaser()
{
pthread_cancel(urgThreadId);
}
void ALLaser::laserOFF(void){
mode = SEND_MODE_OFF;
gSTM->insertData("Device/Laser/LaserEnable",(bool)0);
}
void ALLaser::laserON(void){
mode = SEND_MODE_ON;
gSTM->insertData("Device/Laser/LaserEnable",(bool)1);
}
void ALLaser::setOpeningAngle(const AL::ALValue& angle_min_f, const AL::ALValue& angle_max_f){
angle_min = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_min_f / (2.0 * M_PI));
angle_max = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_max_f / (2.0 * M_PI));
if(angle_min<MIN_ANGLE_LASER) angle_min = MIN_ANGLE_LASER;
if(angle_max>MAX_ANGLE_LASER) angle_max = MAX_ANGLE_LASER;
if(angle_min>=angle_max){
angle_min = MIN_ANGLE_LASER;
angle_max = MAX_ANGLE_LASER;
}
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI) *(angle_min - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI) *(angle_max - MIDDLE_ANGLE) / RESOLUTION_LASER));
}
void ALLaser::setDetectingLength(const AL::ALValue& length_min_l,const AL::ALValue& length_max_l){
length_min=(int)length_min_l;
length_max=(int)length_max_l;
if(length_min<MIN_LENGTH_LASER) length_min = MIN_LENGTH_LASER;
if(length_max>MAX_LENGTH_LASER) length_min = MAX_LENGTH_LASER;
if(length_min>=length_max){
length_min = MIN_LENGTH_LASER;
length_max = MAX_LENGTH_LASER;
}
gSTM->insertData("Device/Laser/MinLength",(int)length_min);
gSTM->insertData("Device/Laser/MaxLength",(int)length_max);
}
//_________________________________________________
// Service functions
//_________________________________________________
int connectToLaserViaUSB(void) {
int success = -1;
const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */
// Try to connect at low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceUSB, URG_FAST_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
int connectToLaserViaACM(void) {
int success = -1;
const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceACM << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceACM, URG_FAST_SPEED);
if (success < 0)
{
std::stringstream ss;
ss << "Connection failure from " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
void connectToLaser(void){
int success = connectToLaserViaUSB();
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to USB, trying ACM... ";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
success = connectToLaserViaACM();
if (success < 0) {
std::stringstream ss;
ss << "Connection to laser failed";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
pthread_exit((void *)NULL);
}
else {
std::stringstream ss;
ss << "Connection to laser via ACM";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
else {
std::stringstream ss;
ss << "Connection to laser via USB";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
unsigned int getLocalTime(void){
struct timeval tv;
unsigned int val;
gettimeofday(&tv, NULL);
val = (unsigned int)((unsigned int)(tv.tv_usec/1000) + (unsigned int)(tv.tv_sec*1000));
// Time in ms
return val;
}
double index2rad(int index){
double radian = (2.0 * M_PI) *
(index - MIDDLE_ANGLE + angle_min) / RESOLUTION_LASER;
return radian;
}
<commit_msg>ALLASER: fix allaser offset.<commit_after>/**
* @author pinkasfeld joseph
* Copyright (c) Aldebaran Robotics 2010, 2011 All Rights Reserved.
*/
#include "allaser.h"
#include <iostream>
#include <alcommon/alproxy.h>
#include <alproxies/almemoryproxy.h>
#include <boost/shared_ptr.hpp>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <sstream>
#include <pthread.h>
#include <signal.h>
#include <cmath>
#include <qi/log.hpp>
#if defined (__linux__)
#include <sys/prctl.h>
#endif
extern "C" {
# include "urg_ctrl.h"
# include "scip_handler.h"
}
#define MODE_ON 0
#define MODE_OFF 1
#define SEND_MODE_ON 2
#define SEND_MODE_OFF 3
#define MIDDLE_ANGLE 384
#define DEFAULT_MIN_ANGLE 44
#define DEFAULT_MAX_ANGLE 725
#define MIN_ANGLE_LASER 44
#define MAX_ANGLE_LASER 725
#define RESOLUTION_LASER 1024
#define MIN_LENGTH_LASER 20
#define MAX_LENGTH_LASER 5600
#include <sys/time.h>
using namespace AL;
using namespace std;
pthread_t urgThreadId;
boost::shared_ptr<ALMemoryProxy> gSTM;
static int mode = MODE_ON;
static urg_t urg;
static int angle_min = DEFAULT_MIN_ANGLE;
static int angle_max = DEFAULT_MAX_ANGLE;
static int length_min = MIN_LENGTH_LASER;
static int length_max = MAX_LENGTH_LASER;
static void urg_exit(urg_t *urg, const char *message) {
qiLogInfo("hardware.allaser", "%s: %s\n", message, urg_error(urg));
urg_disconnect(urg);
qiLogInfo("hardware.allaser", "urg_exit\n");
pthread_exit((void *)NULL);
}
#define URG_DEFAULT_SPEED (19200)
#define URG_FAST_SPEED (500000)
void * urgThread(void * arg) {
#if defined (__linux__)
// thread name
prctl(PR_SET_NAME, "ALLaser::urgThread", 0, 0, 0);
#endif
ALValue urgdata;
long *data = NULL;
int data_max;
int ret;
int n;
int i,imemory,refTime,end,sampleTime, beginThread;
std::string valueName="Device/Laser/Value";
/* Connection */
connectToLaser();
/* Reserve the Receive data buffer */
data_max = urg_dataMax(&urg);
data = (long*)malloc(sizeof(long) * data_max);
memset(data, 0, sizeof(long) * data_max);
if (data == NULL) {
perror("data buffer");
pthread_exit((void *)NULL);
}
/* prepare ALValue for ALMemory*/
urgdata.arraySetSize(data_max);
for (i=0; i< data_max;i++)
{
urgdata[i].arraySetSize(4);
urgdata[i][0]= (int)0;
urgdata[i][1]= (double)0.0;
urgdata[i][2]= (int)0;
urgdata[i][3]= (int)0;
}
/* insert ALvalue in ALMemory*/
gSTM->insertData(valueName,urgdata);
gSTM->insertData("Device/Laser/LaserEnable",(bool)1);
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)*(DEFAULT_MIN_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)*(DEFAULT_MAX_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MinLength",(float)(length_min));
gSTM->insertData("Device/Laser/MaxLength",(float)(length_max));
stringstream ss;
ss << "ALLaser running";
qiLogInfo("hardware.laser") << ss.str() << std::endl;
while(1)
{
if(mode==SEND_MODE_ON){
ret = urg_laserOn(&urg);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
mode=MODE_ON;
/* Connection */
connectToLaser();
}
if(mode==SEND_MODE_OFF){
scip_qt(&urg.serial_, NULL, ScipNoWaitReply);
mode=MODE_OFF;
}
if(mode==MODE_ON){
/* Request Data using GD-Command */
ret = urg_requestData(&urg, URG_GD, URG_FIRST, URG_LAST);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
refTime = getLocalTime();
/* Obtain Data */
n = urg_receiveData(&urg, data, data_max);
qiLogDebug("hardware.laser") << " n " << n << " expected " <<
angle_max - angle_min << std::endl;
if (n < 0) {
urg_exit(&urg, "urg_receiveData()");
}
end= getLocalTime();
sampleTime=end-refTime;
imemory=0;
for (i = 0; i < n; ++i) {
int x, y;
double angle = urg_index2rad(&urg, i);
// if (i < 50) {
qiLogDebug("hardware.laser") << i << " angle " << angle <<
" urgAngle " << urg_index2rad(&urg, i) <<
" dist " << data[i] << std::endl;
// }
int length = data[i];
if((length>=length_min)&&(length<=length_max)){
x = (int)((double)length * cos(angle));
y = (int)((double)length * sin(angle));
urgdata[imemory][0]= length;
urgdata[imemory][1]= angle;
urgdata[imemory][2]= x;
urgdata[imemory][3]= y;
imemory++;
}
}
for(;imemory<data_max;imemory++){
urgdata[imemory][0]= 0;
urgdata[imemory][1]= 0;
urgdata[imemory][2]= 0;
urgdata[imemory][3]= 0;
}
gSTM->insertData(valueName,urgdata);
usleep(1000);
}else{
usleep(10000);
}
}
urg_disconnect(&urg);
free(data);
}
//______________________________________________
// constructor
//______________________________________________
ALLaser::ALLaser(boost::shared_ptr<ALBroker> pBroker, const std::string& pName ): ALModule(pBroker, pName )
{
setModuleDescription( "Allow control over Hokuyo laser when available on Nao's head." );
functionName("laserOFF", "ALLaser", "Disable laser light");
BIND_METHOD( ALLaser::laserOFF );
functionName("laserON", "ALLaser", "Enable laser light and sampling");
BIND_METHOD( ALLaser::laserON );
functionName("setOpeningAngle", "ALLaser", "Set openning angle of the laser");
addParam("angle_min_f", "float containing the min value in rad, this value must be upper than -2.35619449 ");
addParam("angle_max_f", "float containing the max value in rad, this value must be lower than 2.092349795 ");
addMethodExample( "python",
"# Set the opening angle at -90/90 degres\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setOpeningAngle(-1.570796327,1.570796327)\n"
);
BIND_METHOD( ALLaser::setOpeningAngle );
functionName("setDetectingLength", "ALLaser", "Set detection threshold of the laser");
addParam("length_min_l", "int containing the min length that the laser will detect(mm), this value must be upper than 20 mm");
addParam("length_max_l", "int containing the max length that the laser will detect(mm), this value must be lower than 5600 mm");
addMethodExample( "python",
"# Set detection threshold at 500/3000 mm\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setDetectingLength(500,3000)\n"
);
BIND_METHOD( ALLaser::setDetectingLength );
// get broker on DCM and ALMemory
try {
gSTM = getParentBroker()->getMemoryProxy();
} catch(ALError& e) {
qiLogError("hardware.allaser") << "Could not connect to Memory. Error: " << e.what() << std::endl;
}
pthread_create(&urgThreadId, NULL, urgThread, NULL);
}
//______________________________________________
// destructor
//______________________________________________
ALLaser::~ALLaser()
{
pthread_cancel(urgThreadId);
}
void ALLaser::laserOFF(void){
mode = SEND_MODE_OFF;
gSTM->insertData("Device/Laser/LaserEnable",(bool)0);
}
void ALLaser::laserON(void){
mode = SEND_MODE_ON;
gSTM->insertData("Device/Laser/LaserEnable",(bool)1);
}
void ALLaser::setOpeningAngle(const AL::ALValue& angle_min_f, const AL::ALValue& angle_max_f){
angle_min = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_min_f / (2.0 * M_PI));
angle_max = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_max_f / (2.0 * M_PI));
if(angle_min<MIN_ANGLE_LASER) angle_min = MIN_ANGLE_LASER;
if(angle_max>MAX_ANGLE_LASER) angle_max = MAX_ANGLE_LASER;
if(angle_min>=angle_max){
angle_min = MIN_ANGLE_LASER;
angle_max = MAX_ANGLE_LASER;
}
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI) *(angle_min - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI) *(angle_max - MIDDLE_ANGLE) / RESOLUTION_LASER));
}
void ALLaser::setDetectingLength(const AL::ALValue& length_min_l,const AL::ALValue& length_max_l){
length_min=(int)length_min_l;
length_max=(int)length_max_l;
if(length_min<MIN_LENGTH_LASER) length_min = MIN_LENGTH_LASER;
if(length_max>MAX_LENGTH_LASER) length_min = MAX_LENGTH_LASER;
if(length_min>=length_max){
length_min = MIN_LENGTH_LASER;
length_max = MAX_LENGTH_LASER;
}
gSTM->insertData("Device/Laser/MinLength",(int)length_min);
gSTM->insertData("Device/Laser/MaxLength",(int)length_max);
}
//_________________________________________________
// Service functions
//_________________________________________________
int connectToLaserViaUSB(void) {
int success = -1;
const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */
// Try to connect at low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceUSB, URG_FAST_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
int connectToLaserViaACM(void) {
int success = -1;
const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceACM << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceACM, URG_FAST_SPEED);
if (success < 0)
{
std::stringstream ss;
ss << "Connection failure from " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
void connectToLaser(void){
int success = connectToLaserViaUSB();
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to USB, trying ACM... ";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
success = connectToLaserViaACM();
if (success < 0) {
std::stringstream ss;
ss << "Connection to laser failed";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
pthread_exit((void *)NULL);
}
else {
std::stringstream ss;
ss << "Connection to laser via ACM";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
else {
std::stringstream ss;
ss << "Connection to laser via USB";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
unsigned int getLocalTime(void){
struct timeval tv;
unsigned int val;
gettimeofday(&tv, NULL);
val = (unsigned int)((unsigned int)(tv.tv_usec/1000) + (unsigned int)(tv.tv_sec*1000));
// Time in ms
return val;
}
double index2rad(int index){
double radian = (2.0 * M_PI) *
(index - MIDDLE_ANGLE) / RESOLUTION_LASER;
return radian;
}
<|endoftext|> |
<commit_before>/* implementations of byte-at-a-time virtual read/writes for long mode that
never cause faults/exceptions and maybe do not affect TLB content */
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
Bit8u BX_CPP_AttrRegparmN(2)
BX_CPU_C::read_virtual_byte_64_nofail(unsigned s, Bit64u offset, uint8_t *error)
{
Bit8u data;
Bit64u laddr = get_laddr64(s, offset); // this is safe
if (! IsCanonical(laddr)) {
*error = 1;
return 0;
}
access_read_linear_nofail(laddr, 1, 0, BX_READ, (void *) &data, error);
return data;
}
int BX_CPU_C::access_read_linear_nofail(bx_address laddr, unsigned len, unsigned curr_pl, unsigned xlate_rw, void *data, uint8_t *error)
{
Bit32u combined_access = 0x06;
Bit32u lpf_mask = 0xfff; // 4K pages
bx_phy_address paddress, ppf, poffset = PAGE_OFFSET(laddr);
paddress = translate_linear_long_mode_nofail(laddr, error);
paddress = A20ADDR(paddress);
if (*error == 1) {
return 0;
}
access_read_physical(paddress, len, data);
return 0;
}
bx_phy_address BX_CPU_C::translate_linear_long_mode_nofail(bx_address laddr, uint8_t *error)
{
bx_phy_address entry_addr[4];
bx_phy_address ppf = BX_CPU_THIS_PTR cr3 & BX_CR3_PAGING_MASK;
Bit64u entry[4];
bx_bool nx_fault = 0;
int leaf;
Bit64u offset_mask = BX_CONST64(0x0000ffffffffffff);
Bit64u reserved = PAGING_PAE_RESERVED_BITS;
if (! BX_CPU_THIS_PTR efer.get_NXE())
reserved |= PAGE_DIRECTORY_NX_BIT;
for (leaf = BX_LEVEL_PML4;; --leaf) {
entry_addr[leaf] = ppf + ((laddr >> (9 + 9*leaf)) & 0xff8);
access_read_physical(entry_addr[leaf], 8, &entry[leaf]);
BX_NOTIFY_PHY_MEMORY_ACCESS(entry_addr[leaf], 8, BX_READ, (BX_PTE_ACCESS + leaf), (Bit8u*)(&entry[leaf]));
offset_mask >>= 9;
Bit64u curr_entry = entry[leaf];
int fault = check_entry_PAE(bx_paging_level[leaf], curr_entry, reserved, rw, &nx_fault);
if (fault >= 0) {
*error = 1;
return 0;
}
ppf = curr_entry & BX_CONST64(0x000ffffffffff000);
if (leaf == BX_LEVEL_PTE) break;
if (curr_entry & 0x80) {
if (leaf > (BX_LEVEL_PDE + !!bx_cpuid_support_1g_paging())) {
BX_DEBUG(("PAE %s: PS bit set !", bx_paging_level[leaf]));
*error = 1;
return 0;
}
ppf &= BX_CONST64(0x000fffffffffe000);
if (ppf & offset_mask) {
BX_DEBUG(("PAE %s: reserved bit is set: 0x" FMT_ADDRX64, bx_paging_level[leaf], curr_entry));
*error = 1;
return 0;
}
break;
}
} /* for (leaf = BX_LEVEL_PML4;; --leaf) */
return ppf | (laddr & offset_mask);
}
<commit_msg>PAE POE OPE PRECIOUS BODILY FLUIDS<commit_after>/* implementations of byte-at-a-time virtual read/writes for long mode that
never cause faults/exceptions and maybe do not affect TLB content */
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#define BX_CR3_PAGING_MASK (BX_CONST64(0x000ffffffffff000))
#define PAGE_DIRECTORY_NX_BIT (BX_CONST64(0x8000000000000000))
#define BX_PAGING_PHY_ADDRESS_RESERVED_BITS \
(BX_PHY_ADDRESS_RESERVED_BITS & BX_CONST64(0xfffffffffffff))
#define PAGING_PAE_RESERVED_BITS (BX_PAGING_PHY_ADDRESS_RESERVED_BITS)
#define BX_LEVEL_PML4 3
#define BX_LEVEL_PDPTE 2
#define BX_LEVEL_PDE 1
#define BX_LEVEL_PTE 0
Bit8u BX_CPP_AttrRegparmN(2)
BX_CPU_C::read_virtual_byte_64_nofail(unsigned s, Bit64u offset, uint8_t *error)
{
Bit8u data;
Bit64u laddr = get_laddr64(s, offset); // this is safe
if (! IsCanonical(laddr)) {
*error = 1;
return 0;
}
access_read_linear_nofail(laddr, 1, 0, BX_READ, (void *) &data, error);
return data;
}
int BX_CPU_C::access_read_linear_nofail(bx_address laddr, unsigned len, unsigned curr_pl, unsigned xlate_rw, void *data, uint8_t *error)
{
Bit32u combined_access = 0x06;
Bit32u lpf_mask = 0xfff; // 4K pages
bx_phy_address paddress, ppf, poffset = PAGE_OFFSET(laddr);
paddress = translate_linear_long_mode_nofail(laddr, error);
paddress = A20ADDR(paddress);
if (*error == 1) {
return 0;
}
access_read_physical(paddress, len, data);
return 0;
}
bx_phy_address BX_CPU_C::translate_linear_long_mode_nofail(bx_address laddr, uint8_t *error)
{
bx_phy_address entry_addr[4];
bx_phy_address ppf = BX_CPU_THIS_PTR cr3 & BX_CR3_PAGING_MASK;
Bit64u entry[4];
bx_bool nx_fault = 0;
int leaf;
Bit64u offset_mask = BX_CONST64(0x0000ffffffffffff);
Bit64u reserved = PAGING_PAE_RESERVED_BITS;
if (! BX_CPU_THIS_PTR efer.get_NXE())
reserved |= PAGE_DIRECTORY_NX_BIT;
for (leaf = BX_LEVEL_PML4;; --leaf) {
entry_addr[leaf] = ppf + ((laddr >> (9 + 9*leaf)) & 0xff8);
access_read_physical(entry_addr[leaf], 8, &entry[leaf]);
BX_NOTIFY_PHY_MEMORY_ACCESS(entry_addr[leaf], 8, BX_READ, (BX_PTE_ACCESS + leaf), (Bit8u*)(&entry[leaf]));
offset_mask >>= 9;
Bit64u curr_entry = entry[leaf];
int fault = check_entry_PAE(bx_paging_level[leaf], curr_entry, reserved, rw, &nx_fault);
if (fault >= 0) {
*error = 1;
return 0;
}
ppf = curr_entry & BX_CONST64(0x000ffffffffff000);
if (leaf == BX_LEVEL_PTE) break;
if (curr_entry & 0x80) {
if (leaf > (BX_LEVEL_PDE + !!bx_cpuid_support_1g_paging())) {
BX_DEBUG(("PAE %s: PS bit set !", bx_paging_level[leaf]));
*error = 1;
return 0;
}
ppf &= BX_CONST64(0x000fffffffffe000);
if (ppf & offset_mask) {
BX_DEBUG(("PAE %s: reserved bit is set: 0x" FMT_ADDRX64, bx_paging_level[leaf], curr_entry));
*error = 1;
return 0;
}
break;
}
} /* for (leaf = BX_LEVEL_PML4;; --leaf) */
return ppf | (laddr & offset_mask);
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_LISTS_HH
#define CQL3_LISTS_HH
#include "cql3/abstract_marker.hh"
#include "to_string.hh"
#include "utils/UUID_gen.hh"
#include "operation.hh"
namespace cql3 {
/**
* Static helper methods and classes for lists.
*/
class lists {
lists() = delete;
public:
static shared_ptr<column_specification> index_spec_of(shared_ptr<column_specification> column);
static shared_ptr<column_specification> value_spec_of(shared_ptr<column_specification> column);
class literal : public term::raw {
const std::vector<shared_ptr<term::raw>> _elements;
public:
explicit literal(std::vector<shared_ptr<term::raw>> elements)
: _elements(std::move(elements)) {
}
shared_ptr<term> prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver);
private:
void validate_assignable_to(database& db, const sstring keyspace, shared_ptr<column_specification> receiver);
public:
virtual assignment_testable::test_result test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) override;
virtual sstring to_string() const override;
};
class value : public multi_item_terminal, collection_terminal {
public:
std::vector<bytes_opt> _elements;
public:
explicit value(std::vector<bytes_opt> elements)
: _elements(std::move(elements)) {
}
static value from_serialized(bytes_view v, list_type type, serialization_format sf);
virtual bytes_opt get(const query_options& options) override;
virtual bytes get_with_protocol_version(serialization_format sf) override;
bool equals(shared_ptr<list_type_impl> lt, const value& v);
virtual std::vector<bytes_opt> get_elements() override;
virtual sstring to_string() const;
friend class lists;
};
/**
* Basically similar to a Value, but with some non-pure function (that need
* to be evaluated at execution time) in it.
*
* Note: this would also work for a list with bind markers, but we don't support
* that because 1) it's not excessively useful and 2) we wouldn't have a good
* column name to return in the ColumnSpecification for those markers (not a
* blocker per-se but we don't bother due to 1)).
*/
class delayed_value : public non_terminal {
std::vector<shared_ptr<term>> _elements;
public:
explicit delayed_value(std::vector<shared_ptr<term>> elements)
: _elements(std::move(elements)) {
}
virtual bool contains_bind_marker() const override;
virtual void collect_marker_specification(shared_ptr<variable_specifications> bound_names);
virtual shared_ptr<terminal> bind(const query_options& options) override;
};
/**
* A marker for List values and IN relations
*/
class marker : public abstract_marker {
public:
marker(int32_t bind_index, ::shared_ptr<column_specification> receiver)
: abstract_marker{bind_index, std::move(receiver)}
{ }
#if 0
protected Marker(int bindIndex, ColumnSpecification receiver)
{
super(bindIndex, receiver);
assert receiver.type instanceof ListType;
}
#endif
virtual ::shared_ptr<terminal> bind(const query_options& options) override;
#if 0
public Value bind(QueryOptions options) throws InvalidRequestException
{
ByteBuffer value = options.getValues().get(bindIndex);
return value == null ? null : Value.fromSerialized(value, (ListType)receiver.type, options.getProtocolVersion());
}
#endif
};
/*
* For prepend, we need to be able to generate unique but decreasing time
* UUID, which is a bit challenging. To do that, given a time in milliseconds,
* we adds a number representing the 100-nanoseconds precision and make sure
* that within the same millisecond, that number is always decreasing. We
* do rely on the fact that the user will only provide decreasing
* milliseconds timestamp for that purpose.
*/
private:
class precision_time {
public:
// Our reference time (1 jan 2010, 00:00:00) in milliseconds.
static constexpr const db_clock::time_point REFERENCE_TIME{std::chrono::milliseconds(1262304000000)};
private:
static thread_local precision_time _last;
public:
db_clock::time_point millis;
int32_t nanos;
static precision_time get_next(db_clock::time_point millis);
};
public:
class setter : public operation {
public:
setter(const column_definition& column, shared_ptr<term> t)
: operation(column, std::move(t)) {
}
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class setter_by_index : public operation {
shared_ptr<term> _idx;
public:
setter_by_index(const column_definition& column, shared_ptr<term> idx, shared_ptr<term> t)
: operation(column, std::move(t)), _idx(std::move(idx)) {
}
virtual bool requires_read() override;
virtual void collect_marker_specification(shared_ptr<variable_specifications> bound_names);
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class appender : public operation {
public:
using operation::operation;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
static void do_append(shared_ptr<term> t,
mutation& m,
const exploded_clustering_prefix& prefix,
const column_definition& column,
const update_parameters& params,
tombstone ts = {});
class prepender : public operation {
public:
using operation::operation;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class discarder : public operation {
public:
discarder(const column_definition& column, shared_ptr<term> t)
: operation(column, std::move(t)) {
}
virtual bool requires_read() override;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class discarder_by_index : public operation {
public:
discarder_by_index(const column_definition& column, shared_ptr<term> idx)
: operation(column, std::move(idx)) {
}
virtual bool requires_read() override;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params);
};
};
}
#endif
<commit_msg>cql3: remove gunk from lists.hh<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_LISTS_HH
#define CQL3_LISTS_HH
#include "cql3/abstract_marker.hh"
#include "to_string.hh"
#include "utils/UUID_gen.hh"
#include "operation.hh"
namespace cql3 {
/**
* Static helper methods and classes for lists.
*/
class lists {
lists() = delete;
public:
static shared_ptr<column_specification> index_spec_of(shared_ptr<column_specification> column);
static shared_ptr<column_specification> value_spec_of(shared_ptr<column_specification> column);
class literal : public term::raw {
const std::vector<shared_ptr<term::raw>> _elements;
public:
explicit literal(std::vector<shared_ptr<term::raw>> elements)
: _elements(std::move(elements)) {
}
shared_ptr<term> prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver);
private:
void validate_assignable_to(database& db, const sstring keyspace, shared_ptr<column_specification> receiver);
public:
virtual assignment_testable::test_result test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) override;
virtual sstring to_string() const override;
};
class value : public multi_item_terminal, collection_terminal {
public:
std::vector<bytes_opt> _elements;
public:
explicit value(std::vector<bytes_opt> elements)
: _elements(std::move(elements)) {
}
static value from_serialized(bytes_view v, list_type type, serialization_format sf);
virtual bytes_opt get(const query_options& options) override;
virtual bytes get_with_protocol_version(serialization_format sf) override;
bool equals(shared_ptr<list_type_impl> lt, const value& v);
virtual std::vector<bytes_opt> get_elements() override;
virtual sstring to_string() const;
friend class lists;
};
/**
* Basically similar to a Value, but with some non-pure function (that need
* to be evaluated at execution time) in it.
*
* Note: this would also work for a list with bind markers, but we don't support
* that because 1) it's not excessively useful and 2) we wouldn't have a good
* column name to return in the ColumnSpecification for those markers (not a
* blocker per-se but we don't bother due to 1)).
*/
class delayed_value : public non_terminal {
std::vector<shared_ptr<term>> _elements;
public:
explicit delayed_value(std::vector<shared_ptr<term>> elements)
: _elements(std::move(elements)) {
}
virtual bool contains_bind_marker() const override;
virtual void collect_marker_specification(shared_ptr<variable_specifications> bound_names);
virtual shared_ptr<terminal> bind(const query_options& options) override;
};
/**
* A marker for List values and IN relations
*/
class marker : public abstract_marker {
public:
marker(int32_t bind_index, ::shared_ptr<column_specification> receiver)
: abstract_marker{bind_index, std::move(receiver)}
{ }
virtual ::shared_ptr<terminal> bind(const query_options& options) override;
};
/*
* For prepend, we need to be able to generate unique but decreasing time
* UUID, which is a bit challenging. To do that, given a time in milliseconds,
* we adds a number representing the 100-nanoseconds precision and make sure
* that within the same millisecond, that number is always decreasing. We
* do rely on the fact that the user will only provide decreasing
* milliseconds timestamp for that purpose.
*/
private:
class precision_time {
public:
// Our reference time (1 jan 2010, 00:00:00) in milliseconds.
static constexpr const db_clock::time_point REFERENCE_TIME{std::chrono::milliseconds(1262304000000)};
private:
static thread_local precision_time _last;
public:
db_clock::time_point millis;
int32_t nanos;
static precision_time get_next(db_clock::time_point millis);
};
public:
class setter : public operation {
public:
setter(const column_definition& column, shared_ptr<term> t)
: operation(column, std::move(t)) {
}
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class setter_by_index : public operation {
shared_ptr<term> _idx;
public:
setter_by_index(const column_definition& column, shared_ptr<term> idx, shared_ptr<term> t)
: operation(column, std::move(t)), _idx(std::move(idx)) {
}
virtual bool requires_read() override;
virtual void collect_marker_specification(shared_ptr<variable_specifications> bound_names);
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class appender : public operation {
public:
using operation::operation;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
static void do_append(shared_ptr<term> t,
mutation& m,
const exploded_clustering_prefix& prefix,
const column_definition& column,
const update_parameters& params,
tombstone ts = {});
class prepender : public operation {
public:
using operation::operation;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class discarder : public operation {
public:
discarder(const column_definition& column, shared_ptr<term> t)
: operation(column, std::move(t)) {
}
virtual bool requires_read() override;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override;
};
class discarder_by_index : public operation {
public:
discarder_by_index(const column_definition& column, shared_ptr<term> idx)
: operation(column, std::move(idx)) {
}
virtual bool requires_read() override;
virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params);
};
};
}
#endif
<|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.
*/
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <sys/time.h>
#include <faiss/IndexPQ.h>
#include <faiss/IndexIVFPQ.h>
#include <faiss/IndexFlat.h>
#include <faiss/index_io.h>
double elapsed ()
{
struct timeval tv;
gettimeofday (&tv, nullptr);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
int main ()
{
double t0 = elapsed();
// dimension of the vectors to index
int d = 64;
// size of the database we plan to index
size_t nb = 1000 * 1000;
size_t add_bs = 10000; // # size of the blocks to add
// make a set of nt training vectors in the unit cube
// (could be the database)
size_t nt = 100 * 1000;
//---------------------------------------------------------------
// Define the core quantizer
// We choose a multiple inverted index for faster training with less data
// and because it usually offers best accuracy/speed trade-offs
//
// We here assume that its lifespan of this coarse quantizer will cover the
// lifespan of the inverted-file quantizer IndexIVFFlat below
// With dynamic allocation, one may give the responsability to free the
// quantizer to the inverted-file index (with attribute do_delete_quantizer)
//
// Note: a regular clustering algorithm would be defined as:
// faiss::IndexFlatL2 coarse_quantizer (d);
//
// Use nhash=2 subquantizers used to define the product coarse quantizer
// Number of bits: we will have 2^nbits_coarse centroids per subquantizer
// meaning (2^12)^nhash distinct inverted lists
//
// The parameter bytes_per_code is determined by the memory
// constraint, the dataset will use nb * (bytes_per_code + 8)
// bytes.
//
// The parameter nbits_subq is determined by the size of the dataset to index.
//
size_t nhash = 2;
size_t nbits_subq = 9;
size_t ncentroids = 1 << (nhash * nbits_subq); // total # of centroids
int bytes_per_code = 16;
faiss::MultiIndexQuantizer coarse_quantizer (d, nhash, nbits_subq);
printf ("IMI (%ld,%ld): %ld virtual centroids (target: %ld base vectors)",
nhash, nbits_subq, ncentroids, nb);
// the coarse quantizer should not be dealloced before the index
// 4 = nb of bytes per code (d must be a multiple of this)
// 8 = nb of bits per sub-code (almost always 8)
faiss::MetricType metric = faiss::METRIC_L2; // can be METRIC_INNER_PRODUCT
faiss::IndexIVFPQ index (&coarse_quantizer, d, ncentroids, bytes_per_code, 8);
index.quantizer_trains_alone = true;
// define the number of probes. 2048 is for high-dim, overkill in practice
// Use 4-1024 depending on the trade-off speed accuracy that you want
index.nprobe = 2048;
std::mt19937 rng;
std::uniform_real_distribution<> distrib;
{ // training.
// The distribution of the training vectors should be the same
// as the database vectors. It could be a sub-sample of the
// database vectors, if sampling is not biased. Here we just
// randomly generate the vectors.
printf ("[%.3f s] Generating %ld vectors in %dD for training\n",
elapsed() - t0, nt, d);
std::vector <float> trainvecs (nt * d);
for (size_t i = 0; i < nt; i++) {
for (size_t j = 0; j < d; j++) {
trainvecs[i * d + j] = distrib(rng);
}
}
printf ("[%.3f s] Training the index\n", elapsed() - t0);
index.verbose = true;
index.train (nt, trainvecs.data());
}
// the index can be re-loaded later with
// faiss::Index * idx = faiss::read_index("/tmp/trained_index.faissindex");
faiss::write_index(&index, "/tmp/trained_index.faissindex");
size_t nq;
std::vector<float> queries;
{ // populating the database
printf ("[%.3f s] Building a dataset of %ld vectors to index\n",
elapsed() - t0, nb);
std::vector <float> database (nb * d);
std::vector <long> ids (nb);
for (size_t i = 0; i < nb; i++) {
for (size_t j = 0; j < d; j++) {
database[i * d + j] = distrib(rng);
}
ids[i] = 8760000000L + i;
}
printf ("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
for (size_t begin = 0; begin < nb; begin += add_bs) {
size_t end = std::min (begin + add_bs, nb);
index.add_with_ids (end - begin,
database.data() + d * begin,
ids.data() + begin);
}
// remember a few elements from the database as queries
int i0 = 1234;
int i1 = 1244;
nq = i1 - i0;
queries.resize (nq * d);
for (int i = i0; i < i1; i++) {
for (int j = 0; j < d; j++) {
queries [(i - i0) * d + j] = database [i * d + j];
}
}
}
// A few notes on the internal format of the index:
//
// - the positing lists for PQ codes are index.codes, which is a
// std::vector < std::vector<uint8_t> >
// if n is the length of posting list #i, codes[i] has length bytes_per_code * n
//
// - the corresponding ids are stored in index.ids
//
// - given a vector float *x, finding which k centroids are
// closest to it (ie to find the nearest neighbors) can be done with
//
// long *centroid_ids = new long[k];
// float *distances = new float[k];
// index.quantizer->search (1, x, k, dis, centroids_ids);
//
faiss::write_index(&index, "/tmp/populated_index.faissindex");
{ // searching the database
int k = 5;
printf ("[%.3f s] Searching the %d nearest neighbors "
"of %ld vectors in the index\n",
elapsed() - t0, k, nq);
std::vector<faiss::Index::idx_t> nns (k * nq);
std::vector<float> dis (k * nq);
index.search (nq, queries.data(), k, dis.data(), nns.data());
printf ("[%.3f s] Query results (vector ids, then distances):\n",
elapsed() - t0);
for (int i = 0; i < nq; i++) {
printf ("query %2d: ", i);
for (int j = 0; j < k; j++) {
printf ("%7ld ", nns[j + i * k]);
}
printf ("\n dis: ");
for (int j = 0; j < k; j++) {
printf ("%7g ", dis[j + i * k]);
}
printf ("\n");
}
}
return 0;
}
<commit_msg>Update demo_imi_pq.cpp (#1636)<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 <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <sys/time.h>
#include <faiss/IndexPQ.h>
#include <faiss/IndexIVFPQ.h>
#include <faiss/IndexFlat.h>
#include <faiss/index_io.h>
double elapsed ()
{
struct timeval tv;
gettimeofday (&tv, nullptr);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
int main ()
{
double t0 = elapsed();
// dimension of the vectors to index
int d = 64;
// size of the database we plan to index
size_t nb = 1000 * 1000;
size_t add_bs = 10000; // # size of the blocks to add
// make a set of nt training vectors in the unit cube
// (could be the database)
size_t nt = 100 * 1000;
//---------------------------------------------------------------
// Define the core quantizer
// We choose a multiple inverted index for faster training with less data
// and because it usually offers best accuracy/speed trade-offs
//
// We here assume that its lifespan of this coarse quantizer will cover the
// lifespan of the inverted-file quantizer IndexIVFFlat below
// With dynamic allocation, one may give the responsability to free the
// quantizer to the inverted-file index (with attribute do_delete_quantizer)
//
// Note: a regular clustering algorithm would be defined as:
// faiss::IndexFlatL2 coarse_quantizer (d);
//
// Use nhash=2 subquantizers used to define the product coarse quantizer
// Number of bits: we will have 2^nbits_coarse centroids per subquantizer
// meaning (2^12)^nhash distinct inverted lists
//
// The parameter bytes_per_code is determined by the memory
// constraint, the dataset will use nb * (bytes_per_code + 8)
// bytes.
//
// The parameter nbits_subq is determined by the size of the dataset to index.
//
size_t nhash = 2;
size_t nbits_subq = 9;
size_t ncentroids = 1 << (nhash * nbits_subq); // total # of centroids
int bytes_per_code = 16;
faiss::MultiIndexQuantizer coarse_quantizer (d, nhash, nbits_subq);
printf ("IMI (%ld,%ld): %ld virtual centroids (target: %ld base vectors)",
nhash, nbits_subq, ncentroids, nb);
// the coarse quantizer should not be dealloced before the index
// 4 = nb of bytes per code (d must be a multiple of this)
// 8 = nb of bits per sub-code (almost always 8)
faiss::MetricType metric = faiss::METRIC_L2; // can be METRIC_INNER_PRODUCT
faiss::IndexIVFPQ index (&coarse_quantizer, d, ncentroids, bytes_per_code, 8);
index.quantizer_trains_alone = true;
// define the number of probes. 2048 is for high-dim, overkill in practice
// Use 4-1024 depending on the trade-off speed accuracy that you want
index.nprobe = 2048;
std::mt19937 rng;
std::uniform_real_distribution<> distrib;
{ // training.
// The distribution of the training vectors should be the same
// as the database vectors. It could be a sub-sample of the
// database vectors, if sampling is not biased. Here we just
// randomly generate the vectors.
printf ("[%.3f s] Generating %ld vectors in %dD for training\n",
elapsed() - t0, nt, d);
std::vector <float> trainvecs (nt * d);
for (size_t i = 0; i < nt; i++) {
for (size_t j = 0; j < d; j++) {
trainvecs[i * d + j] = distrib(rng);
}
}
printf ("[%.3f s] Training the index\n", elapsed() - t0);
index.verbose = true;
index.train (nt, trainvecs.data());
}
// the index can be re-loaded later with
// faiss::Index * idx = faiss::read_index("/tmp/trained_index.faissindex");
faiss::write_index(&index, "/tmp/trained_index.faissindex");
size_t nq;
std::vector<float> queries;
{ // populating the database
printf ("[%.3f s] Building a dataset of %ld vectors to index\n",
elapsed() - t0, nb);
std::vector <float> database (nb * d);
std::vector <faiss::Index::idx_t> ids (nb);
for (size_t i = 0; i < nb; i++) {
for (size_t j = 0; j < d; j++) {
database[i * d + j] = distrib(rng);
}
ids[i] = 8760000000L + i;
}
printf ("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
for (size_t begin = 0; begin < nb; begin += add_bs) {
size_t end = std::min (begin + add_bs, nb);
index.add_with_ids (end - begin,
database.data() + d * begin,
ids.data() + begin);
}
// remember a few elements from the database as queries
int i0 = 1234;
int i1 = 1244;
nq = i1 - i0;
queries.resize (nq * d);
for (int i = i0; i < i1; i++) {
for (int j = 0; j < d; j++) {
queries [(i - i0) * d + j] = database [i * d + j];
}
}
}
// A few notes on the internal format of the index:
//
// - the positing lists for PQ codes are index.codes, which is a
// std::vector < std::vector<uint8_t> >
// if n is the length of posting list #i, codes[i] has length bytes_per_code * n
//
// - the corresponding ids are stored in index.ids
//
// - given a vector float *x, finding which k centroids are
// closest to it (ie to find the nearest neighbors) can be done with
//
// faiss::Index::idx_t *centroid_ids = new faiss::Index::idx_t[k];
// float *distances = new float[k];
// index.quantizer->search (1, x, k, dis, centroids_ids);
//
faiss::write_index(&index, "/tmp/populated_index.faissindex");
{ // searching the database
int k = 5;
printf ("[%.3f s] Searching the %d nearest neighbors "
"of %ld vectors in the index\n",
elapsed() - t0, k, nq);
std::vector<faiss::Index::idx_t> nns (k * nq);
std::vector<float> dis (k * nq);
index.search (nq, queries.data(), k, dis.data(), nns.data());
printf ("[%.3f s] Query results (vector ids, then distances):\n",
elapsed() - t0);
for (int i = 0; i < nq; i++) {
printf ("query %2d: ", i);
for (int j = 0; j < k; j++) {
printf ("%7ld ", nns[j + i * k]);
}
printf ("\n dis: ");
for (int j = 0; j < k; j++) {
printf ("%7g ", dis[j + i * k]);
}
printf ("\n");
}
}
return 0;
}
<|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.
*/
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/time.h>
#include <faiss/AutoTune.h>
/**
* To run this demo, please download the ANN_SIFT1M dataset from
*
* http://corpus-texmex.irisa.fr/
*
* and unzip it to the sudirectory sift1M.
**/
/*****************************************************
* I/O functions for fvecs and ivecs
*****************************************************/
float * fvecs_read (const char *fname,
size_t *d_out, size_t *n_out)
{
FILE *f = fopen(fname, "r");
if(!f) {
fprintf(stderr, "could not open %s\n", fname);
perror("");
abort();
}
int d;
fread(&d, 1, sizeof(int), f);
assert((d > 0 && d < 1000000) || !"unreasonable dimension");
fseek(f, 0, SEEK_SET);
struct stat st;
fstat(fileno(f), &st);
size_t sz = st.st_size;
assert(sz % ((d + 1) * 4) == 0 || !"weird file size");
size_t n = sz / ((d + 1) * 4);
*d_out = d; *n_out = n;
float *x = new float[n * (d + 1)];
size_t nr = fread(x, sizeof(float), n * (d + 1), f);
assert(nr == n * (d + 1) || !"could not read whole file");
// shift array to remove row headers
for(size_t i = 0; i < n; i++)
memmove(x + i * d, x + 1 + i * (d + 1), d * sizeof(*x));
fclose(f);
return x;
}
// not very clean, but works as long as sizeof(int) == sizeof(float)
int *ivecs_read(const char *fname, size_t *d_out, size_t *n_out)
{
return (int*)fvecs_read(fname, d_out, n_out);
}
double elapsed ()
{
struct timeval tv;
gettimeofday (&tv, nullptr);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
int main()
{
double t0 = elapsed();
// this is typically the fastest one.
const char *index_key = "IVF4096,Flat";
// these ones have better memory usage
// const char *index_key = "Flat";
// const char *index_key = "PQ32";
// const char *index_key = "PCA80,Flat";
// const char *index_key = "IVF4096,PQ8+16";
// const char *index_key = "IVF4096,PQ32";
// const char *index_key = "IMI2x8,PQ32";
// const char *index_key = "IMI2x8,PQ8+16";
// const char *index_key = "OPQ16_64,IMI2x8,PQ8+16";
faiss::Index * index;
size_t d;
{
printf ("[%.3f s] Loading train set\n", elapsed() - t0);
size_t nt;
float *xt = fvecs_read("sift1M/sift_learn.fvecs", &d, &nt);
printf ("[%.3f s] Preparing index \"%s\" d=%ld\n",
elapsed() - t0, index_key, d);
index = faiss::index_factory(d, index_key);
printf ("[%.3f s] Training on %ld vectors\n", elapsed() - t0, nt);
index->train(nt, xt);
delete [] xt;
}
{
printf ("[%.3f s] Loading database\n", elapsed() - t0);
size_t nb, d2;
float *xb = fvecs_read("sift1M/sift_base.fvecs", &d2, &nb);
assert(d == d2 || !"dataset does not have same dimension as train set");
printf ("[%.3f s] Indexing database, size %ld*%ld\n",
elapsed() - t0, nb, d);
index->add(nb, xb);
delete [] xb;
}
size_t nq;
float *xq;
{
printf ("[%.3f s] Loading queries\n", elapsed() - t0);
size_t d2;
xq = fvecs_read("sift1M/sift_query.fvecs", &d2, &nq);
assert(d == d2 || !"query does not have same dimension as train set");
}
size_t k; // nb of results per query in the GT
faiss::Index::idx_t *gt; // nq * k matrix of ground-truth nearest-neighbors
{
printf ("[%.3f s] Loading ground truth for %ld queries\n",
elapsed() - t0, nq);
// load ground-truth and convert int to long
size_t nq2;
int *gt_int = ivecs_read("sift1M/sift_groundtruth.ivecs", &k, &nq2);
assert(nq2 == nq || !"incorrect nb of ground truth entries");
gt = new faiss::Index::idx_t[k * nq];
for(int i = 0; i < k * nq; i++) {
gt[i] = gt_int[i];
}
delete [] gt_int;
}
// Result of the auto-tuning
std::string selected_params;
{ // run auto-tuning
printf ("[%.3f s] Preparing auto-tune criterion 1-recall at 1 "
"criterion, with k=%ld nq=%ld\n", elapsed() - t0, k, nq);
faiss::OneRecallAtRCriterion crit(nq, 1);
crit.set_groundtruth (k, nullptr, gt);
crit.nnn = k; // by default, the criterion will request only 1 NN
printf ("[%.3f s] Preparing auto-tune parameters\n", elapsed() - t0);
faiss::ParameterSpace params;
params.initialize(index);
printf ("[%.3f s] Auto-tuning over %ld parameters (%ld combinations)\n",
elapsed() - t0, params.parameter_ranges.size(),
params.n_combinations());
faiss::OperatingPoints ops;
params.explore (index, nq, xq, crit, &ops);
printf ("[%.3f s] Found the following operating points: \n",
elapsed() - t0);
ops.display ();
// keep the first parameter that obtains > 0.5 1-recall@1
for (int i = 0; i < ops.optimal_pts.size(); i++) {
if (ops.optimal_pts[i].perf > 0.5) {
selected_params = ops.optimal_pts[i].key;
break;
}
}
assert (selected_params.size() >= 0 ||
!"could not find good enough op point");
}
{ // Use the found configuration to perform a search
faiss::ParameterSpace params;
printf ("[%.3f s] Setting parameter configuration \"%s\" on index\n",
elapsed() - t0, selected_params.c_str());
params.set_index_parameters (index, selected_params.c_str());
printf ("[%.3f s] Perform a search on %ld queries\n",
elapsed() - t0, nq);
// output buffers
faiss::Index::idx_t *I = new faiss::Index::idx_t[nq * k];
float *D = new float[nq * k];
index->search(nq, xq, k, D, I);
printf ("[%.3f s] Compute recalls\n", elapsed() - t0);
// evaluate result by hand.
int n_1 = 0, n_10 = 0, n_100 = 0;
for(int i = 0; i < nq; i++) {
int gt_nn = gt[i * k];
for(int j = 0; j < k; j++) {
if (I[i * k + j] == gt_nn) {
if(j < 1) n_1++;
if(j < 10) n_10++;
if(j < 100) n_100++;
}
}
}
printf("R@1 = %.4f\n", n_1 / float(nq));
printf("R@10 = %.4f\n", n_10 / float(nq));
printf("R@100 = %.4f\n", n_100 / float(nq));
}
delete [] xq;
delete [] gt;
delete index;
return 0;
}
<commit_msg>Update demo_sift1M.cpp<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 <cmath>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/time.h>
#include <faiss/AutoTune.h>
#include <faiss/index_factory.h>
/**
* To run this demo, please download the ANN_SIFT1M dataset from
*
* http://corpus-texmex.irisa.fr/
*
* and unzip it to the sudirectory sift1M.
**/
/*****************************************************
* I/O functions for fvecs and ivecs
*****************************************************/
float * fvecs_read (const char *fname,
size_t *d_out, size_t *n_out)
{
FILE *f = fopen(fname, "r");
if(!f) {
fprintf(stderr, "could not open %s\n", fname);
perror("");
abort();
}
int d;
fread(&d, 1, sizeof(int), f);
assert((d > 0 && d < 1000000) || !"unreasonable dimension");
fseek(f, 0, SEEK_SET);
struct stat st;
fstat(fileno(f), &st);
size_t sz = st.st_size;
assert(sz % ((d + 1) * 4) == 0 || !"weird file size");
size_t n = sz / ((d + 1) * 4);
*d_out = d; *n_out = n;
float *x = new float[n * (d + 1)];
size_t nr = fread(x, sizeof(float), n * (d + 1), f);
assert(nr == n * (d + 1) || !"could not read whole file");
// shift array to remove row headers
for(size_t i = 0; i < n; i++)
memmove(x + i * d, x + 1 + i * (d + 1), d * sizeof(*x));
fclose(f);
return x;
}
// not very clean, but works as long as sizeof(int) == sizeof(float)
int *ivecs_read(const char *fname, size_t *d_out, size_t *n_out)
{
return (int*)fvecs_read(fname, d_out, n_out);
}
double elapsed ()
{
struct timeval tv;
gettimeofday (&tv, nullptr);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
int main()
{
double t0 = elapsed();
// this is typically the fastest one.
const char *index_key = "IVF4096,Flat";
// these ones have better memory usage
// const char *index_key = "Flat";
// const char *index_key = "PQ32";
// const char *index_key = "PCA80,Flat";
// const char *index_key = "IVF4096,PQ8+16";
// const char *index_key = "IVF4096,PQ32";
// const char *index_key = "IMI2x8,PQ32";
// const char *index_key = "IMI2x8,PQ8+16";
// const char *index_key = "OPQ16_64,IMI2x8,PQ8+16";
faiss::Index * index;
size_t d;
{
printf ("[%.3f s] Loading train set\n", elapsed() - t0);
size_t nt;
float *xt = fvecs_read("sift1M/sift_learn.fvecs", &d, &nt);
printf ("[%.3f s] Preparing index \"%s\" d=%ld\n",
elapsed() - t0, index_key, d);
index = faiss::index_factory(d, index_key);
printf ("[%.3f s] Training on %ld vectors\n", elapsed() - t0, nt);
index->train(nt, xt);
delete [] xt;
}
{
printf ("[%.3f s] Loading database\n", elapsed() - t0);
size_t nb, d2;
float *xb = fvecs_read("sift1M/sift_base.fvecs", &d2, &nb);
assert(d == d2 || !"dataset does not have same dimension as train set");
printf ("[%.3f s] Indexing database, size %ld*%ld\n",
elapsed() - t0, nb, d);
index->add(nb, xb);
delete [] xb;
}
size_t nq;
float *xq;
{
printf ("[%.3f s] Loading queries\n", elapsed() - t0);
size_t d2;
xq = fvecs_read("sift1M/sift_query.fvecs", &d2, &nq);
assert(d == d2 || !"query does not have same dimension as train set");
}
size_t k; // nb of results per query in the GT
faiss::Index::idx_t *gt; // nq * k matrix of ground-truth nearest-neighbors
{
printf ("[%.3f s] Loading ground truth for %ld queries\n",
elapsed() - t0, nq);
// load ground-truth and convert int to long
size_t nq2;
int *gt_int = ivecs_read("sift1M/sift_groundtruth.ivecs", &k, &nq2);
assert(nq2 == nq || !"incorrect nb of ground truth entries");
gt = new faiss::Index::idx_t[k * nq];
for(int i = 0; i < k * nq; i++) {
gt[i] = gt_int[i];
}
delete [] gt_int;
}
// Result of the auto-tuning
std::string selected_params;
{ // run auto-tuning
printf ("[%.3f s] Preparing auto-tune criterion 1-recall at 1 "
"criterion, with k=%ld nq=%ld\n", elapsed() - t0, k, nq);
faiss::OneRecallAtRCriterion crit(nq, 1);
crit.set_groundtruth (k, nullptr, gt);
crit.nnn = k; // by default, the criterion will request only 1 NN
printf ("[%.3f s] Preparing auto-tune parameters\n", elapsed() - t0);
faiss::ParameterSpace params;
params.initialize(index);
printf ("[%.3f s] Auto-tuning over %ld parameters (%ld combinations)\n",
elapsed() - t0, params.parameter_ranges.size(),
params.n_combinations());
faiss::OperatingPoints ops;
params.explore (index, nq, xq, crit, &ops);
printf ("[%.3f s] Found the following operating points: \n",
elapsed() - t0);
ops.display ();
// keep the first parameter that obtains > 0.5 1-recall@1
for (int i = 0; i < ops.optimal_pts.size(); i++) {
if (ops.optimal_pts[i].perf > 0.5) {
selected_params = ops.optimal_pts[i].key;
break;
}
}
assert (selected_params.size() >= 0 ||
!"could not find good enough op point");
}
{ // Use the found configuration to perform a search
faiss::ParameterSpace params;
printf ("[%.3f s] Setting parameter configuration \"%s\" on index\n",
elapsed() - t0, selected_params.c_str());
params.set_index_parameters (index, selected_params.c_str());
printf ("[%.3f s] Perform a search on %ld queries\n",
elapsed() - t0, nq);
// output buffers
faiss::Index::idx_t *I = new faiss::Index::idx_t[nq * k];
float *D = new float[nq * k];
index->search(nq, xq, k, D, I);
printf ("[%.3f s] Compute recalls\n", elapsed() - t0);
// evaluate result by hand.
int n_1 = 0, n_10 = 0, n_100 = 0;
for(int i = 0; i < nq; i++) {
int gt_nn = gt[i * k];
for(int j = 0; j < k; j++) {
if (I[i * k + j] == gt_nn) {
if(j < 1) n_1++;
if(j < 10) n_10++;
if(j < 100) n_100++;
}
}
}
printf("R@1 = %.4f\n", n_1 / float(nq));
printf("R@10 = %.4f\n", n_10 / float(nq));
printf("R@100 = %.4f\n", n_100 / float(nq));
}
delete [] xq;
delete [] gt;
delete index;
return 0;
}
<|endoftext|> |
<commit_before>/* 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/.
*
* Copyright 2019 (c) fortiss (Author: Stefan Profanter)
*/
#include "custom_memory_manager.h"
#include <open62541/plugin/log_stdout.h>
#include <open62541/server_config_default.h>
#include <open62541/types.h>
#include "ua_server_internal.h"
#include "testing_networklayers.h"
#define RECEIVE_BUFFER_SIZE 65535
/*
** Main entry point. The fuzzer invokes this function with each
** fuzzed input.
*/
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if(size <= 4)
return 0;
if(!UA_memoryManager_setLimitFromLast4Bytes(data, size))
return 0;
size -= 4;
UA_Connection c = createDummyConnection(RECEIVE_BUFFER_SIZE, NULL);
/* less debug output */
UA_ServerConfig initialConfig;
memset(&initialConfig, 0, sizeof(UA_ServerConfig));
UA_StatusCode retval = UA_ServerConfig_setDefault(&initialConfig);
initialConfig.allowEmptyVariables = UA_RULEHANDLING_ACCEPT;
if(retval != UA_STATUSCODE_GOOD) {
UA_ServerConfig_clean(&initialConfig);
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
"Could not generate the server config");
return 0;
}
UA_Server *server = UA_Server_newWithConfig(&initialConfig);
if(!server) {
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
"Could not create server instance using UA_Server_new");
return 0;
}
// we need to copy the message because it will be freed in the processing function
UA_ByteString msg = UA_ByteString();
retval = UA_ByteString_allocBuffer(&msg, size);
if(retval != UA_STATUSCODE_GOOD) {
UA_Server_delete(server);
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
"Could not allocate message buffer");
return 0;
}
memcpy(msg.data, data, size);
UA_Server_processBinaryMessage(server, &c, &msg);
// if we got an invalid chunk, the message is not deleted, so delete it here
UA_ByteString_clear(&msg);
UA_Server_run_shutdown(server);
UA_Server_delete(server);
c.close(&c);
return 0;
}
<commit_msg>refactor(tests): Use C idioms in fuzz_binary_message.cc for consistency<commit_after>/* 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/.
*
* Copyright 2019 (c) fortiss (Author: Stefan Profanter)
*/
#include "custom_memory_manager.h"
#include <open62541/plugin/log_stdout.h>
#include <open62541/server_config_default.h>
#include <open62541/types.h>
#include "ua_server_internal.h"
#include "testing_networklayers.h"
#define RECEIVE_BUFFER_SIZE 65535
/*
** Main entry point. The fuzzer invokes this function with each
** fuzzed input.
*/
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if(size <= 4)
return 0;
if(!UA_memoryManager_setLimitFromLast4Bytes(data, size))
return 0;
size -= 4;
UA_Connection c = createDummyConnection(RECEIVE_BUFFER_SIZE, NULL);
/* less debug output */
UA_ServerConfig initialConfig;
memset(&initialConfig, 0, sizeof(UA_ServerConfig));
UA_StatusCode retval = UA_ServerConfig_setDefault(&initialConfig);
initialConfig.allowEmptyVariables = UA_RULEHANDLING_ACCEPT;
if(retval != UA_STATUSCODE_GOOD) {
UA_ServerConfig_clean(&initialConfig);
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
"Could not generate the server config");
return 0;
}
UA_Server *server = UA_Server_newWithConfig(&initialConfig);
if(!server) {
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
"Could not create server instance using UA_Server_new");
return 0;
}
// we need to copy the message because it will be freed in the processing function
UA_ByteString msg = UA_BYTESTRING_NULL;
retval = UA_ByteString_allocBuffer(&msg, size);
if(retval != UA_STATUSCODE_GOOD) {
UA_Server_delete(server);
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
"Could not allocate message buffer");
return 0;
}
memcpy(msg.data, data, size);
UA_Server_processBinaryMessage(server, &c, &msg);
// if we got an invalid chunk, the message is not deleted, so delete it here
UA_ByteString_clear(&msg);
UA_Server_run_shutdown(server);
UA_Server_delete(server);
c.close(&c);
return 0;
}
<|endoftext|> |
<commit_before>//
// Created by Rui Wang on 16-4-30.
//
#include "gtest/gtest.h"
#include "harness.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <backend/planner/hybrid_scan_plan.h>
#include <backend/executor/hybrid_scan_executor.h>
#include "backend/catalog/manager.h"
#include "backend/catalog/schema.h"
#include "backend/concurrency/transaction.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/common/timer.h"
#include "backend/executor/abstract_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/index/index_factory.h"
#include "backend/planner/insert_plan.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/data_table.h"
#include "backend/storage/table_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/constant_value_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/conjunction_expression.h"
#include "backend/index/index_factory.h"
namespace peloton {
namespace test {
class HybridIndexTests : public PelotonTest {};
static double projectivity = 1.0;
static int columncount = 4;
static size_t tuples_per_tile_group = 10;
static size_t tile_group = 10;
void CreateTable(std::unique_ptr<storage::DataTable>& hyadapt_table, bool indexes) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const bool is_inlined = true;
// Create schema first
std::vector<catalog::Column> columns;
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto column =
catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"" + std::to_string(col_itr), is_inlined);
columns.push_back(column);
}
catalog::Schema *table_schema = new catalog::Schema(columns);
std::string table_name("HYADAPTTABLE");
/////////////////////////////////////////////////////////
// Create table.
/////////////////////////////////////////////////////////
bool own_schema = true;
bool adapt_table = true;
hyadapt_table.reset(storage::TableFactory::GetDataTable(
INVALID_OID, INVALID_OID, table_schema, table_name,
tuples_per_tile_group, own_schema, adapt_table));
// PRIMARY INDEX
if (indexes == true) {
std::vector<oid_t> key_attrs;
auto tuple_schema = hyadapt_table->GetSchema();
catalog::Schema *key_schema;
index::IndexMetadata *index_metadata;
bool unique;
key_attrs = {0};
key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);
key_schema->SetIndexedColumns(key_attrs);
unique = true;
index_metadata = new index::IndexMetadata(
"primary_index", 123, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique);
index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata);
hyadapt_table->AddIndex(pkey_index);
}
}
void LoadTable(std::unique_ptr<storage::DataTable>& hyadapt_table) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const int tuple_count = tile_group * tuples_per_tile_group;
auto table_schema = hyadapt_table->GetSchema();
/////////////////////////////////////////////////////////
// Load in the data
/////////////////////////////////////////////////////////
// Insert tuples into tile_group.
//auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
const bool allocate = true;
//auto txn = txn_manager.BeginTransaction();
std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM));
int rowid;
for (rowid = 0; rowid < tuple_count; rowid++) {
int populate_value = rowid;
storage::Tuple tuple(table_schema, allocate);
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto value = ValueFactory::GetIntegerValue(populate_value);
tuple.SetValue(col_itr, value, pool.get());
}
ItemPointer tuple_slot_id = hyadapt_table->InsertTuple(&tuple);
assert(tuple_slot_id.block != INVALID_OID);
assert(tuple_slot_id.offset != INVALID_OID);
//txn->RecordInsert(tuple_slot_id);
}
//txn_manager.CommitTransaction();
}
expression::AbstractExpression *CreatePredicate(const int lower_bound) {
// ATTR0 >= LOWER_BOUND
// First, create tuple value expression.
expression::AbstractExpression *tuple_value_expr =
expression::ExpressionUtil::TupleValueFactory(0, 0);
// Second, create constant value expression.
Value constant_value = ValueFactory::GetIntegerValue(lower_bound);
expression::AbstractExpression *constant_value_expr =
expression::ExpressionUtil::ConstantValueFactory(constant_value);
// Finally, link them together using an greater than expression.
expression::AbstractExpression *predicate =
expression::ExpressionUtil::ComparisonFactory(
EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, tuple_value_expr,
constant_value_expr);
return predicate;
}
void GenerateSequence(std::vector<oid_t>& hyadapt_column_ids, oid_t column_count) {
// Reset sequence
hyadapt_column_ids.clear();
// Generate sequence
for (oid_t column_id = 1; column_id <= column_count; column_id++)
hyadapt_column_ids.push_back(column_id);
std::random_shuffle(hyadapt_column_ids.begin(), hyadapt_column_ids.end());
}
void ExecuteTest(executor::AbstractExecutor *executor, size_t tiple_group_counts) {
Timer<> timer;
size_t tuple_counts = 0;
timer.Start();
bool status = false;
status = executor->Init();
if (status == false) throw Exception("Init failed");
std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;
while (executor->Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_tile(
executor->GetOutput());
tuple_counts += result_tile->GetTupleCount();
result_tiles.emplace_back(result_tile.release());
tiple_group_counts--;
}
// Execute stuff
executor->Execute();
timer.Stop();
double time_per_transaction = timer.GetDuration();
LOG_INFO("%f", time_per_transaction);
EXPECT_EQ(tiple_group_counts, 0);
EXPECT_EQ(tuple_counts, tile_group * tuples_per_tile_group);
}
TEST_F(HybridIndexTests, SeqScanTest) {
std::unique_ptr<storage::DataTable> hyadapt_table;
CreateTable(hyadapt_table, false);
//LoadTable(hyadapt_table);
LOG_INFO("%s", hyadapt_table->GetInfo().c_str());
const int lower_bound = 30;
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
/////////////////////////////////////////////////////////
// SEQ SCAN + PREDICATE
/////////////////////////////////////////////////////////
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Column ids to be added to logical tile after scan.
std::vector<oid_t> column_ids;
// oid_t column_count = state.projectivity * state.column_count;
oid_t column_count = projectivity * columncount;
std::vector<oid_t> hyadapt_column_ids;
GenerateSequence(hyadapt_column_ids, column_count);
for (oid_t col_itr = 0; col_itr < column_count; col_itr++) {
column_ids.push_back(hyadapt_column_ids[col_itr]);
}
// Create and set up seq scan executor
auto predicate = nullptr; // CreatePredicate(lower_bound);
planner::HybridScanPlan hybrid_scan_node(hyadapt_table.get(), predicate, column_ids);
executor::HybridScanExecutor Hybrid_scan_executor(&hybrid_scan_node, context.get());
ExecuteTest(&Hybrid_scan_executor, hyadapt_table->hyGetTileGroupCount());
txn_manager.CommitTransaction();
}
} // namespace tet
} // namespace peloton
<commit_msg>update<commit_after>//
// Created by Rui Wang on 16-4-30.
//
#include "gtest/gtest.h"
#include "harness.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <backend/planner/hybrid_scan_plan.h>
#include <backend/executor/hybrid_scan_executor.h>
#include "backend/catalog/manager.h"
#include "backend/catalog/schema.h"
#include "backend/concurrency/transaction.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/common/timer.h"
#include "backend/executor/abstract_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/index/index_factory.h"
#include "backend/planner/insert_plan.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/data_table.h"
#include "backend/storage/table_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/constant_value_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/conjunction_expression.h"
#include "backend/index/index_factory.h"
namespace peloton {
namespace test {
class HybridIndexTests : public PelotonTest {};
static double projectivity = 1.0;
static int columncount = 4;
static size_t tuples_per_tile_group = 10;
static size_t tile_group = 10;
void CreateTable(std::unique_ptr<storage::DataTable>& hyadapt_table, bool indexes) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const bool is_inlined = true;
// Create schema first
std::vector<catalog::Column> columns;
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto column =
catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"" + std::to_string(col_itr), is_inlined);
columns.push_back(column);
}
catalog::Schema *table_schema = new catalog::Schema(columns);
std::string table_name("HYADAPTTABLE");
/////////////////////////////////////////////////////////
// Create table.
/////////////////////////////////////////////////////////
bool own_schema = true;
bool adapt_table = true;
hyadapt_table.reset(storage::TableFactory::GetDataTable(
INVALID_OID, INVALID_OID, table_schema, table_name,
tuples_per_tile_group, own_schema, adapt_table));
// PRIMARY INDEX
if (indexes == true) {
std::vector<oid_t> key_attrs;
auto tuple_schema = hyadapt_table->GetSchema();
catalog::Schema *key_schema;
index::IndexMetadata *index_metadata;
bool unique;
key_attrs = {0};
key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);
key_schema->SetIndexedColumns(key_attrs);
unique = true;
index_metadata = new index::IndexMetadata(
"primary_index", 123, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique);
index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata);
hyadapt_table->AddIndex(pkey_index);
}
}
void LoadTable(std::unique_ptr<storage::DataTable>& hyadapt_table) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const int tuple_count = tile_group * tuples_per_tile_group;
auto table_schema = hyadapt_table->GetSchema();
/////////////////////////////////////////////////////////
// Load in the data
/////////////////////////////////////////////////////////
// Insert tuples into tile_group.
//auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
const bool allocate = true;
//auto txn = txn_manager.BeginTransaction();
std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM));
int rowid;
for (rowid = 0; rowid < tuple_count; rowid++) {
int populate_value = rowid;
storage::Tuple tuple(table_schema, allocate);
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto value = ValueFactory::GetIntegerValue(populate_value);
tuple.SetValue(col_itr, value, pool.get());
}
ItemPointer tuple_slot_id = hyadapt_table->InsertTuple(&tuple);
assert(tuple_slot_id.block != INVALID_OID);
assert(tuple_slot_id.offset != INVALID_OID);
//txn->RecordInsert(tuple_slot_id);
}
//txn_manager.CommitTransaction();
}
expression::AbstractExpression *CreatePredicate(const int lower_bound) {
// ATTR0 >= LOWER_BOUND
// First, create tuple value expression.
expression::AbstractExpression *tuple_value_expr =
expression::ExpressionUtil::TupleValueFactory(0, 0);
// Second, create constant value expression.
Value constant_value = ValueFactory::GetIntegerValue(lower_bound);
expression::AbstractExpression *constant_value_expr =
expression::ExpressionUtil::ConstantValueFactory(constant_value);
// Finally, link them together using an greater than expression.
expression::AbstractExpression *predicate =
expression::ExpressionUtil::ComparisonFactory(
EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, tuple_value_expr,
constant_value_expr);
return predicate;
}
void GenerateSequence(std::vector<oid_t>& hyadapt_column_ids, oid_t column_count) {
// Reset sequence
hyadapt_column_ids.clear();
// Generate sequence
for (oid_t column_id = 0; column_id < column_count; column_id++)
hyadapt_column_ids.push_back(column_id);
// std::random_shuffle(hyadapt_column_ids.begin(), hyadapt_column_ids.end());
}
void ExecuteTest(executor::AbstractExecutor *executor, size_t tiple_group_counts) {
Timer<> timer;
size_t tuple_counts = 0;
timer.Start();
bool status = false;
status = executor->Init();
if (status == false) throw Exception("Init failed");
std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;
while (executor->Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_tile(
executor->GetOutput());
tuple_counts += result_tile->GetTupleCount();
result_tiles.emplace_back(result_tile.release());
tiple_group_counts--;
}
// Execute stuff
executor->Execute();
timer.Stop();
double time_per_transaction = timer.GetDuration();
LOG_INFO("%f", time_per_transaction);
EXPECT_EQ(tiple_group_counts, 0);
EXPECT_EQ(tuple_counts, tile_group * tuples_per_tile_group);
}
TEST_F(HybridIndexTests, SeqScanTest) {
std::unique_ptr<storage::DataTable> hyadapt_table;
CreateTable(hyadapt_table, false);
//LoadTable(hyadapt_table);
LOG_INFO("%s", hyadapt_table->GetInfo().c_str());
const int lower_bound = 30;
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
/////////////////////////////////////////////////////////
// SEQ SCAN + PREDICATE
/////////////////////////////////////////////////////////
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Column ids to be added to logical tile after scan.
std::vector<oid_t> column_ids;
// oid_t column_count = state.projectivity * state.column_count;
oid_t column_count = projectivity * columncount;
std::vector<oid_t> hyadapt_column_ids;
GenerateSequence(hyadapt_column_ids, column_count);
for (oid_t col_itr = 0; col_itr < column_count; col_itr++) {
column_ids.push_back(hyadapt_column_ids[col_itr]);
}
// Create and set up seq scan executor
auto predicate = nullptr; // CreatePredicate(lower_bound);
planner::HybridScanPlan hybrid_scan_node(hyadapt_table.get(), predicate, column_ids);
executor::HybridScanExecutor Hybrid_scan_executor(&hybrid_scan_node, context.get());
ExecuteTest(&Hybrid_scan_executor, hyadapt_table->hyGetTileGroupCount());
txn_manager.CommitTransaction();
}
} // namespace tet
} // namespace peloton
<|endoftext|> |
<commit_before>// Copyright 2015-2016 Ansersion
//
// 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 "myRegex.h"
#include <stdio.h>
#include <stdlib.h>
const int MyRegex::REGEX_FAILURE = 0;
const int MyRegex::REGEX_SUCCESS = 1;
const int REG_NOERROR = 0;
MyRegex::MyRegex():
pReg(NULL), pMatch(NULL), NextPos(string::npos), LastStr(NULL)
{
memset(RegexBuf, 0, REGEX_BUF_SIZE);
}
MyRegex::~MyRegex()
{
if(pReg) delete pReg;
if(pMatch) delete pMatch;
}
int MyRegex::Regex(const char * str, const char * pattern, list<string> * groups, bool ignore_case)
{
if(!str) return REGEX_FAILURE;
if(!pattern) return REGEX_FAILURE;
if(!groups) return REGEX_FAILURE;
string StrPattern(pattern);
char ErrBuf[1024]; // use "1024" at random
int GroupNum = 0;
string::size_type GroupPos = 0;
GroupNum++; // the whole pattern is the 'first group'
while((GroupPos = StrPattern.find("(", GroupPos)) != string::npos) GroupNum++, GroupPos++;
while((GroupPos = StrPattern.find("\\(", GroupPos)) != string::npos) GroupNum--, GroupPos++;
if(GroupNum < 0) {
printf("REGEX INTERNAL PANIC, NEED DEBUGING(Regex)");
return REGEX_FAILURE;
}
pReg = (regex_t *)calloc(1, sizeof(regex_t));
pMatch = (regmatch_t *)calloc(GroupNum, sizeof(regmatch_t));
int RegFlags = REG_EXTENDED;
ignore_case && (RegFlags |= REG_ICASE);
int ErrNo = regcomp(pReg, pattern, REG_EXTENDED);
if(ErrNo != 0) {
regerror(ErrNo, pReg, ErrBuf, sizeof(ErrBuf));
printf("Regex Error: %s\n", ErrBuf);
return REGEX_FAILURE;
}
ErrNo = regexec(pReg, str, GroupNum, pMatch, 0);
if(ErrNo != REG_NOERROR) {
regfree(pReg);free(pReg);free(pMatch);
pReg = NULL; pMatch = NULL;
return REGEX_FAILURE;
}
groups->clear();
// printf("GroupNum: %d\n", GroupNum); //###Debug###//
for(int i = 0; i < GroupNum; i++) {
const char * pStr;
if((pStr = Substr(str, pMatch[i].rm_so, pMatch[i].rm_eo)) != NULL) {
groups->push_back(pStr);
}
}
regfree(pReg);free(pReg);free(pMatch);
pReg = NULL; pMatch = NULL;
return REGEX_SUCCESS;
}
int MyRegex::Regex(const char * str, const char * pattern, bool ignore_case)
{
list<string> tmp;
return Regex(str, pattern, &tmp, ignore_case);
}
int MyRegex::RegexLine(string * str, string * pattern, list<string> * groups, bool ignore_case)
{
const int EndOfString = 0;
const int StillInString = 1;
string::size_type TmpPos = 0;
string MatchedLine("");
if(LastStr != str) {
LastStr = str;
NextPos = 0;
}
if(string::npos == NextPos) return EndOfString;
if(!LastStr || !pattern || !groups) return EndOfString;
TmpPos = LastStr->find("\r\n", NextPos);
if(string::npos == TmpPos) TmpPos = LastStr->find("\n", NextPos);
groups->clear();
if(TmpPos != string::npos) {
MatchedLine.assign(LastStr->substr(NextPos, TmpPos - NextPos));
NextPos = ++TmpPos;
} else {
MatchedLine.assign(LastStr->substr(NextPos));
NextPos = string::npos;
}
if(!Regex(MatchedLine.c_str(), pattern->c_str(), groups, ignore_case)) {
groups->clear();
} else {
groups->push_front(MatchedLine);
}
return StillInString;
}
int MyRegex::RegexLine(string * str, string * pattern, bool ignore_case)
{
list<string> tmp;
return RegexLine(str, pattern, &tmp, ignore_case);
}
/********************/
/* proteced method */
const char * MyRegex::Substr(const char * str, int pos1, int pos2)
{
if(!str) return NULL;
// printf("%d:%d\n", pos1, pos2); //###Debug###//
int Len = strlen(str);
int SubLen = pos2 - pos1;
if(pos1 >= 0 && pos1 <= Len &&
pos2 >= 0 && pos2 <= Len &&
SubLen >= 0 && SubLen < REGEX_BUF_SIZE) {
strncpy(RegexBuf, &str[pos1], SubLen);
RegexBuf[SubLen] = '\0';
return RegexBuf;
} else {
return NULL;
}
}
<commit_msg>fixed REG_NOERROR problem<commit_after>// Copyright 2015-2016 Ansersion
//
// 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 "myRegex.h"
#include <stdio.h>
#include <stdlib.h>
const int MyRegex::REGEX_FAILURE = 0;
const int MyRegex::REGEX_SUCCESS = 1;
const int REG_NOERROR = 0;
MyRegex::MyRegex():
pReg(NULL), pMatch(NULL), NextPos(string::npos), LastStr(NULL)
{
memset(RegexBuf, 0, REGEX_BUF_SIZE);
}
MyRegex::~MyRegex()
{
if(pReg) delete pReg;
if(pMatch) delete pMatch;
}
int MyRegex::Regex(const char * str, const char * pattern, list<string> * groups, bool ignore_case)
{
if(!str) return REGEX_FAILURE;
if(!pattern) return REGEX_FAILURE;
if(!groups) return REGEX_FAILURE;
string StrPattern(pattern);
char ErrBuf[1024]; // use "1024" at random
int GroupNum = 0;
string::size_type GroupPos = 0;
GroupNum++; // the whole pattern is the 'first group'
while((GroupPos = StrPattern.find("(", GroupPos)) != string::npos) GroupNum++, GroupPos++;
while((GroupPos = StrPattern.find("\\(", GroupPos)) != string::npos) GroupNum--, GroupPos++;
if(GroupNum < 0) {
printf("REGEX INTERNAL PANIC, NEED DEBUGING(Regex)");
return REGEX_FAILURE;
}
pReg = (regex_t *)calloc(1, sizeof(regex_t));
pMatch = (regmatch_t *)calloc(GroupNum, sizeof(regmatch_t));
int RegFlags = REG_EXTENDED;
ignore_case && (RegFlags |= REG_ICASE);
int ErrNo = regcomp(pReg, pattern, REG_EXTENDED);
if(ErrNo != 0) {
regerror(ErrNo, pReg, ErrBuf, sizeof(ErrBuf));
printf("Regex Error: %s\n", ErrBuf);
return REGEX_FAILURE;
}
ErrNo = regexec(pReg, str, GroupNum, pMatch, 0);
if(ErrNo != 0) { //REG_NOERROR is problematic in many systems
regfree(pReg);free(pReg);free(pMatch);
pReg = NULL; pMatch = NULL;
return REGEX_FAILURE;
}
groups->clear();
// printf("GroupNum: %d\n", GroupNum); //###Debug###//
for(int i = 0; i < GroupNum; i++) {
const char * pStr;
if((pStr = Substr(str, pMatch[i].rm_so, pMatch[i].rm_eo)) != NULL) {
groups->push_back(pStr);
}
}
regfree(pReg);free(pReg);free(pMatch);
pReg = NULL; pMatch = NULL;
return REGEX_SUCCESS;
}
int MyRegex::Regex(const char * str, const char * pattern, bool ignore_case)
{
list<string> tmp;
return Regex(str, pattern, &tmp, ignore_case);
}
int MyRegex::RegexLine(string * str, string * pattern, list<string> * groups, bool ignore_case)
{
const int EndOfString = 0;
const int StillInString = 1;
string::size_type TmpPos = 0;
string MatchedLine("");
if(LastStr != str) {
LastStr = str;
NextPos = 0;
}
if(string::npos == NextPos) return EndOfString;
if(!LastStr || !pattern || !groups) return EndOfString;
TmpPos = LastStr->find("\r\n", NextPos);
if(string::npos == TmpPos) TmpPos = LastStr->find("\n", NextPos);
groups->clear();
if(TmpPos != string::npos) {
MatchedLine.assign(LastStr->substr(NextPos, TmpPos - NextPos));
NextPos = ++TmpPos;
} else {
MatchedLine.assign(LastStr->substr(NextPos));
NextPos = string::npos;
}
if(!Regex(MatchedLine.c_str(), pattern->c_str(), groups, ignore_case)) {
groups->clear();
} else {
groups->push_front(MatchedLine);
}
return StillInString;
}
int MyRegex::RegexLine(string * str, string * pattern, bool ignore_case)
{
list<string> tmp;
return RegexLine(str, pattern, &tmp, ignore_case);
}
/********************/
/* proteced method */
const char * MyRegex::Substr(const char * str, int pos1, int pos2)
{
if(!str) return NULL;
// printf("%d:%d\n", pos1, pos2); //###Debug###//
int Len = strlen(str);
int SubLen = pos2 - pos1;
if(pos1 >= 0 && pos1 <= Len &&
pos2 >= 0 && pos2 <= Len &&
SubLen >= 0 && SubLen < REGEX_BUF_SIZE) {
strncpy(RegexBuf, &str[pos1], SubLen);
RegexBuf[SubLen] = '\0';
return RegexBuf;
} else {
return NULL;
}
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "Instruction.hpp"
class LedController
{
public:
void runProgram(const Instructions &)
{
}
};
TEST(LedControllerTest, ShouldCreate)
{
LedController controller;
controller.runProgram(Instructions{});
}<commit_msg>LedController can print led<commit_after>#include "gmock/gmock.h"
#include <sstream>
#include "Instruction.hpp"
class LedController
{
public:
explicit LedController(std::ostream &stream) :
out{stream}
{
}
void runProgram(const Instructions &)
{
out << "........\n";
}
private:
std::ostream &out;
};
static constexpr Instruction createInstructionWithZeroValue(InstructionType type)
{
return{type, 0};
}
using namespace ::testing;
TEST(LedControllerTest, OutInstructionShouldPrintLedState)
{
std::stringstream stream;
LedController controller{stream};
controller.runProgram(Instructions{createInstructionWithZeroValue(InstructionType::OutA)});
EXPECT_THAT(stream.str(), Eq("........\n"));
}<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/glue/plugins/test/plugin_private_test.h"
#include "base/basictypes.h"
#include "base/string_util.h"
#include "webkit/glue/plugins/test/plugin_client.h"
namespace NPAPIClient {
PrivateTest::PrivateTest(NPP id, NPNetscapeFuncs *host_functions)
: PluginTest(id, host_functions) {
}
NPError PrivateTest::New(uint16 mode, int16 argc,
const char* argn[], const char* argv[],
NPSavedData* saved) {
PluginTest::New(mode, argc, argn, argv, saved);
NPBool private_mode = 0;
NPNetscapeFuncs* browser = NPAPIClient::PluginClient::HostFunctions();
NPError result = browser->getvalue(
id(), NPNVprivateModeBool, &private_mode);
if (result != NPERR_NO_ERROR) {
SetError("Failed to read NPNVprivateModeBool value.");
} else {
NPIdentifier location = HostFunctions()->getstringidentifier("location");
NPIdentifier href = HostFunctions()->getstringidentifier("href");
NPObject *window_obj = NULL;
HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj);
NPVariant location_var;
HostFunctions()->getproperty(id(), window_obj, location, &location_var);
NPVariant href_var;
HostFunctions()->getproperty(id(), NPVARIANT_TO_OBJECT(location_var), href,
&href_var);
std::string href_str(href_var.value.stringValue.UTF8Characters,
href_var.value.stringValue.UTF8Length);
bool private_expected = href_str.find("?private") != href_str.npos;
if (private_mode != private_expected)
SetError("NPNVprivateModeBool returned incorrect value.");
HostFunctions()->releasevariantvalue(&href_var);
HostFunctions()->releasevariantvalue(&location_var);
HostFunctions()->releaseobject(window_obj);
}
SignalTestCompleted();
return NPERR_NO_ERROR;
}
} // namespace NPAPIClient
<commit_msg>Revert r20046. Review URL: http://codereview.chromium.org/149264<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/glue/plugins/test/plugin_private_test.h"
#include "base/basictypes.h"
#include "base/string_util.h"
#include "webkit/glue/plugins/test/plugin_client.h"
namespace NPAPIClient {
PrivateTest::PrivateTest(NPP id, NPNetscapeFuncs *host_functions)
: PluginTest(id, host_functions) {
}
NPError PrivateTest::New(uint16 mode, int16 argc,
const char* argn[], const char* argv[],
NPSavedData* saved) {
PluginTest::New(mode, argc, argn, argv, saved);
NPBool private_mode = 0;
NPNetscapeFuncs* browser = NPAPIClient::PluginClient::HostFunctions();
NPError result = browser->getvalue(
id(), NPNVprivateModeBool, &private_mode);
if (result != NPERR_NO_ERROR) {
SetError("Failed to read NPNVprivateModeBool value.");
} else {
NPIdentifier location = HostFunctions()->getstringidentifier("location");
NPIdentifier href = HostFunctions()->getstringidentifier("href");
NPObject *window_obj = NULL;
HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj);
NPVariant location_var;
HostFunctions()->getproperty(id(), window_obj, location, &location_var);
NPVariant href_var;
HostFunctions()->getproperty(id(), NPVARIANT_TO_OBJECT(location_var), href,
&href_var);
std::string href_str(href_var.value.stringValue.UTF8Characters,
href_var.value.stringValue.UTF8Length);
bool private_expected = href_str.find("?private") != href_str.npos;
if (private_expected != private_expected)
SetError("NPNVprivateModeBool returned incorrect value.");
HostFunctions()->releasevariantvalue(&href_var);
HostFunctions()->releasevariantvalue(&location_var);
HostFunctions()->releaseobject(window_obj);
}
SignalTestCompleted();
return NPERR_NO_ERROR;
}
} // namespace NPAPIClient
<|endoftext|> |
<commit_before>#include "ContextCairo.h"
#include <cassert>
#include <cmath>
#include <iostream>
using namespace canvas;
using namespace std;
static cairo_format_t getCairoFormat(InternalFormat format) {
switch (format) {
case R8: return CAIRO_FORMAT_A8;
case RGB565: return CAIRO_FORMAT_RGB16_565;
case RGBA8: return CAIRO_FORMAT_ARGB32;
case RGB8: return CAIRO_FORMAT_RGB24;
default:
assert(0);
return CAIRO_FORMAT_ARGB32;
}
}
static InternalFormat getInternalFormat(const ImageFormat & f) {
if (f == ImageFormat::LUM8) {
return R8;
} else if (f == ImageFormat::RGB32 || f == ImageFormat::RGB24) {
return RGB8;
} else if (f == ImageFormat::RGBA32) {
return RGBA8;
} else {
cerr << "unhandled ImageFormat: bpp = " << f.getBytesPerPixel() << ", c = " << f.getNumChannels() << endl;
assert(0);
return RGBA8;
}
}
CairoSurface::CairoSurface(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, const InternalFormat & _image_format)
: Surface(_logical_width, _logical_height, _actual_width, _actual_height, _image_format) {
if (_actual_width && _actual_height) {
surface = cairo_image_surface_create(getCairoFormat(_image_format), _actual_width, _actual_height);
assert(surface);
} else {
surface = 0;
}
}
CairoSurface::CairoSurface(const Image & image)
: Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), getInternalFormat(image.getFormat()))
{
cairo_format_t format = getCairoFormat(getFormat());
unsigned int stride = cairo_format_stride_for_width(format, getActualWidth());
assert(stride == 4 * getActualWidth());
size_t numPixels = getActualWidth() * getActualHeight();
storage = new unsigned int[numPixels];
const unsigned char * data = image.getData();
if (image.getFormat().getBytesPerPixel() == 4) {
memcpy(storage, data, numPixels * 4);
} else if (image.getFormat().getBytesPerPixel() == 1) {
memcpy(storage, data, numPixels);
} else if (image.getFormat().hasAlpha()) {
for (unsigned int i = 0; i < numPixels; i++) {
storage[i] = (data[4 * i + 0]) + (data[4 * i + 1] << 8) + (data[4 * i + 2] << 16) + (data[4 * i + 3] << 24);
}
} else {
for (unsigned int i = 0; i < numPixels; i++) {
storage[i] = data[3 * i + 2] + (data[3 * i + 1] << 8) + (data[3 * i + 0] << 16);
}
}
surface = cairo_image_surface_create_for_data((unsigned char*)storage,
format,
getActualWidth(),
getActualHeight(),
stride);
assert(surface);
}
CairoSurface::CairoSurface(const std::string & filename) : Surface(0, 0, 0, 0, RGBA8) {
surface = cairo_image_surface_create_from_png(filename.c_str());
assert(surface);
unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
bool a = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32;
Surface::resize(w, h, w, h, a ? RGBA8 : RGB8);
}
struct read_buffer_s {
size_t offset, size;
const unsigned char * data;
};
static cairo_status_t read_buffer(void *closure, unsigned char *data, unsigned int length)
{
read_buffer_s * buf = (read_buffer_s*)closure;
if (buf->offset + length > buf->size) {
return CAIRO_STATUS_READ_ERROR;
}
memcpy(data, buf->data + buf->offset, length);
buf->offset += length;
return CAIRO_STATUS_SUCCESS;
}
CairoSurface::CairoSurface(const unsigned char * buffer, size_t size) : Surface(16, 16, 16, 16, RGBA8) {
read_buffer_s buf = { 0, size, buffer };
if (isPNG(buffer, size)) {
surface = cairo_image_surface_create_from_png_stream(read_buffer, &buf);
unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
bool a = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32;
Surface::resize(w, h, w, h, a ? RGBA8 : RGB8);
} else {
cerr << "failed to load image from memory\n";
surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, getActualWidth(), getActualHeight());
}
assert(surface);
}
CairoSurface::~CairoSurface() {
if (cr) {
cairo_destroy(cr);
}
if (surface) {
cairo_surface_destroy(surface);
}
delete[] storage;
}
void
CairoSurface::flush() {
cairo_surface_flush(surface);
}
void
CairoSurface::markDirty() {
cairo_surface_mark_dirty(surface);
}
void
CairoSurface::resize(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, InternalFormat _format) {
Surface::resize(_logical_width, _logical_height, _actual_width, _actual_height, _format);
if (cr) {
cairo_destroy(cr);
cr = 0;
}
if (surface) cairo_surface_destroy(surface);
surface = cairo_image_surface_create(getCairoFormat(getFormat()), _actual_width, _actual_height);
assert(surface);
}
void
CairoSurface::sendPath(const Path & path) {
initializeContext();
cairo_new_path(cr);
for (auto pc : path.getData()) {
switch (pc.type) {
case PathComponent::MOVE_TO: cairo_move_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
case PathComponent::LINE_TO: cairo_line_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
case PathComponent::CLOSE: cairo_close_path(cr); break;
case PathComponent::ARC:
if (!pc.anticlockwise) {
cairo_arc(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
} else {
cairo_arc_negative(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
}
break;
}
}
}
void
CairoSurface::clip(const Path & path, float display_scale) {
sendPath(path);
cairo_clip(cr);
}
void
CairoSurface::resetClip() {
if (cr) cairo_reset_clip(cr);
}
void
CairoSurface::renderPath(RenderMode mode, const Path & path, const Style & style, float lineWidth, Operator op, float display_scale, float globalAlpha, float sadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor) {
initializeContext();
switch (op) {
case SOURCE_OVER: cairo_set_operator(cr, CAIRO_OPERATOR_OVER); break;
case COPY: cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); break;
}
cairo_pattern_t * pat = 0;
if (style.getType() == Style::LINEAR_GRADIENT) {
pat = cairo_pattern_create_linear(style.x0 * display_scale, style.y0 * display_scale, style.x1 * display_scale, style.y1 * display_scale);
for (map<float, Color>::const_iterator it = style.getColors().begin(); it != style.getColors().end(); it++) {
cairo_pattern_add_color_stop_rgba(pat, it->first, it->second.red, it->second.green, it->second.blue, it->second.alpha * globalAlpha);
}
cairo_set_source(cr, pat);
} else if (style.getType() == Style::FILTER) {
double min_x, min_y, max_x, max_y;
path.getExtents(min_x, min_y, max_x, max_y);
} else {
cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha * globalAlpha);
}
sendPath(path);
switch (mode) {
case STROKE:
cairo_set_line_width(cr, lineWidth * display_scale);
// cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke(cr);
break;
case FILL:
cairo_fill(cr);
break;
}
if (pat) {
cairo_pattern_destroy(pat);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
}
}
void
CairoSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, Operator op, float display_scale, float alpha, float shadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor) {
initializeContext();
switch (op) {
case SOURCE_OVER: cairo_set_operator(cr, CAIRO_OPERATOR_OVER); break;
case COPY: cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); break;
}
cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha * alpha);
cairo_select_font_face(cr, font.family.c_str(),
font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, font.size * display_scale);
x *= display_scale;
y *= display_scale;
if (textBaseline.getType() == TextBaseline::MIDDLE || textBaseline.getType() == TextBaseline::TOP) {
cairo_font_extents_t font_extents;
cairo_font_extents(cr, &font_extents);
switch (textBaseline.getType()) {
// case TextBaseline::MIDDLE: y -= (extents.height/2 + extents.y_bearing); break;
case TextBaseline::MIDDLE: y += -font_extents.descent + (font_extents.ascent + font_extents.descent) / 2.0; break;
case TextBaseline::TOP: y += font_extents.ascent; break;
default: break;
}
}
if (textAlign.getType() != TextAlign::LEFT) {
cairo_text_extents_t text_extents;
cairo_text_extents(cr, text.c_str(), &text_extents);
switch (textAlign.getType()) {
case TextAlign::LEFT: break;
case TextAlign::CENTER: x -= text_extents.width / 2; break;
case TextAlign::RIGHT: x -= text_extents.width; break;
default: break;
}
}
cairo_move_to(cr, x + 0.5, y + 0.5);
switch (mode) {
case STROKE:
cairo_set_line_width(cr, lineWidth);
cairo_text_path(cr, text.c_str());
cairo_stroke(cr);
break;
case FILL:
cairo_show_text(cr, text.c_str());
break;
}
}
TextMetrics
CairoSurface::measureText(const Font & font, const std::string & text, float display_scale) {
initializeContext();
cairo_select_font_face(cr, font.family.c_str(),
font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, font.size * display_scale);
cairo_text_extents_t te;
cairo_text_extents(cr, text.c_str(), &te);
return TextMetrics((float)te.width / display_scale); //, (float)te.height);
}
void
CairoSurface::drawNativeSurface(CairoSurface & img, double x, double y, double w, double h, float globalAlpha, bool imageSmoothingEnabled) {
initializeContext();
double sx = w / img.getActualWidth(), sy = h / img.getActualHeight();
cairo_save(cr);
cairo_scale(cr, sx, sy);
cairo_set_source_surface(cr, img.surface, (x / sx) + 0.5, (y / sy) + 0.5);
cairo_pattern_set_filter(cairo_get_source(cr), imageSmoothingEnabled ? CAIRO_FILTER_BEST : CAIRO_FILTER_NEAREST);
if (globalAlpha < 1.0f) {
cairo_paint_with_alpha(cr, globalAlpha);
} else {
cairo_paint(cr);
}
cairo_set_source_rgb(cr, 0.0f, 0.0f, 0.0f); // is this needed?
cairo_restore(cr);
}
void
CairoSurface::drawImage(Surface & _img, double x, double y, double w, double h, float displayScale, float globalAlpha, float shadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor, bool imageSmoothingEnabled) {
CairoSurface * cs_ptr = dynamic_cast<CairoSurface*>(&_img);
if (cs_ptr) {
drawNativeSurface(*cs_ptr, x, y, w, h, globalAlpha, imageSmoothingEnabled);
} else {
auto img = _img.createImage();
CairoSurface cs(*img);
drawNativeSurface(cs, x, y, w, h, globalAlpha, imageSmoothingEnabled);
}
}
void
CairoSurface::drawImage(const Image & _img, double x, double y, double w, double h, float displayScale, float globalAlpha, float shadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor, bool imageSmoothingEnabled) {
CairoSurface img(_img);
drawNativeSurface(img, x, y, w, h, globalAlpha, imageSmoothingEnabled);
}
void
CairoSurface::save() {
initializeContext();
cairo_save(cr);
}
void
CairoSurface::restore() {
initializeContext();
cairo_restore(cr);
}
<commit_msg>remove clip, resetClip, save, restore, implement clipping in render methods<commit_after>#include "ContextCairo.h"
#include <cassert>
#include <cmath>
#include <iostream>
using namespace canvas;
using namespace std;
static cairo_format_t getCairoFormat(InternalFormat format) {
switch (format) {
case R8: return CAIRO_FORMAT_A8;
case RGB565: return CAIRO_FORMAT_RGB16_565;
case RGBA8: return CAIRO_FORMAT_ARGB32;
case RGB8: return CAIRO_FORMAT_RGB24;
default:
assert(0);
return CAIRO_FORMAT_ARGB32;
}
}
static InternalFormat getInternalFormat(const ImageFormat & f) {
if (f == ImageFormat::LUM8) {
return R8;
} else if (f == ImageFormat::RGB32 || f == ImageFormat::RGB24) {
return RGB8;
} else if (f == ImageFormat::RGBA32) {
return RGBA8;
} else {
cerr << "unhandled ImageFormat: bpp = " << f.getBytesPerPixel() << ", c = " << f.getNumChannels() << endl;
assert(0);
return RGBA8;
}
}
CairoSurface::CairoSurface(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, const InternalFormat & _image_format)
: Surface(_logical_width, _logical_height, _actual_width, _actual_height, _image_format) {
if (_actual_width && _actual_height) {
surface = cairo_image_surface_create(getCairoFormat(_image_format), _actual_width, _actual_height);
assert(surface);
} else {
surface = 0;
}
}
CairoSurface::CairoSurface(const Image & image)
: Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), getInternalFormat(image.getFormat()))
{
cairo_format_t format = getCairoFormat(getFormat());
unsigned int stride = cairo_format_stride_for_width(format, getActualWidth());
assert(stride == 4 * getActualWidth());
size_t numPixels = getActualWidth() * getActualHeight();
storage = new unsigned int[numPixels];
const unsigned char * data = image.getData();
if (image.getFormat().getBytesPerPixel() == 4) {
memcpy(storage, data, numPixels * 4);
} else if (image.getFormat().getBytesPerPixel() == 1) {
memcpy(storage, data, numPixels);
} else if (image.getFormat().hasAlpha()) {
for (unsigned int i = 0; i < numPixels; i++) {
storage[i] = (data[4 * i + 0]) + (data[4 * i + 1] << 8) + (data[4 * i + 2] << 16) + (data[4 * i + 3] << 24);
}
} else {
for (unsigned int i = 0; i < numPixels; i++) {
storage[i] = data[3 * i + 2] + (data[3 * i + 1] << 8) + (data[3 * i + 0] << 16);
}
}
surface = cairo_image_surface_create_for_data((unsigned char*)storage,
format,
getActualWidth(),
getActualHeight(),
stride);
assert(surface);
}
CairoSurface::CairoSurface(const std::string & filename) : Surface(0, 0, 0, 0, RGBA8) {
surface = cairo_image_surface_create_from_png(filename.c_str());
assert(surface);
unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
bool a = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32;
Surface::resize(w, h, w, h, a ? RGBA8 : RGB8);
}
struct read_buffer_s {
size_t offset, size;
const unsigned char * data;
};
static cairo_status_t read_buffer(void *closure, unsigned char *data, unsigned int length)
{
read_buffer_s * buf = (read_buffer_s*)closure;
if (buf->offset + length > buf->size) {
return CAIRO_STATUS_READ_ERROR;
}
memcpy(data, buf->data + buf->offset, length);
buf->offset += length;
return CAIRO_STATUS_SUCCESS;
}
CairoSurface::CairoSurface(const unsigned char * buffer, size_t size) : Surface(16, 16, 16, 16, RGBA8) {
read_buffer_s buf = { 0, size, buffer };
if (isPNG(buffer, size)) {
surface = cairo_image_surface_create_from_png_stream(read_buffer, &buf);
unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
bool a = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32;
Surface::resize(w, h, w, h, a ? RGBA8 : RGB8);
} else {
cerr << "failed to load image from memory\n";
surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, getActualWidth(), getActualHeight());
}
assert(surface);
}
CairoSurface::~CairoSurface() {
if (cr) {
cairo_destroy(cr);
}
if (surface) {
cairo_surface_destroy(surface);
}
delete[] storage;
}
void
CairoSurface::flush() {
cairo_surface_flush(surface);
}
void
CairoSurface::markDirty() {
cairo_surface_mark_dirty(surface);
}
void
CairoSurface::resize(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, InternalFormat _format) {
Surface::resize(_logical_width, _logical_height, _actual_width, _actual_height, _format);
if (cr) {
cairo_destroy(cr);
cr = 0;
}
if (surface) cairo_surface_destroy(surface);
surface = cairo_image_surface_create(getCairoFormat(getFormat()), _actual_width, _actual_height);
assert(surface);
}
void
CairoSurface::sendPath(const Path & path) {
initializeContext();
cairo_new_path(cr);
for (auto pc : path.getData()) {
switch (pc.type) {
case PathComponent::MOVE_TO: cairo_move_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
case PathComponent::LINE_TO: cairo_line_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
case PathComponent::CLOSE: cairo_close_path(cr); break;
case PathComponent::ARC:
if (!pc.anticlockwise) {
cairo_arc(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
} else {
cairo_arc_negative(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
}
break;
}
}
}
void
CairoSurface::renderPath(RenderMode mode, const Path & path, const Style & style, float lineWidth, Operator op, float display_scale, float globalAlpha, float sadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor, const Path & clipPath) {
initializeContext();
if (!clipPath.empty()) {
sendPath(clipPath);
cairo_clip(cr);
}
switch (op) {
case SOURCE_OVER: cairo_set_operator(cr, CAIRO_OPERATOR_OVER); break;
case COPY: cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); break;
}
cairo_pattern_t * pat = 0;
if (style.getType() == Style::LINEAR_GRADIENT) {
pat = cairo_pattern_create_linear(style.x0 * display_scale, style.y0 * display_scale, style.x1 * display_scale, style.y1 * display_scale);
for (map<float, Color>::const_iterator it = style.getColors().begin(); it != style.getColors().end(); it++) {
cairo_pattern_add_color_stop_rgba(pat, it->first, it->second.red, it->second.green, it->second.blue, it->second.alpha * globalAlpha);
}
cairo_set_source(cr, pat);
} else if (style.getType() == Style::FILTER) {
double min_x, min_y, max_x, max_y;
path.getExtents(min_x, min_y, max_x, max_y);
} else {
cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha * globalAlpha);
}
sendPath(path);
switch (mode) {
case STROKE:
cairo_set_line_width(cr, lineWidth * display_scale);
// cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke(cr);
break;
case FILL:
cairo_fill(cr);
break;
}
if (pat) {
cairo_pattern_destroy(pat);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
}
if (!clipPath.empty()) {
cairo_reset_clip(cr);
}
}
void
CairoSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, Operator op, float display_scale, float alpha, float shadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor, const Path & clipPath) {
initializeContext();
if (!clipPath.empty()) {
sendPath(clipPath);
cairo_clip(cr);
}
switch (op) {
case SOURCE_OVER: cairo_set_operator(cr, CAIRO_OPERATOR_OVER); break;
case COPY: cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); break;
}
cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha * alpha);
cairo_select_font_face(cr, font.family.c_str(),
font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, font.size * display_scale);
x *= display_scale;
y *= display_scale;
if (textBaseline.getType() == TextBaseline::MIDDLE || textBaseline.getType() == TextBaseline::TOP) {
cairo_font_extents_t font_extents;
cairo_font_extents(cr, &font_extents);
switch (textBaseline.getType()) {
// case TextBaseline::MIDDLE: y -= (extents.height/2 + extents.y_bearing); break;
case TextBaseline::MIDDLE: y += -font_extents.descent + (font_extents.ascent + font_extents.descent) / 2.0; break;
case TextBaseline::TOP: y += font_extents.ascent; break;
default: break;
}
}
if (textAlign.getType() != TextAlign::LEFT) {
cairo_text_extents_t text_extents;
cairo_text_extents(cr, text.c_str(), &text_extents);
switch (textAlign.getType()) {
case TextAlign::LEFT: break;
case TextAlign::CENTER: x -= text_extents.width / 2; break;
case TextAlign::RIGHT: x -= text_extents.width; break;
default: break;
}
}
cairo_move_to(cr, x + 0.5, y + 0.5);
switch (mode) {
case STROKE:
cairo_set_line_width(cr, lineWidth);
cairo_text_path(cr, text.c_str());
cairo_stroke(cr);
break;
case FILL:
cairo_show_text(cr, text.c_str());
break;
}
if (!clipPath.empty()) {
cairo_reset_clip(cr);
}
}
TextMetrics
CairoSurface::measureText(const Font & font, const std::string & text, float display_scale) {
initializeContext();
cairo_select_font_face(cr, font.family.c_str(),
font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, font.size * display_scale);
cairo_text_extents_t te;
cairo_text_extents(cr, text.c_str(), &te);
return TextMetrics((float)te.width / display_scale); //, (float)te.height);
}
void
CairoSurface::drawNativeSurface(CairoSurface & img, double x, double y, double w, double h, float globalAlpha, const Path & clipPath, bool imageSmoothingEnabled) {
initializeContext();
if (!clipPath.empty()) {
sendPath(clipPath);
cairo_clip(cr);
}
double sx = w / img.getActualWidth(), sy = h / img.getActualHeight();
cairo_save(cr);
cairo_scale(cr, sx, sy);
cairo_set_source_surface(cr, img.surface, (x / sx) + 0.5, (y / sy) + 0.5);
cairo_pattern_set_filter(cairo_get_source(cr), imageSmoothingEnabled ? CAIRO_FILTER_BEST : CAIRO_FILTER_NEAREST);
if (globalAlpha < 1.0f) {
cairo_paint_with_alpha(cr, globalAlpha);
} else {
cairo_paint(cr);
}
cairo_set_source_rgb(cr, 0.0f, 0.0f, 0.0f); // is this needed?
cairo_restore(cr);
if (!clipPath.empty()) {
cairo_reset_clip(cr);
}
}
void
CairoSurface::drawImage(Surface & _img, double x, double y, double w, double h, float displayScale, float globalAlpha, float shadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor, const Path & clipPath, bool imageSmoothingEnabled) {
CairoSurface * cs_ptr = dynamic_cast<CairoSurface*>(&_img);
if (cs_ptr) {
drawNativeSurface(*cs_ptr, x, y, w, h, globalAlpha, clipPath, imageSmoothingEnabled);
} else {
auto img = _img.createImage();
CairoSurface cs(*img);
drawNativeSurface(cs, x, y, w, h, globalAlpha, clipPath, imageSmoothingEnabled);
}
}
void
CairoSurface::drawImage(const Image & _img, double x, double y, double w, double h, float displayScale, float globalAlpha, float shadowBlur, float shadowOffsetX, float shadowOffsetY, const Color & shadowColor, const Path & clipPath, bool imageSmoothingEnabled) {
CairoSurface img(_img);
drawNativeSurface(img, x, y, w, h, globalAlpha, clipPath, imageSmoothingEnabled);
}
<|endoftext|> |
<commit_before>// (C) Copyright Kirill Lykov 2013.
//
// Contributed author Vadim Frolov
// Distributed under the FreeBSD Software License (See accompanying file license.txt)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
// OpenNI
#include <XnCppWrapper.h>
#define THROW_IF_FAILED(retVal) {if (retVal != XN_STATUS_OK) throw xnGetStatusString(retVal);}
// OpenCV
#include <opencv2/opencv.hpp>
/**
* @class
* Helper class for tackling codec names
*/
class CodecName2FourCC
{
typedef std::map<std::string, std::string> Map;
typedef std::map<std::string, std::string>::iterator Iterator;
Map m_codecName2FourCC;
public:
CodecName2FourCC()
{
m_codecName2FourCC["MPEG-1"] = "PIM1";
m_codecName2FourCC["MPEG-4.2"] = "MP42";
m_codecName2FourCC["MPEG-4.3"] = "DIV3";
m_codecName2FourCC["MPEG-4"] = "DIVX";
m_codecName2FourCC["FLV1"] = "FLV1";
}
int operator() (const std::string& codeName)
{
Iterator it = m_codecName2FourCC.find(codeName);
if (it == m_codecName2FourCC.end())
throw "unknown codec name";
std::string fourcc = it->second;
return CV_FOURCC(fourcc[0], fourcc[1], fourcc[2], fourcc[3]);
}
};
std::ostream& operator << (std::ostream& stream, const XnVersion& item)
{
stream << static_cast<int>(item.nMajor) << "." << static_cast<int>(item.nMinor) << "." << item.nMaintenance << ". Build " << item.nBuild;
return stream;
}
std::ostream& operator << (std::ostream& stream, const XnProductionNodeDescription& item)
{
stream << "\tOpenNI version: " << item.Version << std::endl;
stream << "\tType: " << item.Type << ". Generator name: " << item.strName << ". Vendor: " << item.strVendor << "." << std::endl;
return stream;
}
/**
* @class
* Normalize colors in depth using histogram as proposed by user Vlad:
* http://stackoverflow.com/questions/17944590/convert-kinects-depth-to-rgb
* The original idea is from
* https://github.com/OpenNI/OpenNI2/blob/master/Samples/Common/OniSampleUtilities.h
*/
class HistogramNormalizer
{
public:
static void run(cv::Mat& input)
{
// TODO smth like cv::equalizeHist(depthMat8UC1, depth2);
// should give the same result but is not. Check it out
std::vector<float> histogram;
calculateHistogram(input, histogram);
cv::MatIterator_<short> it = input.begin<short>(), it_end = input.end<short>();
for(; it != it_end; ++it) {
*it = histogram[*it];
}
}
private:
static void calculateHistogram(const cv::Mat& depth, std::vector<float>& histogram)
{
int depthTypeSize = CV_ELEM_SIZE(depth.type());
int histogramSize = pow(2., 8 * depthTypeSize);
histogram.resize(histogramSize, 0.0f);
unsigned int nNumberOfPoints = 0;
cv::MatConstIterator_<short> it = depth.begin<short>(), it_end = depth.end<short>();
for(; it != it_end; ++it) {
if (*it != 0) {
++histogram[*it];
++nNumberOfPoints;
}
}
for (int nIndex = 1; nIndex < histogramSize; ++nIndex)
{
histogram[nIndex] += histogram[nIndex - 1];
}
if (nNumberOfPoints != 0)
{
for (int nIndex = 1; nIndex < histogramSize; ++nIndex)
{
histogram[nIndex] = (256.0 * (1.0f - (histogram[nIndex] / nNumberOfPoints)));
}
}
}
};
/**
* @class
* Convert oni file to avi or images
*/
class Oni2AviConverter
{
CodecName2FourCC m_codecName2Code;
public:
Oni2AviConverter()
{
}
void run(const std::string& codecName,
const std::string& inputFile, const std::string& outputFile, bool depthAsPng = false)
{
// TODO For the latest version of OpenCV, you may use HighGUI instead of using OpenNI
// assumed that nframes, picture size for depth and images is the same
xn::Context context;
THROW_IF_FAILED(context.Init());
xn::Player player;
THROW_IF_FAILED(context.OpenFileRecording(inputFile.c_str(), player));
THROW_IF_FAILED(player.SetRepeat(false));
xn::ImageGenerator imageGen;
THROW_IF_FAILED(imageGen.Create(context));
XnPixelFormat pixelFormat = imageGen.GetPixelFormat();
if (pixelFormat != XN_PIXEL_FORMAT_RGB24) {
THROW_IF_FAILED(imageGen.SetPixelFormat(XN_PIXEL_FORMAT_RGB24));
}
xn::ImageMetaData xImageMap2;
imageGen.GetMetaData(xImageMap2);
XnUInt32 fps = xImageMap2.FPS();
XnUInt32 frame_height = xImageMap2.YRes();
XnUInt32 frame_width = xImageMap2.XRes();
xn::DepthGenerator depthGen;
depthGen.Create(context);
XnUInt32 nframes;
player.GetNumFrames(depthGen.GetName(), nframes);
std::string outputFileImg, outputFileDepth;
getOutputFileNames(outputFile, outputFileImg, outputFileDepth);
printResume(nframes, codecName, inputFile, outputFileImg, depthGen);
//check permissions to write in the current directory
//fs::path currentFolder("./");
//fs::file_status st = fs::status(currentFolder);
//std::cout << (st.permissions() & fs::all_all) << std::endl;
cv::VideoWriter imgWriter(outputFileImg, m_codecName2Code(codecName), fps, cvSize(frame_width, frame_height), 1);
cv::VideoWriter depthWriter;
if (!depthAsPng)
depthWriter.open(outputFileDepth, m_codecName2Code(codecName), fps, cvSize(frame_width, frame_height), 1);
fs::path folderForDepthImages = getDepthFolderName(outputFileImg);
if (depthAsPng)
{
if (fs::exists(folderForDepthImages) && !fs::is_directory(folderForDepthImages))
{
throw "Cannot create a directory because file with the same name exists. Remove it and try again";
}
if (!fs::exists(folderForDepthImages))
{
fs::create_directory(folderForDepthImages);
}
}
std::vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(0);
THROW_IF_FAILED(context.StartGeneratingAll());
size_t outStep = nframes > 10 ? nframes / 10 : 1;
try
{
for(size_t iframe = 0; iframe < nframes; ++iframe)
{
if ( iframe % outStep == 0 )
std::cout << iframe << "/" << nframes << std::endl;
// save image
THROW_IF_FAILED(imageGen.WaitAndUpdateData());
xn::ImageMetaData xImageMap;
imageGen.GetMetaData(xImageMap);
XnRGB24Pixel* imgData = const_cast<XnRGB24Pixel*>(xImageMap.RGB24Data());
cv::Mat image(frame_height, frame_width, CV_8UC3, reinterpret_cast<void*>(imgData));
cv::cvtColor(image, image, CV_BGR2RGB); // opencv image format is BGR
imgWriter << image.clone();
// save depth
THROW_IF_FAILED(depthGen.WaitAndUpdateData());
xn::DepthMetaData xDepthMap;
depthGen.GetMetaData(xDepthMap);
XnDepthPixel* depthData = const_cast<XnDepthPixel*>(xDepthMap.Data());
cv::Mat depth(frame_height, frame_width, CV_16U, reinterpret_cast<void*>(depthData));
if (!depthAsPng)
{
#if (CV_MAJOR_VERSION == 2 && CV_MINOR_VERSION >= 4) || CV_MAJOR_VERSION > 2
HistogramNormalizer::run(depth);
cv::Mat depthMat8UC1;
depth.convertTo(depthMat8UC1, CV_8UC1);
// can be used for having different colors than grey
cv::Mat falseColorsMap;
cv::applyColorMap(depthMat8UC1, falseColorsMap, cv::COLORMAP_AUTUMN);
depthWriter << falseColorsMap;
#else
throw "saving depth in avi file is not supported for opencv 2.3 or earlier. please use option --depth-png=yes";
#endif
}
else
{
// to_string is not supported by gcc4.7 so I don't use it here
//std::string imgNumAsStr = std::to_string(imgNum);
std::stringstream ss;
ss << folderForDepthImages.string() << "/depth-" << iframe << ".png";
cv::imwrite(ss.str(), depth, compression_params);
}
}
}
catch(...)
{
context.StopGeneratingAll();
context.Release();
throw;
}
context.StopGeneratingAll();
context.Release();
}
private:
static void printResume(size_t nframes, const std::string& codecName,
const std::string& inputFile, const std::string& outputFile, const xn::DepthGenerator& depthGen)
{
std::cout <<
"Input file name: " << inputFile << ".\nOutput file name: " << outputFile
<< ".\n\tTotal: " << nframes << " frames. Used codec: " << codecName << std::endl;
xn::NodeInfo nin = depthGen.GetInfo();
if ((XnNodeInfo*)nin == 0)
throw "Could not read DepthGenerator info. Probably, the input file is corrupted";
XnProductionNodeDescription description = nin.GetDescription();
std::cout << description;
}
static void getOutputFileNames(const std::string& outputFileName, std::string& outputFileImg,
std::string& outputFileDepth)
{
fs::path outPath(outputFileName);
if (outPath.extension() != ".avi")
throw "output file extention must be avi";
std::string nameWithoutExtension = (outPath.parent_path() / outPath.stem()).string();
outputFileImg = nameWithoutExtension + "-img.avi";
outputFileDepth = nameWithoutExtension + "-depth.avi";
}
static fs::path getDepthFolderName(fs::path outPath)
{
fs::path fnNoExt = outPath.stem();
//fnNoExt += "-depth"; cannot use it because boost 1.48 doesn't have operator +=
return fs::path(fnNoExt.string() + "-depth");
}
Oni2AviConverter(const Oni2AviConverter&);
Oni2AviConverter& operator= (const Oni2AviConverter&);
};
int main(int argc, char* argv[])
{
try
{
po::options_description desc("oni2avi converts an input oni file into 2 avi files - one for image and another for the depth map."
"\n Allowed options:");
desc.add_options()
("help", "produce help message")
("codec", po::value<std::string>()->default_value("MPEG-4.2"),
"codec used for output video. Available codecs are MPEG-1, MPEG-4, MPEG-4.2, MPEG-4.3 , FLV1")
("input-file", po::value< std::string >(), "input oni file")
("output-file", po::value< std::string >(), "output avi file")
("depth-png", po::value< std::string >(), "save depth as png images instead of avi file. Available values yes or no")
;
po::positional_options_description p;
p.add("input-file", 1);
p.add("output-file", 2);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
if (!vm.count("codec"))
throw "codec was not set\n";
if (!vm.count("input-file"))
throw "input file was not set\n";
if (!vm.count("output-file"))
throw "output file was not set\n";
bool depthAsPng = false;
if (vm.count("depth-png"))
if (vm["depth-png"].as<std::string>() == "yes")
{
depthAsPng = true;
}
Oni2AviConverter converter;
converter.run(vm["codec"].as<std::string>(),
vm["input-file"].as<std::string>(),
vm["output-file"].as<std::string>(), depthAsPng);
}
catch (const char* error)
{
// oni2avi errors
std::cout << "Error: " << error << std::endl;
return 1;
}
catch (const std::exception& error)
{
// OpenCV exceptions are derived from std::exception
std::cout << error.what() << std::endl;
return 1;
}
catch (...)
{
std::cout << "Unknown error" << std::endl;
return 1;
}
return 0;
}
<commit_msg>Added functionality to extract high quality images and depth map<commit_after>// (C) Copyright Kirill Lykov 2013.
//
// Contributed author Vadim Frolov
// Distributed under the FreeBSD Software License (See accompanying file license.txt)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
// OpenNI
#include <XnCppWrapper.h>
#define THROW_IF_FAILED(retVal) {if (retVal != XN_STATUS_OK) throw xnGetStatusString(retVal);}
// OpenCV
#include <opencv2/opencv.hpp>
/**
* @class
* Helper class for tackling codec names
*/
class CodecName2FourCC
{
typedef std::map<std::string, std::string> Map;
typedef std::map<std::string, std::string>::iterator Iterator;
Map m_codecName2FourCC;
public:
CodecName2FourCC()
{
m_codecName2FourCC["MPEG-1"] = "PIM1";
m_codecName2FourCC["MPEG-4.2"] = "MP42";
m_codecName2FourCC["MPEG-4.3"] = "DIV3";
m_codecName2FourCC["MPEG-4"] = "DIVX";
m_codecName2FourCC["FLV1"] = "FLV1";
}
int operator() (const std::string& codeName)
{
Iterator it = m_codecName2FourCC.find(codeName);
if (it == m_codecName2FourCC.end())
throw "unknown codec name";
std::string fourcc = it->second;
return CV_FOURCC(fourcc[0], fourcc[1], fourcc[2], fourcc[3]);
}
};
std::ostream& operator << (std::ostream& stream, const XnVersion& item)
{
stream << static_cast<int>(item.nMajor) << "." << static_cast<int>(item.nMinor) << "." << item.nMaintenance << ". Build " << item.nBuild;
return stream;
}
std::ostream& operator << (std::ostream& stream, const XnProductionNodeDescription& item)
{
stream << "\tOpenNI version: " << item.Version << std::endl;
stream << "\tType: " << item.Type << ". Generator name: " << item.strName << ". Vendor: " << item.strVendor << "." << std::endl;
return stream;
}
/**
* @class
* Normalize colors in depth using histogram as proposed by user Vlad:
* http://stackoverflow.com/questions/17944590/convert-kinects-depth-to-rgb
* The original idea is from
* https://github.com/OpenNI/OpenNI2/blob/master/Samples/Common/OniSampleUtilities.h
*/
class HistogramNormalizer
{
public:
static void run(cv::Mat& input)
{
// TODO smth like cv::equalizeHist(depthMat8UC1, depth2);
// should give the same result but is not. Check it out
std::vector<float> histogram;
calculateHistogram(input, histogram);
cv::MatIterator_<short> it = input.begin<short>(), it_end = input.end<short>();
for(; it != it_end; ++it) {
*it = histogram[*it];
}
}
private:
static void calculateHistogram(const cv::Mat& depth, std::vector<float>& histogram)
{
int depthTypeSize = CV_ELEM_SIZE(depth.type());
int histogramSize = pow(2., 8 * depthTypeSize);
histogram.resize(histogramSize, 0.0f);
unsigned int nNumberOfPoints = 0;
cv::MatConstIterator_<short> it = depth.begin<short>(), it_end = depth.end<short>();
for(; it != it_end; ++it) {
if (*it != 0) {
++histogram[*it];
++nNumberOfPoints;
}
}
for (int nIndex = 1; nIndex < histogramSize; ++nIndex)
{
histogram[nIndex] += histogram[nIndex - 1];
}
if (nNumberOfPoints != 0)
{
for (int nIndex = 1; nIndex < histogramSize; ++nIndex)
{
histogram[nIndex] = (256.0 * (1.0f - (histogram[nIndex] / nNumberOfPoints)));
}
}
}
};
/**
* @class
* Convert oni file to avi or images
*/
class Oni2AviConverter
{
CodecName2FourCC m_codecName2Code;
public:
Oni2AviConverter()
{
}
void run(const std::string& codecName,
const std::string& inputFile, const std::string& outputFile, bool depthAsPng = false)
{
// TODO For the latest version of OpenCV, you may use HighGUI instead of using OpenNI
// assumed that nframes, picture size for depth and images is the same
xn::Context context;
THROW_IF_FAILED(context.Init());
xn::Player player;
THROW_IF_FAILED(context.OpenFileRecording(inputFile.c_str(), player));
THROW_IF_FAILED(player.SetRepeat(false));
xn::ImageGenerator imageGen;
THROW_IF_FAILED(imageGen.Create(context));
XnPixelFormat pixelFormat = imageGen.GetPixelFormat();
if (pixelFormat != XN_PIXEL_FORMAT_RGB24) {
THROW_IF_FAILED(imageGen.SetPixelFormat(XN_PIXEL_FORMAT_RGB24));
}
xn::ImageMetaData xImageMap2;
imageGen.GetMetaData(xImageMap2);
XnUInt32 fps = xImageMap2.FPS();
XnUInt32 frame_height = xImageMap2.YRes();
XnUInt32 frame_width = xImageMap2.XRes();
xn::DepthGenerator depthGen;
depthGen.Create(context);
XnUInt32 nframes;
player.GetNumFrames(depthGen.GetName(), nframes);
std::string outputFileImg, outputFileDepth;
getOutputFileNames(outputFile, outputFileImg, outputFileDepth);
printResume(nframes, codecName, inputFile, outputFileImg, depthGen);
//check permissions to write in the current directory
//fs::path currentFolder("./");
//fs::file_status st = fs::status(currentFolder);
//std::cout << (st.permissions() & fs::all_all) << std::endl;
cv::VideoWriter imgWriter(outputFileImg, m_codecName2Code(codecName), fps, cvSize(frame_width, frame_height), 1);
cv::VideoWriter depthWriter;
if (!depthAsPng)
depthWriter.open(outputFileDepth, m_codecName2Code(codecName), fps, cvSize(frame_width, frame_height), 1);
fs::path folderForDepthImages = getDepthFolderName(outputFileImg);
if (depthAsPng)
{
if (fs::exists(folderForDepthImages) && !fs::is_directory(folderForDepthImages))
{
throw "Cannot create a directory because file with the same name exists. Remove it and try again";
}
if (!fs::exists(folderForDepthImages))
{
fs::create_directory(folderForDepthImages);
}
}
std::vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(0);
THROW_IF_FAILED(context.StartGeneratingAll());
size_t outStep = nframes > 10 ? nframes / 10 : 1;
try
{
for(size_t iframe = 0; iframe < nframes; ++iframe)
{
if ( iframe % outStep == 0 )
std::cout << iframe << "/" << nframes << std::endl;
// save image
THROW_IF_FAILED(imageGen.WaitAndUpdateData());
xn::ImageMetaData xImageMap;
imageGen.GetMetaData(xImageMap);
XnRGB24Pixel* imgData = const_cast<XnRGB24Pixel*>(xImageMap.RGB24Data());
cv::Mat image(frame_height, frame_width, CV_8UC3, reinterpret_cast<void*>(imgData));
cv::cvtColor(image, image, CV_BGR2RGB); // opencv image format is BGR
//Saving Image frames
std::ostringstream oss;
oss << "rgb-" << iframe << ".ppm";
std::string color_mat = oss.str();
cv::imwrite(color_mat,image);
imgWriter << image.clone();
// save depth
THROW_IF_FAILED(depthGen.WaitAndUpdateData());
xn::DepthMetaData xDepthMap;
depthGen.GetMetaData(xDepthMap);
XnDepthPixel* depthData = const_cast<XnDepthPixel*>(xDepthMap.Data());
cv::Mat depth(frame_height, frame_width, CV_16U, reinterpret_cast<void*>(depthData));
//Saving depth frames
std::ostringstream oss2;
oss2 << "depth-" << iframe;
std::string depth_mat = oss2.str();
cv::FileStorage file(depth_mat,cv::FileStorage::WRITE);
file << depth_mat<<depth ;
if (!depthAsPng)
{
#if (CV_MAJOR_VERSION == 2 && CV_MINOR_VERSION >= 4) || CV_MAJOR_VERSION > 2
HistogramNormalizer::run(depth);
cv::Mat depthMat8UC1;
depth.convertTo(depthMat8UC1, CV_8UC1);
// can be used for having different colors than grey
cv::Mat falseColorsMap;
cv::applyColorMap(depthMat8UC1, falseColorsMap, cv::COLORMAP_AUTUMN);
depthWriter << falseColorsMap;
#else
throw "saving depth in avi file is not supported for opencv 2.3 or earlier. please use option --depth-png=yes";
#endif
}
else
{
// to_string is not supported by gcc4.7 so I don't use it here
//std::string imgNumAsStr = std::to_string(imgNum);
std::stringstream ss;
ss << folderForDepthImages.string() << "/depth-" << iframe << ".png";
cv::imwrite(ss.str(), depth, compression_params);
}
}
}
catch(...)
{
context.StopGeneratingAll();
context.Release();
throw;
}
context.StopGeneratingAll();
context.Release();
}
private:
static void printResume(size_t nframes, const std::string& codecName,
const std::string& inputFile, const std::string& outputFile, const xn::DepthGenerator& depthGen)
{
std::cout <<
"Input file name: " << inputFile << ".\nOutput file name: " << outputFile
<< ".\n\tTotal: " << nframes << " frames. Used codec: " << codecName << std::endl;
xn::NodeInfo nin = depthGen.GetInfo();
if ((XnNodeInfo*)nin == 0)
throw "Could not read DepthGenerator info. Probably, the input file is corrupted";
XnProductionNodeDescription description = nin.GetDescription();
std::cout << description;
}
static void getOutputFileNames(const std::string& outputFileName, std::string& outputFileImg,
std::string& outputFileDepth)
{
fs::path outPath(outputFileName);
if (outPath.extension() != ".avi")
throw "output file extention must be avi";
std::string nameWithoutExtension = (outPath.parent_path() / outPath.stem()).string();
outputFileImg = nameWithoutExtension + "-img.avi";
outputFileDepth = nameWithoutExtension + "-depth.avi";
}
static fs::path getDepthFolderName(fs::path outPath)
{
fs::path fnNoExt = outPath.stem();
//fnNoExt += "-depth"; cannot use it because boost 1.48 doesn't have operator +=
return fs::path(fnNoExt.string() + "-depth");
}
Oni2AviConverter(const Oni2AviConverter&);
Oni2AviConverter& operator= (const Oni2AviConverter&);
};
int main(int argc, char* argv[])
{
try
{
po::options_description desc("oni2avi converts an input oni file into 2 avi files - one for image and another for the depth map."
"\n Allowed options:");
desc.add_options()
("help", "produce help message")
("codec", po::value<std::string>()->default_value("MPEG-4.2"),
"codec used for output video. Available codecs are MPEG-1, MPEG-4, MPEG-4.2, MPEG-4.3 , FLV1")
("input-file", po::value< std::string >(), "input oni file")
("output-file", po::value< std::string >(), "output avi file")
("depth-png", po::value< std::string >(), "save depth as png images instead of avi file. Available values yes or no")
;
po::positional_options_description p;
p.add("input-file", 1);
p.add("output-file", 2);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
if (!vm.count("codec"))
throw "codec was not set\n";
if (!vm.count("input-file"))
throw "input file was not set\n";
if (!vm.count("output-file"))
throw "output file was not set\n";
bool depthAsPng = false;
if (vm.count("depth-png"))
if (vm["depth-png"].as<std::string>() == "yes")
{
depthAsPng = true;
}
Oni2AviConverter converter;
converter.run(vm["codec"].as<std::string>(),
vm["input-file"].as<std::string>(),
vm["output-file"].as<std::string>(), depthAsPng);
}
catch (const char* error)
{
// oni2avi errors
std::cout << "Error: " << error << std::endl;
return 1;
}
catch (const std::exception& error)
{
// OpenCV exceptions are derived from std::exception
std::cout << error.what() << std::endl;
return 1;
}
catch (...)
{
std::cout << "Unknown error" << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "prog_solver.h"
#include "OsiSolverInterface.hpp"
#include "prog_translator.h"
#include "greedy_solver.h"
#include "solver_factory.h"
namespace cyclus {
void Report(OsiSolverInterface* iface) {
std::cout << iface->getNumCols() << " total variables, "
<< iface->getNumIntegers() << " integer.\n";
std::cout << iface->getNumRows() << " constraints\n";
}
ProgSolver::ProgSolver(std::string solver_t)
: solver_t_(solver_t),
tmax_(ProgSolver::KOptimizeDefaultTimeout),
ExchangeSolver(false) {}
ProgSolver::ProgSolver(std::string solver_t, bool exclusive_orders)
: solver_t_(solver_t),
tmax_(ProgSolver::KOptimizeDefaultTimeout),
ExchangeSolver(exclusive_orders) {}
ProgSolver::ProgSolver(std::string solver_t, double tmax)
: solver_t_(solver_t),
tmax_(tmax),
ExchangeSolver(false) {}
ProgSolver::ProgSolver(std::string solver_t, double tmax, bool exclusive_orders)
: solver_t_(solver_t),
tmax_(tmax),
ExchangeSolver(exclusive_orders) {}
ProgSolver::~ProgSolver() {}
double ProgSolver::SolveGraph() {
SolverFactory sf(solver_t_);
OsiSolverInterface* iface = sf.get();
try {
// get greedy solution
GreedySolver greedy(exclusive_orders_);
double greedy_obj = greedy.Solve(graph_);
graph_->ClearMatches();
// translate graph to iface instance
double pseudo_cost = PseudoCost(); // from ExchangeSolver API
ProgTranslator xlator(graph_, iface, exclusive_orders_, pseudo_cost);
xlator.ToProg();
// set noise level
CoinMessageHandler h;
h.setLogLevel(0);
if (verbose_) {
Report(iface);
h.setLogLevel(4);
}
iface->passInMessageHandler(&h);
if (verbose_) {
std::cout << "Solving problem, message handler has log level of "
<< iface->messageHandler()->logLevel() << "\n";
}
bool verbose = false; // turn this off, solveprog prints a lot
// solve and back translate
SolveProg(iface, greedy_obj, verbose);
xlator.FromProg();
} catch(...) {
delete iface;
throw;
}
double ret = iface->getObjValue();
delete iface;
return ret;
}
} // namespace cyclus
<commit_msg>prog solver now passes through tmax argument<commit_after>#include "prog_solver.h"
#include "OsiSolverInterface.hpp"
#include "prog_translator.h"
#include "greedy_solver.h"
#include "solver_factory.h"
namespace cyclus {
void Report(OsiSolverInterface* iface) {
std::cout << iface->getNumCols() << " total variables, "
<< iface->getNumIntegers() << " integer.\n";
std::cout << iface->getNumRows() << " constraints\n";
}
ProgSolver::ProgSolver(std::string solver_t)
: solver_t_(solver_t),
tmax_(ProgSolver::KOptimizeDefaultTimeout),
ExchangeSolver(false) {}
ProgSolver::ProgSolver(std::string solver_t, bool exclusive_orders)
: solver_t_(solver_t),
tmax_(ProgSolver::KOptimizeDefaultTimeout),
ExchangeSolver(exclusive_orders) {}
ProgSolver::ProgSolver(std::string solver_t, double tmax)
: solver_t_(solver_t),
tmax_(tmax),
ExchangeSolver(false) {}
ProgSolver::ProgSolver(std::string solver_t, double tmax, bool exclusive_orders)
: solver_t_(solver_t),
tmax_(tmax),
ExchangeSolver(exclusive_orders) {}
ProgSolver::~ProgSolver() {}
double ProgSolver::SolveGraph() {
SolverFactory sf(solver_t_, tmax_);
OsiSolverInterface* iface = sf.get();
try {
// get greedy solution
GreedySolver greedy(exclusive_orders_);
double greedy_obj = greedy.Solve(graph_);
graph_->ClearMatches();
// translate graph to iface instance
double pseudo_cost = PseudoCost(); // from ExchangeSolver API
ProgTranslator xlator(graph_, iface, exclusive_orders_, pseudo_cost);
xlator.ToProg();
// set noise level
CoinMessageHandler h;
h.setLogLevel(0);
if (verbose_) {
Report(iface);
h.setLogLevel(4);
}
iface->passInMessageHandler(&h);
if (verbose_) {
std::cout << "Solving problem, message handler has log level of "
<< iface->messageHandler()->logLevel() << "\n";
}
bool verbose = false; // turn this off, solveprog prints a lot
// solve and back translate
SolveProg(iface, greedy_obj, verbose);
xlator.FromProg();
} catch(...) {
delete iface;
throw;
}
double ret = iface->getObjValue();
delete iface;
return ret;
}
} // namespace cyclus
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include "../Global.h"
#include "../Options.h"
#include "../Data.h"
#include "../Scheme.h"
#include "../Inputs/Input.h"
#include "../Loggers/Logger.h"
#include "../Loggers/Default.h"
#include "../Location.h"
#include "../Member.h"
#include <cstring>
bool mShowAll;
bool mShowStat;
bool mShowSpecific;
void showLocations(Input* input);
void showOffsets(Input* input);
void showDates(Input* input);
void showMembers(Input* input);
void showVariables(Input* input);
int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate);
int main(int argc, const char *argv[]) {
Global::setLogger(new LoggerDefault(Logger::message));
if(argc != 2 && argc != 3 && argc != 4) {
std::cout << "Show information about a COMPS dataset" << std::endl;
std::cout << std::endl;
std::cout << "usage: info.exe dataset [--show-all] show information about dataset" << std::endl;
std::cout << " or: info.exe dataset date show detailed information for a specific date" << std::endl;
std::cout << " or: info.exe dataset startDate endDate show detailed information for a date range" << std::endl;
std::cout << std::endl;
std::cout << "Arguments:" << std::endl;
std::cout << " dataset Tag of dataset from namelist" << std::endl;
std::cout << " date Date in YYYYMMDD format" << std::endl;
std::cout << " --show-all Do not limit variables/dates/offsets to the first 100" << std::endl;
return 0;
}
mShowAll = false;
mShowSpecific = false;
int startDate = Global::MV;
int endDate = Global::MV;
std::string dataset(argv[1]);
if(argc >= 3) {
for(int i = 2; i < argc; i++) {
if(!std::strcmp(argv[i], "--show-all")) {
mShowAll = true;
}
else if(!Global::isValid(startDate)) {
std::stringstream ss;
ss<< std::string(argv[i]);
ss >> startDate;
endDate = startDate;
}
else {
std::stringstream ss;
ss<< std::string(argv[i]);
ss >> endDate;
}
}
}
if(Global::isValid(startDate)) {
mShowSpecific = true;
}
InputContainer inputContainer(Options(""));
Input* input = inputContainer.getInput(dataset);
if(mShowSpecific) {
// Show results for one specific date
std::vector<float> offsets = input->getOffsets();
std::vector<std::string> variables = input->getVariables();
std::vector<Location> locations = input->getLocations();
std::vector<Member> members = input->getMembers();
std::vector<double> min(variables.size(), Global::INF);
std::vector<double> mean(variables.size(), 0);
std::vector<double> max(variables.size(), -Global::INF);
std::vector<long> num(variables.size(), 0);
std::cout << "Variable min mean max count (max "
<< offsets.size()*locations.size()*members.size() << ")" << std::endl;
for(int v = 0; v < variables.size(); v++) {
int date = startDate;
while(date <= endDate) {
for(int i = 0; i < offsets.size(); i++) {
for(int k = 0; k < locations.size(); k++) {
for(int m = 0; m < members.size(); m++) {
double value = input->getValue(date, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]);
if(Global::isValid(value)) {
min[v] = std::min(min[v], value);
mean[v] += value;
max[v] = std::max(max[v], value);
num[v]++;
}
}
}
}
date = Global::getDate(date, 24);
}
if(num[v] > 0)
mean[v] /= num[v];
else {
min[v] = Global::MV;
mean[v] = Global::MV;
max[v] = Global::MV;
}
std::cout << std::left << std::setfill(' ') << std::setw(12) << variables[v] << " "
<< std::setprecision(3) << std::setw(5) << min[v] << " "
<< std::setprecision(3) << std::setw(5) << mean[v]<< " "
<< std::setprecision(3) << std::setw(10) << max[v] << " " << num[v] << std::endl;
}
// Show results for each location
std::cout << std::endl;
std::cout << "Counts for each location and variable" << std::endl;
std::cout << "Id ";
for(int v = 0; v < variables.size(); v++) {
std::cout << std::setw(12) << variables[v];
}
std::cout << std::endl;
for(int k = 0; k < locations.size(); k++) {
std::cout << std::setw(6) << locations[k].getId();
for(int v = 0; v < variables.size(); v++) {
int num = 0;
int date = startDate;
while(date <= endDate) {
for(int i = 0; i < offsets.size(); i++) {
for(int m = 0; m < members.size(); m++) {
float value = input->getValue(startDate, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]);
if(Global::isValid(value)) {
num++;
}
}
}
date = Global::getDate(date, 24);
}
std::cout << std::setw(12) << num;
}
std::cout << std::endl;
}
}
else {
// Show general statistics
showLocations(input);
showOffsets(input);
showDates(input);
showVariables(input);
showMembers(input);
}
}
void showLocations(Input* input) {
const std::vector<Location>& locations = input->getLocations();
std::cout << "Locations (" << locations.size() << " total):" << std::endl;
std::cout << "Id code lat lon elev gradient landFrac";
std::cout << std::endl;
for(int i = 0; i < locations.size(); i++) {
if(mShowAll || locations.size() < 100 || i < 5 || i >= locations.size()-5) {
std::cout << std::setw(6) << locations[i].getId() << " "
<< std::setw(6) << locations[i].getCode() << " "
<< std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getLat() << " "
<< std::setw(6) << locations[i].getLon() << " "
<< std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getElev() << " ";
float gradX = locations[i].getGradientX();
float gradY = locations[i].getGradientY();
if(Global::isValid(gradX) && Global::isValid(gradY)) {
std::cout << std::setw(6) << std::fixed << std::setprecision(3) << gradX << ","
<< std::setw(6) << std::fixed << std::setprecision(3) << gradY;
}
else {
std::cout << " ";
}
float landFrac = locations[i].getLandFraction();
if(Global::isValid(landFrac)) {
std::cout << std::setw(6) << std::fixed << std::setprecision(3) << landFrac;
}
else {
std::cout << " ";
}
std::cout << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
void showOffsets(Input* input) {
std::vector<float> offsets = input->getOffsets();
std::cout << "Offsets (" << offsets.size() << " total):" << std::endl;
std::cout << "Id offset (h)" << std::endl;
for(int i = 0; i < offsets.size(); i++) {
if(mShowAll || offsets.size() < 100 || i < 5 || i >= offsets.size()-5) {
std::cout << std::setw(6) << i << " "
<< std::setw(6) << offsets[i] << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
void showDates(Input* input) {
std::vector<int> dates;
std::cout << "Dates (" << dates.size() << " total):" << std::endl;
input->getDates(dates);
std::cout << "Id dates" << std::endl;
for(int i = 0; i < dates.size(); i++) {
if(mShowAll || dates.size() < 100 || i < 5 || i >= dates.size()-5) {
std::cout << std::setw(6) << i
<< std::setw(9) << dates[i] << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
void showVariables(Input* input) {
std::vector<std::string> variables = input->getVariables();
std::cout << "Variables (" << variables.size() << " total):" << std::endl;
std::cout << " Id variable" << std::endl;
for(int i = 0; i < variables.size(); i++) {
if(mShowAll || variables.size() < 100 || i < 5 || i >= variables.size()-5) {
std::cout << std::setw(6) << i << " "
<< std::setw(12) << variables[i] << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
}
void showMembers(Input* input) {
std::vector<Member> members = input->getMembers();
std::cout << "Members (" << members.size() << " total):" << std::endl;
std::cout << " Id model resolution" << std::endl;
for(int i = 0; i < members.size(); i++) {
if(mShowAll || members.size() < 100 || i < 5 || i >= members.size()-5) {
float res = members[i].getResolution();
std::cout << std::setw(6) << i << " "
<< std::setw(12) << members[i].getModel();
if(Global::isValid(res))
std::cout << std::setw(9) << res << "km";
std::cout << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate) {
std::vector<float> offsets = input->getOffsets();
std::vector<Location> locations = input->getLocations();
std::vector<Member> members = input->getMembers();
// float min=0,mean=0,max=0,num=0;
float num = 0;
int date = startDate;
while(date <= endDate) {
for(int i = 0; i < offsets.size(); i++) {
for(int k = 0; k < locations.size(); k++) {
for(int m = 0; m < members.size(); m++) {
float value = input->getValue(date, 0, offsets[i], locationId, members[m].getId(), variable);
if(Global::isValid(value)) {
// min = std::min(min, value);
// mean += value;
// max = std::max(max, value);
num++;
}
}
}
}
date = Global::getDate(date, 24);
}
return num;
}
<commit_msg>Allow init to be specified in info.exe<commit_after>#include <iostream>
#include <iomanip>
#include "../Global.h"
#include "../Options.h"
#include "../Data.h"
#include "../Scheme.h"
#include "../Inputs/Input.h"
#include "../Loggers/Logger.h"
#include "../Loggers/Default.h"
#include "../Location.h"
#include "../Member.h"
#include <cstring>
bool mShowAll;
bool mShowStat;
bool mShowSpecific;
void showLocations(Input* input);
void showOffsets(Input* input);
void showDates(Input* input);
void showMembers(Input* input);
void showVariables(Input* input);
int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate, int init);
int main(int argc, const char *argv[]) {
Global::setLogger(new LoggerDefault(Logger::message));
if(argc != 2 && argc != 3 && argc != 4 && argc != 5) {
std::cout << "Show information about a COMPS dataset" << std::endl;
std::cout << std::endl;
std::cout << "usage: info.exe dataset [--show-all] show information about dataset" << std::endl;
std::cout << " or: info.exe dataset date [init] show detailed information for a specific date" << std::endl;
std::cout << " or: info.exe dataset startDate endDate [init] show detailed information for a date range" << std::endl;
std::cout << std::endl;
std::cout << "Arguments:" << std::endl;
std::cout << " dataset Tag of dataset from namelist" << std::endl;
std::cout << " date Date in YYYYMMDD format" << std::endl;
std::cout << " init Initialization time in HH format. Default is 0." << std::endl;
std::cout << " --show-all Do not limit variables/dates/offsets to the first 100" << std::endl;
return 0;
}
mShowAll = false;
mShowSpecific = false;
int startDate = Global::MV;
int endDate = Global::MV;
int init = 0;
std::string dataset(argv[1]);
if(argc >= 3) {
for(int i = 2; i < argc; i++) {
if(!std::strcmp(argv[i], "--show-all")) {
mShowAll = true;
}
else {
float value;
std::stringstream ss;
ss << std::string(argv[i]);
ss >> value;
if(value < 1000) {
init = value;
}
else if(!Global::isValid(startDate)) {
std::stringstream ss;
ss<< std::string(argv[i]);
ss >> startDate;
endDate = startDate;
}
else {
std::stringstream ss;
ss<< std::string(argv[i]);
ss >> endDate;
}
}
}
}
if(Global::isValid(startDate)) {
mShowSpecific = true;
}
InputContainer inputContainer(Options(""));
Input* input = inputContainer.getInput(dataset);
if(mShowSpecific) {
// Show results for one specific date
std::vector<float> offsets = input->getOffsets();
std::vector<std::string> variables = input->getVariables();
std::vector<Location> locations = input->getLocations();
std::vector<Member> members = input->getMembers();
std::vector<double> min(variables.size(), Global::INF);
std::vector<double> mean(variables.size(), 0);
std::vector<double> max(variables.size(), -Global::INF);
std::vector<long> num(variables.size(), 0);
std::cout << "Variable min mean max count (max "
<< offsets.size()*locations.size()*members.size() << ")" << std::endl;
for(int v = 0; v < variables.size(); v++) {
int date = startDate;
while(date <= endDate) {
for(int i = 0; i < offsets.size(); i++) {
for(int k = 0; k < locations.size(); k++) {
for(int m = 0; m < members.size(); m++) {
double value = input->getValue(date, init, offsets[i], locations[k].getId(), members[m].getId(), variables[v]);
if(Global::isValid(value)) {
min[v] = std::min(min[v], value);
mean[v] += value;
max[v] = std::max(max[v], value);
num[v]++;
}
}
}
}
date = Global::getDate(date, 24);
}
if(num[v] > 0)
mean[v] /= num[v];
else {
min[v] = Global::MV;
mean[v] = Global::MV;
max[v] = Global::MV;
}
std::cout << std::left << std::setfill(' ') << std::setw(12) << variables[v] << " "
<< std::setprecision(3) << std::setw(5) << min[v] << " "
<< std::setprecision(3) << std::setw(5) << mean[v]<< " "
<< std::setprecision(3) << std::setw(10) << max[v] << " " << num[v] << std::endl;
}
// Show results for each location
std::cout << std::endl;
std::cout << "Counts for each location and variable" << std::endl;
std::cout << "Id ";
for(int v = 0; v < variables.size(); v++) {
std::cout << std::setw(12) << variables[v];
}
std::cout << std::endl;
for(int k = 0; k < locations.size(); k++) {
std::cout << std::setw(6) << locations[k].getId();
for(int v = 0; v < variables.size(); v++) {
int num = 0;
int date = startDate;
while(date <= endDate) {
for(int i = 0; i < offsets.size(); i++) {
for(int m = 0; m < members.size(); m++) {
float value = input->getValue(startDate, init, offsets[i], locations[k].getId(), members[m].getId(), variables[v]);
if(Global::isValid(value)) {
num++;
}
}
}
date = Global::getDate(date, 24);
}
std::cout << std::setw(12) << num;
}
std::cout << std::endl;
}
}
else {
// Show general statistics
showLocations(input);
showOffsets(input);
showDates(input);
showVariables(input);
showMembers(input);
}
}
void showLocations(Input* input) {
const std::vector<Location>& locations = input->getLocations();
std::cout << "Locations (" << locations.size() << " total):" << std::endl;
std::cout << "Id code lat lon elev gradient landFrac";
std::cout << std::endl;
for(int i = 0; i < locations.size(); i++) {
if(mShowAll || locations.size() < 100 || i < 5 || i >= locations.size()-5) {
std::cout << std::setw(6) << locations[i].getId() << " "
<< std::setw(6) << locations[i].getCode() << " "
<< std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getLat() << " "
<< std::setw(6) << locations[i].getLon() << " "
<< std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getElev() << " ";
float gradX = locations[i].getGradientX();
float gradY = locations[i].getGradientY();
if(Global::isValid(gradX) && Global::isValid(gradY)) {
std::cout << std::setw(6) << std::fixed << std::setprecision(3) << gradX << ","
<< std::setw(6) << std::fixed << std::setprecision(3) << gradY;
}
else {
std::cout << " ";
}
float landFrac = locations[i].getLandFraction();
if(Global::isValid(landFrac)) {
std::cout << std::setw(6) << std::fixed << std::setprecision(3) << landFrac;
}
else {
std::cout << " ";
}
std::cout << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
void showOffsets(Input* input) {
std::vector<float> offsets = input->getOffsets();
std::cout << "Offsets (" << offsets.size() << " total):" << std::endl;
std::cout << "Id offset (h)" << std::endl;
for(int i = 0; i < offsets.size(); i++) {
if(mShowAll || offsets.size() < 100 || i < 5 || i >= offsets.size()-5) {
std::cout << std::setw(6) << i << " "
<< std::setw(6) << offsets[i] << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
void showDates(Input* input) {
std::vector<int> dates;
std::cout << "Dates (" << dates.size() << " total):" << std::endl;
input->getDates(dates);
std::cout << "Id dates" << std::endl;
for(int i = 0; i < dates.size(); i++) {
if(mShowAll || dates.size() < 100 || i < 5 || i >= dates.size()-5) {
std::cout << std::setw(6) << i
<< std::setw(9) << dates[i] << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
void showVariables(Input* input) {
std::vector<std::string> variables = input->getVariables();
std::cout << "Variables (" << variables.size() << " total):" << std::endl;
std::cout << " Id variable" << std::endl;
for(int i = 0; i < variables.size(); i++) {
if(mShowAll || variables.size() < 100 || i < 5 || i >= variables.size()-5) {
std::cout << std::setw(6) << i << " "
<< std::setw(12) << variables[i] << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
}
void showMembers(Input* input) {
std::vector<Member> members = input->getMembers();
std::cout << "Members (" << members.size() << " total):" << std::endl;
std::cout << " Id model resolution" << std::endl;
for(int i = 0; i < members.size(); i++) {
if(mShowAll || members.size() < 100 || i < 5 || i >= members.size()-5) {
float res = members[i].getResolution();
std::cout << std::setw(6) << i << " "
<< std::setw(12) << members[i].getModel();
if(Global::isValid(res))
std::cout << std::setw(9) << res << "km";
std::cout << std::endl;
}
else if(i == 5) {
std::cout << "..." << std::endl;
}
}
std::cout << std::endl;
}
int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate, int init) {
std::vector<float> offsets = input->getOffsets();
std::vector<Location> locations = input->getLocations();
std::vector<Member> members = input->getMembers();
// float min=0,mean=0,max=0,num=0;
float num = 0;
int date = startDate;
while(date <= endDate) {
for(int i = 0; i < offsets.size(); i++) {
for(int k = 0; k < locations.size(); k++) {
for(int m = 0; m < members.size(); m++) {
float value = input->getValue(date, init, offsets[i], locationId, members[m].getId(), variable);
if(Global::isValid(value)) {
// min = std::min(min, value);
// mean += value;
// max = std::max(max, value);
num++;
}
}
}
}
date = Global::getDate(date, 24);
}
return num;
}
<|endoftext|> |
<commit_before>#include <string>
#include <memory>
#include <utility>
#include <nan.h>
#include <v8.h>
#include "nan/all_callback.h"
#include "nan/options.h"
#include "hub.h"
using v8::Local;
using v8::Value;
using v8::Object;
using v8::String;
using v8::Uint32;
using v8::Boolean;
using v8::Function;
using v8::FunctionTemplate;
using std::string;
using std::unique_ptr;
using std::move;
void configure(const Nan::FunctionCallbackInfo<Value> &info)
{
string main_log_file;
bool main_log_disable = false;
bool main_log_stderr = false;
bool main_log_stdout = false;
string worker_log_file;
bool worker_log_disable = false;
bool worker_log_stderr = false;
bool worker_log_stdout = false;
string polling_log_file;
bool polling_log_disable = false;
bool polling_log_stderr = false;
bool polling_log_stdout = false;
Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]);
if (maybe_options.IsEmpty()) {
Nan::ThrowError("configure() requires an option object");
return;
}
Local<Object> options = maybe_options.ToLocalChecked();
if (!get_string_option(options, "mainLogFile", main_log_file)) return;
if (!get_bool_option(options, "mainLogDisable", main_log_disable)) return;
if (!get_bool_option(options, "mainLogStderr", main_log_stderr)) return;
if (!get_bool_option(options, "mainLogStdout", main_log_stdout)) return;
if (!get_string_option(options, "workerLogFile", worker_log_file)) return;
if (!get_bool_option(options, "workerLogDisable", worker_log_disable)) return;
if (!get_bool_option(options, "workerLogStderr", worker_log_stderr)) return;
if (!get_bool_option(options, "workerLogStdout", worker_log_stdout)) return;
if (!get_string_option(options, "pollingLogFile", polling_log_file)) return;
if (!get_bool_option(options, "pollingLogDisable", polling_log_disable)) return;
if (!get_bool_option(options, "pollingLogStderr", polling_log_stderr)) return;
if (!get_bool_option(options, "pollingLogStdout", polling_log_stdout)) return;
unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>()));
AllCallback all(move(callback));
if (main_log_disable) {
Hub::get().disable_main_log();
} else if (!main_log_file.empty()) {
Hub::get().use_main_log_file(move(main_log_file));
} else if (main_log_stderr) {
Hub::get().use_main_log_stderr();
} else if (main_log_stdout) {
Hub::get().use_main_log_stdout();
}
Result<> wr = ok_result();
if (worker_log_disable) {
wr = Hub::get().disable_worker_log(all.create_callback());
} else if (!worker_log_file.empty()) {
wr = Hub::get().use_worker_log_file(move(worker_log_file), all.create_callback());
} else if (worker_log_stderr) {
wr = Hub::get().use_worker_log_stderr(all.create_callback());
} else if (worker_log_stdout) {
wr = Hub::get().use_worker_log_stdout(all.create_callback());
}
Result<> pr = ok_result();
if (polling_log_disable) {
pr = Hub::get().disable_polling_log(all.create_callback());
} else if (!polling_log_file.empty()) {
pr = Hub::get().use_polling_log_file(move(polling_log_file), all.create_callback());
} else if (polling_log_stderr) {
pr = Hub::get().use_polling_log_stderr(all.create_callback());
} else if (polling_log_stdout) {
pr = Hub::get().use_polling_log_stdout(all.create_callback());
}
all.fire_if_empty();
}
void watch(const Nan::FunctionCallbackInfo<Value> &info)
{
if (info.Length() != 3) {
return Nan::ThrowError("watch() requires three arguments");
}
Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]);
if (maybe_root.IsEmpty()) {
Nan::ThrowError("watch() requires a string as argument one");
return;
}
Local<String> root_v8_string = maybe_root.ToLocalChecked();
Nan::Utf8String root_utf8(root_v8_string);
if (*root_utf8 == nullptr) {
Nan::ThrowError("watch() argument one must be a valid UTF-8 string");
return;
}
string root_str(*root_utf8, root_utf8.length());
unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>()));
unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>()));
Result<> r = Hub::get().watch(move(root_str), false, move(ack_callback), move(event_callback));
if (r.is_error()) {
Nan::ThrowError(r.get_error().c_str());
}
}
void unwatch(const Nan::FunctionCallbackInfo<Value> &info)
{
if (info.Length() != 2) {
Nan::ThrowError("unwatch() requires two arguments");
return;
}
Nan::Maybe<uint32_t> maybe_channel_id = Nan::To<uint32_t>(info[0]);
if (maybe_channel_id.IsNothing()) {
Nan::ThrowError("unwatch() requires a channel ID as its first argument");
return;
}
ChannelID channel_id = static_cast<ChannelID>(maybe_channel_id.FromJust());
unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>()));
Result<> r = Hub::get().unwatch(channel_id, move(ack_callback));
if (r.is_error()) {
Nan::ThrowError(r.get_error().c_str());
}
}
void status(const Nan::FunctionCallbackInfo<Value> &info)
{
Status status;
Hub::get().collect_status(status);
Local<Object> status_object = Nan::New<Object>();
Nan::Set(
status_object,
Nan::New<String>("pendingCallbackCount").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.pending_callback_count))
);
Nan::Set(
status_object,
Nan::New<String>("channelCallbackCount").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.channel_callback_count))
);
Nan::Set(
status_object,
Nan::New<String>("workerThreadOk").ToLocalChecked(),
Nan::New<String>(status.worker_thread_ok).ToLocalChecked()
);
Nan::Set(
status_object,
Nan::New<String>("workerInSize").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.worker_in_size))
);
Nan::Set(
status_object,
Nan::New<String>("workerInOk").ToLocalChecked(),
Nan::New<String>(status.worker_in_ok).ToLocalChecked()
);
Nan::Set(
status_object,
Nan::New<String>("workerOutSize").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.worker_out_size))
);
Nan::Set(
status_object,
Nan::New<String>("workerOutOk").ToLocalChecked(),
Nan::New<String>(status.worker_out_ok).ToLocalChecked()
);
Nan::Set(
status_object,
Nan::New<String>("pollingThreadActive").ToLocalChecked(),
Nan::New<Boolean>(status.polling_thread_active)
);
info.GetReturnValue().Set(status_object);
}
void initialize(Local<Object> exports)
{
Nan::Set(
exports,
Nan::New<String>("configure").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked()
);
Nan::Set(
exports,
Nan::New<String>("watch").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked()
);
Nan::Set(
exports,
Nan::New<String>("unwatch").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked()
);
Nan::Set(
exports,
Nan::New<String>("status").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(status)).ToLocalChecked()
);
}
NODE_MODULE(watcher, initialize);
<commit_msg>Accept a {poll: [true|false]} argument in watch()<commit_after>#include <string>
#include <memory>
#include <utility>
#include <nan.h>
#include <v8.h>
#include "nan/all_callback.h"
#include "nan/options.h"
#include "hub.h"
using v8::Local;
using v8::Value;
using v8::Object;
using v8::String;
using v8::Uint32;
using v8::Boolean;
using v8::Function;
using v8::FunctionTemplate;
using std::string;
using std::unique_ptr;
using std::move;
void configure(const Nan::FunctionCallbackInfo<Value> &info)
{
string main_log_file;
bool main_log_disable = false;
bool main_log_stderr = false;
bool main_log_stdout = false;
string worker_log_file;
bool worker_log_disable = false;
bool worker_log_stderr = false;
bool worker_log_stdout = false;
string polling_log_file;
bool polling_log_disable = false;
bool polling_log_stderr = false;
bool polling_log_stdout = false;
Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]);
if (maybe_options.IsEmpty()) {
Nan::ThrowError("configure() requires an option object");
return;
}
Local<Object> options = maybe_options.ToLocalChecked();
if (!get_string_option(options, "mainLogFile", main_log_file)) return;
if (!get_bool_option(options, "mainLogDisable", main_log_disable)) return;
if (!get_bool_option(options, "mainLogStderr", main_log_stderr)) return;
if (!get_bool_option(options, "mainLogStdout", main_log_stdout)) return;
if (!get_string_option(options, "workerLogFile", worker_log_file)) return;
if (!get_bool_option(options, "workerLogDisable", worker_log_disable)) return;
if (!get_bool_option(options, "workerLogStderr", worker_log_stderr)) return;
if (!get_bool_option(options, "workerLogStdout", worker_log_stdout)) return;
if (!get_string_option(options, "pollingLogFile", polling_log_file)) return;
if (!get_bool_option(options, "pollingLogDisable", polling_log_disable)) return;
if (!get_bool_option(options, "pollingLogStderr", polling_log_stderr)) return;
if (!get_bool_option(options, "pollingLogStdout", polling_log_stdout)) return;
unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>()));
AllCallback all(move(callback));
if (main_log_disable) {
Hub::get().disable_main_log();
} else if (!main_log_file.empty()) {
Hub::get().use_main_log_file(move(main_log_file));
} else if (main_log_stderr) {
Hub::get().use_main_log_stderr();
} else if (main_log_stdout) {
Hub::get().use_main_log_stdout();
}
Result<> wr = ok_result();
if (worker_log_disable) {
wr = Hub::get().disable_worker_log(all.create_callback());
} else if (!worker_log_file.empty()) {
wr = Hub::get().use_worker_log_file(move(worker_log_file), all.create_callback());
} else if (worker_log_stderr) {
wr = Hub::get().use_worker_log_stderr(all.create_callback());
} else if (worker_log_stdout) {
wr = Hub::get().use_worker_log_stdout(all.create_callback());
}
Result<> pr = ok_result();
if (polling_log_disable) {
pr = Hub::get().disable_polling_log(all.create_callback());
} else if (!polling_log_file.empty()) {
pr = Hub::get().use_polling_log_file(move(polling_log_file), all.create_callback());
} else if (polling_log_stderr) {
pr = Hub::get().use_polling_log_stderr(all.create_callback());
} else if (polling_log_stdout) {
pr = Hub::get().use_polling_log_stdout(all.create_callback());
}
all.fire_if_empty();
}
void watch(const Nan::FunctionCallbackInfo<Value> &info)
{
if (info.Length() != 4) {
return Nan::ThrowError("watch() requires four arguments");
}
Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]);
if (maybe_root.IsEmpty()) {
Nan::ThrowError("watch() requires a string as argument one");
return;
}
Local<String> root_v8_string = maybe_root.ToLocalChecked();
Nan::Utf8String root_utf8(root_v8_string);
if (*root_utf8 == nullptr) {
Nan::ThrowError("watch() argument one must be a valid UTF-8 string");
return;
}
string root_str(*root_utf8, root_utf8.length());
Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[1]);
if (maybe_options.IsEmpty()) {
Nan::ThrowError("watch() requires an option object");
return;
}
Local<Object> options = maybe_options.ToLocalChecked();
bool poll = false;
if (!get_bool_option(options, "poll", poll)) return;
unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[2].As<Function>()));
unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[3].As<Function>()));
Result<> r = Hub::get().watch(move(root_str), poll, move(ack_callback), move(event_callback));
if (r.is_error()) {
Nan::ThrowError(r.get_error().c_str());
}
}
void unwatch(const Nan::FunctionCallbackInfo<Value> &info)
{
if (info.Length() != 2) {
Nan::ThrowError("unwatch() requires two arguments");
return;
}
Nan::Maybe<uint32_t> maybe_channel_id = Nan::To<uint32_t>(info[0]);
if (maybe_channel_id.IsNothing()) {
Nan::ThrowError("unwatch() requires a channel ID as its first argument");
return;
}
ChannelID channel_id = static_cast<ChannelID>(maybe_channel_id.FromJust());
unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>()));
Result<> r = Hub::get().unwatch(channel_id, move(ack_callback));
if (r.is_error()) {
Nan::ThrowError(r.get_error().c_str());
}
}
void status(const Nan::FunctionCallbackInfo<Value> &info)
{
Status status;
Hub::get().collect_status(status);
Local<Object> status_object = Nan::New<Object>();
Nan::Set(
status_object,
Nan::New<String>("pendingCallbackCount").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.pending_callback_count))
);
Nan::Set(
status_object,
Nan::New<String>("channelCallbackCount").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.channel_callback_count))
);
Nan::Set(
status_object,
Nan::New<String>("workerThreadOk").ToLocalChecked(),
Nan::New<String>(status.worker_thread_ok).ToLocalChecked()
);
Nan::Set(
status_object,
Nan::New<String>("workerInSize").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.worker_in_size))
);
Nan::Set(
status_object,
Nan::New<String>("workerInOk").ToLocalChecked(),
Nan::New<String>(status.worker_in_ok).ToLocalChecked()
);
Nan::Set(
status_object,
Nan::New<String>("workerOutSize").ToLocalChecked(),
Nan::New<Uint32>(static_cast<uint32_t>(status.worker_out_size))
);
Nan::Set(
status_object,
Nan::New<String>("workerOutOk").ToLocalChecked(),
Nan::New<String>(status.worker_out_ok).ToLocalChecked()
);
Nan::Set(
status_object,
Nan::New<String>("pollingThreadActive").ToLocalChecked(),
Nan::New<Boolean>(status.polling_thread_active)
);
info.GetReturnValue().Set(status_object);
}
void initialize(Local<Object> exports)
{
Nan::Set(
exports,
Nan::New<String>("configure").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked()
);
Nan::Set(
exports,
Nan::New<String>("watch").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked()
);
Nan::Set(
exports,
Nan::New<String>("unwatch").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked()
);
Nan::Set(
exports,
Nan::New<String>("status").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(status)).ToLocalChecked()
);
}
NODE_MODULE(watcher, initialize);
<|endoftext|> |
<commit_before>#define SECURITY_WIN32 1
#include <node.h>
#include <nan.h>
#include <v8.h>
#ifdef _WIN32
#include <Windows.h>
#include <Sddl.h>
#endif
namespace {
#ifdef _WIN32
std::string utf8_encode(const std::wstring &wstr) {
if (wstr.empty()) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int) wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int) wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
std::string GetLastErrorAsString() {
DWORD errorMessageID = ::GetLastError();
if (errorMessageID == 0)
return std::string();
DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD languageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);
LPSTR messageBuffer = NULL;
size_t size = FormatMessageA(flags, NULL, errorMessageID, languageId, (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
#endif
class GetSidForUser : public Nan::AsyncWorker {
public:
GetSidForUser(Nan::Callback *callback, const std::string &user)
: Nan::AsyncWorker(callback), user(user), sid("") { }
~GetSidForUser() { }
virtual void Execute() {
#ifdef _WIN32
LPCWSTR lpSystemName = NULL;
std::wstring swUser = std::wstring(user.begin(), user.end());
LPCWSTR lpAccountName = swUser.c_str();
DWORD cbSid = 256;
BYTE pSid[256];
DWORD cbDomain = 256 / sizeof(WCHAR);
WCHAR Domain[256];
SID_NAME_USE snu;
if (!LookupAccountNameW(lpSystemName, lpAccountName, pSid, &cbSid, Domain, &cbDomain, &snu)) {
SetErrorMessage(GetLastErrorAsString().c_str());
return;
}
if (IsValidSid(pSid) == FALSE) {
std::string msg = "No SID found for user \"" + user + "\"";
SetErrorMessage(msg.c_str());
return;
}
LPTSTR sidStr;
if (ConvertSidToStringSid(pSid, &sidStr) == FALSE) {
SetErrorMessage(GetLastErrorAsString().c_str());
return;
}
sid = utf8_encode(sidStr);
#else
SetErrorMessage("Your operating system is not supported.");
#endif
}
void HandleErrorCallback() {
Nan::HandleScope scope;
v8::Local <v8::Value> argv[] = { Nan::Error(ErrorMessage() )};
callback->Call(1, argv);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local <v8::Value> returnValue = Nan::New<v8::String>((char *) sid.data(), sid.size()).ToLocalChecked();
v8::Local <v8::Value> argv[] = { Nan::Null(), returnValue };
callback->Call(2, argv);
}
private:
std::string user;
std::string sid;
};
NAN_METHOD(getSidForUser) {
Nan::Utf8String user(info[0]->ToString());
Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>());
Nan::AsyncQueueWorker(new GetSidForUser(callback, *user));
}
NAN_MODULE_INIT(init) {
Nan::HandleScope scope;
Nan::SetMethod(target, "getSidForUser", getSidForUser);
}
NODE_MODULE(windows_sid, init)
} // anonymous namespace
<commit_msg>Check that provided SID belongs to a User.<commit_after>#define SECURITY_WIN32 1
#include <node.h>
#include <nan.h>
#include <v8.h>
#ifdef _WIN32
#include <Windows.h>
#include <Sddl.h>
#endif
namespace {
#ifdef _WIN32
std::string utf8_encode(const std::wstring &wstr) {
if (wstr.empty()) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int) wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int) wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
std::string GetLastErrorAsString() {
DWORD errorMessageID = ::GetLastError();
if (errorMessageID == 0)
return std::string();
DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD languageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);
LPSTR messageBuffer = NULL;
size_t size = FormatMessageA(flags, NULL, errorMessageID, languageId, (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
std::string getSidTypeString(SID_NAME_USE snu) {
switch(snu) {
case SidTypeUser:
return "User";
case SidTypeGroup:
return "Group";
case SidTypeDomain:
return "Domain";
case SidTypeAlias:
return "Alias";
case SidTypeWellKnownGroup:
return "WellKnownGroup";
case SidTypeDeletedAccount:
return "DeletedAccount";
case SidTypeInvalid:
return "Invalid";
case SidTypeUnknown:
return "Unknown";
case SidTypeComputer:
return "Computer";
case SidTypeLabel:
return "Label";
default:
return "Unknown";
}
}
#endif
class GetSidForUser : public Nan::AsyncWorker {
public:
GetSidForUser(Nan::Callback *callback, const std::string &user)
: Nan::AsyncWorker(callback), user(user), sid("") { }
~GetSidForUser() { }
virtual void Execute() {
#ifdef _WIN32
LPCWSTR lpSystemName = NULL;
std::wstring swUser = std::wstring(user.begin(), user.end());
LPCWSTR lpAccountName = swUser.c_str();
DWORD cbSid = 256;
BYTE pSid[256];
DWORD cbDomain = 256 / sizeof(WCHAR);
WCHAR Domain[256];
SID_NAME_USE snu;
if (!LookupAccountNameW(lpSystemName, lpAccountName, pSid, &cbSid, Domain, &cbDomain, &snu)) {
SetErrorMessage(GetLastErrorAsString().c_str());
return;
}
if (IsValidSid(pSid) == FALSE) {
std::string msg = "No SID found for user \"" + user + "\".";
SetErrorMessage(msg.c_str());
return;
}
if (snu != SidTypeUser) {
std::string msg = "The provided name must belong to a User, but the according SID is of type \"" + getSidTypeString(snu) + "\".";
SetErrorMessage(msg.c_str());
return;
}
LPTSTR sidStr;
if (ConvertSidToStringSid(pSid, &sidStr) == FALSE) {
SetErrorMessage(GetLastErrorAsString().c_str());
return;
}
sid = utf8_encode(sidStr);
#else
SetErrorMessage("Your operating system is not supported.");
#endif
}
void HandleErrorCallback() {
Nan::HandleScope scope;
v8::Local <v8::Value> argv[] = { Nan::Error(ErrorMessage() )};
callback->Call(1, argv);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local <v8::Value> returnValue = Nan::New<v8::String>((char *) sid.data(), sid.size()).ToLocalChecked();
v8::Local <v8::Value> argv[] = { Nan::Null(), returnValue };
callback->Call(2, argv);
}
private:
std::string user;
std::string sid;
};
NAN_METHOD(getSidForUser) {
Nan::Utf8String user(info[0]->ToString());
Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>());
Nan::AsyncQueueWorker(new GetSidForUser(callback, *user));
}
NAN_MODULE_INIT(init) {
Nan::HandleScope scope;
Nan::SetMethod(target, "getSidForUser", getSidForUser);
}
NODE_MODULE(windows_sid, init)
} // anonymous namespace
<|endoftext|> |
<commit_before>// extract.cpp : extract a posit from a float
//
// Copyright (C) 2017 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "stdafx.h"
#include "../../posit/posit.hpp"
#include "../../posit/posit_manipulators.hpp"
using namespace std;
using namespace sw::unum;
uint64_t regime_lookup[8] = {
0x0ULL,
0x1ULL,
0x2ULL
};
/*
Laid out as bits, floating point numbers look like this:
Single: SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM
Double: SEEEEEEE EEEEMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM
1. The sign bit is 0 for positive, 1 for negative.
2. The exponent base is two.
3. The exponent field contains 127 plus the true exponent for single-precision, or 1023 plus the true exponent for double precision.
4. The first bit of the mantissa is typically assumed to be 1.f, where f is the field of fraction bits.
*/
#define FLOAT_SIGN_MASK 0x80000000
#define FLOAT_EXPONENT_MASK 0x7F800000
#define FLOAT_MANTISSA_MASK 0x007FFFFF
#define FLOAT_ALTERNATING_BITS_SIGNIFICANT_5 0x00555555
#define FLOAT_ALTERNATING_BITS_SIGNIFICANT_A 0x002AAAAA
#define DOUBLE_SIGN_MASK 0x8000000000000000
#define DOUBLE_EXPONENT_MASK 0x7FF0000000000000
#define DOUBLE_MANTISSA_MASK 0x000FFFFFFFFFFFFF
#define DOUBLE_ALTERNATING_BITS_SIGNIFICANT_5 0x0005555555555555
#define DOUBLE_ALTERNATING_BITS_SIGNIFICANT_A 0x000AAAAAAAAAAAAA
/*
In the Standard C++ library there are several functions that manipulate these components:
in the header <cmath>
frexp returns the exponent in exponent and the fraction in the return value
Parameters
arg - floating point value
exp - pointer to integer value to store the exponent to
Return value
If arg is zero, returns zero and stores zero in *exp.
Otherwise (if arg is not zero), if no errors occur, returns the value x in the range (-1;-0.5], [0.5; 1)
and stores an integer value in *exp such that x×2(*exp)=arg
If the value to be stored in *exp is outside the range of int, the behavior is unspecified.
If arg is not a floating-point number, the behavior is unspecified.
float frexp(float in, int* exponent)
double frexp(double in, int* exponent)
long double frexp(long double in, int* exponent)
*/
template<size_t nbits, size_t es>
posit<nbits, es> extract(float f) {
constexpr size_t fbits = posit<nbits, es>::fbits;
posit<nbits, es> p;
bool _sign;
int _scale;
float _fr;
uint32_t _23b_fraction_without_hidden_bit;
extract_fp_components(f, _sign, _scale, _fr, _23b_fraction_without_hidden_bit);
std::bitset<fbits> _fraction = extract_23b_fraction<fbits>(_23b_fraction_without_hidden_bit);
p.convert(_sign, _scale, _fraction);
return p;
}
template<size_t nbits, size_t es>
posit<nbits, es> extract(double d) {
constexpr size_t fbits = posit<nbits, es>::fbits;
posit<nbits, es> p;
bool _sign;
int _scale;
float _fr;
uint32_t _52b_fraction_without_hidden_bit;
extract_fp_components(d, _sign, _scale, _fr, _52b_fraction_without_hidden_bit);
std::bitset<fbits> _fraction = extract_23b_fraction<fbits>(_52b_fraction_without_hidden_bit);
p.convert(_sign, _scale, _fraction);
return p;
}
int main()
try {
const size_t nbits = 32;
const size_t es = 2;
int nrOfFailedTestCases = 0;
posit<nbits,es> p;
bool sign;
int exponent;
float fr;
unsigned int fraction;
std::bitset<nbits> _fraction;
cout << "Conversion tests" << endl;
union {
float f;
unsigned int i;
} uf;
uf.i = FLOAT_ALTERNATING_BITS_SIGNIFICANT_5 | !FLOAT_SIGN_MASK;
cout << "Positive Regime: float value: " << uf.f << endl;
extract_fp_components(uf.f, sign, exponent, fr, fraction);
_fraction = extract_23b_fraction<nbits>(fraction);
cout << "f " << uf.f << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << fraction << endl;
p = extract<nbits, es>(uf.f);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
uf.i = FLOAT_ALTERNATING_BITS_SIGNIFICANT_5 | FLOAT_SIGN_MASK;
cout << "Negative Regime: float value: " << uf.f << endl;
extract_fp_components(uf.f, sign, exponent, fr, fraction);
_fraction = extract_23b_fraction<nbits>(fraction);
cout << "f " << uf.f << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << fraction << endl;
p = extract<nbits, es>(uf.f);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
union {
double d;
unsigned long long i;
} ud;
ud.i = DOUBLE_ALTERNATING_BITS_SIGNIFICANT_5 | !DOUBLE_SIGN_MASK;
cout << "Positive Regime: float value: " << ud.d << endl;
extract_fp_components(ud.d, sign, exponent, fr, fraction);
_fraction = extract_52b_fraction<nbits>(fraction);
cout << "d " << ud.d << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << fraction << endl;
p = extract<nbits, es>(ud.d);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
ud.i = DOUBLE_ALTERNATING_BITS_SIGNIFICANT_5 | DOUBLE_SIGN_MASK;
cout << "Negative Regime: float value: " << ud.d << endl;
extract_fp_components(ud.d, sign, exponent, fr, fraction);
_fraction = extract_52b_fraction<nbits>(fraction);
cout << "d " << ud.d << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << fraction << endl;
p = extract<nbits, es>(uf.f);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
// regime
// posit<3,#>
// -2 s-00
// -1 s-01
// 0 s-10
// 1 s-11
// posit<4,#>
// -3 s-000
// -2 s-001
// -1 s-01#
// 0 s-10#
// 1 s-110
// 2 s-111
// posit<5,#>
// -4 s-0000
// -3 s-0001
// -2 s-001#
// -1 s-01##
// 0 s-10##
// 1 s-110#
// 2 s-1110
// 3 s-1111
// posit<6,#>
// -5 s-00000
// -4 s-00001
// -3 s-0001#
// -2 s-001##
// -1 s-01###
// 0 s-10###
// 1 s-110##
// 2 s-1110#
// 3 s-11110
// 4 s-11111
// posit<7,#>
// -6 s-000000
// -5 s-000001
// -4 s-00001#
// -3 s-0001##
// -2 s-001###
// -1 s-01####
// 0 s-10####
// 1 s-110###
// 2 s-1110##
// 3 s-11110#
// 4 s-111110
// 5 s-111111
// posit<8,#>
// -7 s-0000000
// -6 s-0000001
// -5 s-000001#
// -4 s-00001##
// -3 s-0001###
// -2 s-001####
// -1 s-01#####
// 0 s-10#####
// 1 s-110####
// 2 s-1110###
// 3 s-11110##
// 4 s-111110#
// 5 s-1111110
// 6 s-1111111
return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
catch (char const* msg) {
cerr << msg << endl;
return EXIT_FAILURE;
}
catch (...) {
cerr << "Caught unknown exception" << endl;
return EXIT_FAILURE;
}
// REGIME BITS
// posit<3,#> posit<4,#> posit<5,#> posit<6,#> posit<7,#> posit<8,#>
// -7 s-0000000
// -6 s-000000 s-0000001
// -5 s-00000 s-000001 s-000001#
// -4 s-0000 s-00001 s-00001# s-00001##
// -3 s-000 s-0001 s-0001# s-0001## s-0001###
// -2 s-00 s-001 s-001# s-001## s-001### s-001####
// -1 s-01 s-01# s-01## s-01### s-01#### s-01#####
// 0 s-10 s-10# s-10## s-10### s-10#### s-10#####
// 1 s-11 s-110 s-110# s-110## s-110### s-110####
// 2 s-111 s-1110 s-1110# s-1110## s-1110###
// 3 s-1111 s-11110 s-11110# s-11110##
// 4 s-11111 s-111110 s-111110#
// 5 s-111111 s-1111110
// 6 s-1111111
<commit_msg>compilation warnings removed<commit_after>// extract.cpp : extract a posit from a float
//
// Copyright (C) 2017 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "stdafx.h"
#include "../../posit/posit.hpp"
#include "../../posit/posit_manipulators.hpp"
using namespace std;
using namespace sw::unum;
uint64_t regime_lookup[8] = {
0x0ULL,
0x1ULL,
0x2ULL
};
/*
Laid out as bits, floating point numbers look like this:
Single: SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM
Double: SEEEEEEE EEEEMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM
1. The sign bit is 0 for positive, 1 for negative.
2. The exponent base is two.
3. The exponent field contains 127 plus the true exponent for single-precision, or 1023 plus the true exponent for double precision.
4. The first bit of the mantissa is typically assumed to be 1.f, where f is the field of fraction bits.
*/
#define FLOAT_SIGN_MASK 0x80000000
#define FLOAT_EXPONENT_MASK 0x7F800000
#define FLOAT_MANTISSA_MASK 0x007FFFFF
#define FLOAT_ALTERNATING_BITS_SIGNIFICANT_5 0x00555555
#define FLOAT_ALTERNATING_BITS_SIGNIFICANT_A 0x002AAAAA
#define DOUBLE_SIGN_MASK 0x8000000000000000
#define DOUBLE_EXPONENT_MASK 0x7FF0000000000000
#define DOUBLE_MANTISSA_MASK 0x000FFFFFFFFFFFFF
#define DOUBLE_ALTERNATING_BITS_SIGNIFICANT_5 0x0005555555555555
#define DOUBLE_ALTERNATING_BITS_SIGNIFICANT_A 0x000AAAAAAAAAAAAA
/*
In the Standard C++ library there are several functions that manipulate these components:
in the header <cmath>
frexp returns the exponent in exponent and the fraction in the return value
Parameters
arg - floating point value
exp - pointer to integer value to store the exponent to
Return value
If arg is zero, returns zero and stores zero in *exp.
Otherwise (if arg is not zero), if no errors occur, returns the value x in the range (-1;-0.5], [0.5; 1)
and stores an integer value in *exp such that x×2(*exp)=arg
If the value to be stored in *exp is outside the range of int, the behavior is unspecified.
If arg is not a floating-point number, the behavior is unspecified.
float frexp(float in, int* exponent)
double frexp(double in, int* exponent)
long double frexp(long double in, int* exponent)
*/
template<size_t nbits, size_t es>
posit<nbits, es> extract(float f) {
constexpr size_t fbits = posit<nbits, es>::fbits;
posit<nbits, es> p;
bool _sign;
int _scale;
float _fr;
uint32_t _23b_fraction_without_hidden_bit;
extract_fp_components(f, _sign, _scale, _fr, _23b_fraction_without_hidden_bit);
std::bitset<fbits> _fraction = extract_23b_fraction<fbits>(_23b_fraction_without_hidden_bit);
p.convert(_sign, _scale, _fraction);
return p;
}
template<size_t nbits, size_t es>
posit<nbits, es> extract(double d) {
constexpr size_t fbits = posit<nbits, es>::fbits;
posit<nbits, es> p;
bool _sign;
int _scale;
double _fr;
unsigned long long _52b_fraction_without_hidden_bit;
extract_fp_components(d, _sign, _scale, _fr, _52b_fraction_without_hidden_bit);
std::bitset<fbits> _fraction = extract_52b_fraction<fbits>(_52b_fraction_without_hidden_bit);
p.convert(_sign, _scale, _fraction);
return p;
}
int main()
try {
const size_t nbits = 32;
const size_t es = 2;
int nrOfFailedTestCases = 0;
posit<nbits,es> p;
bool sign;
int exponent;
float ffr;
unsigned int ulfraction;
double dfr;
unsigned long long ullfraction;
std::bitset<nbits> _fraction;
cout << "Conversion tests" << endl;
union {
float f;
unsigned int i;
} uf;
uf.i = FLOAT_ALTERNATING_BITS_SIGNIFICANT_5 | !FLOAT_SIGN_MASK;
cout << "Positive Regime: float value: " << uf.f << endl;
extract_fp_components(uf.f, sign, exponent, ffr, ulfraction);
_fraction = extract_23b_fraction<nbits>(ulfraction);
cout << "f " << uf.f << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << ulfraction << endl;
p = extract<nbits, es>(uf.f);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
uf.i = FLOAT_ALTERNATING_BITS_SIGNIFICANT_5 | FLOAT_SIGN_MASK;
cout << "Negative Regime: float value: " << uf.f << endl;
extract_fp_components(uf.f, sign, exponent, ffr, ulfraction);
_fraction = extract_23b_fraction<nbits>(ulfraction);
cout << "f " << uf.f << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << ulfraction << endl;
p = extract<nbits, es>(uf.f);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
union {
double d;
unsigned long long i;
} ud;
ud.i = DOUBLE_ALTERNATING_BITS_SIGNIFICANT_5 | !DOUBLE_SIGN_MASK;
cout << "Positive Regime: float value: " << ud.d << endl;
extract_fp_components((double)ud.d, sign, exponent, dfr, ullfraction);
_fraction = extract_52b_fraction<nbits>(ullfraction);
cout << "d " << ud.d << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << ullfraction << endl;
p = extract<nbits, es>(ud.d);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
ud.i = DOUBLE_ALTERNATING_BITS_SIGNIFICANT_5 | DOUBLE_SIGN_MASK;
cout << "Negative Regime: float value: " << ud.d << endl;
extract_fp_components((double)ud.d, sign, exponent, dfr, ullfraction);
_fraction = extract_52b_fraction<nbits>(ullfraction);
cout << "d " << ud.d << " sign " << (sign ? -1 : 1) << " exponent " << exponent << " fraction " << ullfraction << endl;
p = extract<nbits, es>(uf.f);
cout << "posit<" << nbits << "," << es << "> = " << p << endl;
cout << "posit<" << nbits << "," << es << "> = " << components_to_string(p) << endl;
// regime
// posit<3,#>
// -2 s-00
// -1 s-01
// 0 s-10
// 1 s-11
// posit<4,#>
// -3 s-000
// -2 s-001
// -1 s-01#
// 0 s-10#
// 1 s-110
// 2 s-111
// posit<5,#>
// -4 s-0000
// -3 s-0001
// -2 s-001#
// -1 s-01##
// 0 s-10##
// 1 s-110#
// 2 s-1110
// 3 s-1111
// posit<6,#>
// -5 s-00000
// -4 s-00001
// -3 s-0001#
// -2 s-001##
// -1 s-01###
// 0 s-10###
// 1 s-110##
// 2 s-1110#
// 3 s-11110
// 4 s-11111
// posit<7,#>
// -6 s-000000
// -5 s-000001
// -4 s-00001#
// -3 s-0001##
// -2 s-001###
// -1 s-01####
// 0 s-10####
// 1 s-110###
// 2 s-1110##
// 3 s-11110#
// 4 s-111110
// 5 s-111111
// posit<8,#>
// -7 s-0000000
// -6 s-0000001
// -5 s-000001#
// -4 s-00001##
// -3 s-0001###
// -2 s-001####
// -1 s-01#####
// 0 s-10#####
// 1 s-110####
// 2 s-1110###
// 3 s-11110##
// 4 s-111110#
// 5 s-1111110
// 6 s-1111111
return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
catch (char const* msg) {
cerr << msg << endl;
return EXIT_FAILURE;
}
catch (...) {
cerr << "Caught unknown exception" << endl;
return EXIT_FAILURE;
}
// REGIME BITS
// posit<3,#> posit<4,#> posit<5,#> posit<6,#> posit<7,#> posit<8,#>
// -7 s-0000000
// -6 s-000000 s-0000001
// -5 s-00000 s-000001 s-000001#
// -4 s-0000 s-00001 s-00001# s-00001##
// -3 s-000 s-0001 s-0001# s-0001## s-0001###
// -2 s-00 s-001 s-001# s-001## s-001### s-001####
// -1 s-01 s-01# s-01## s-01### s-01#### s-01#####
// 0 s-10 s-10# s-10## s-10### s-10#### s-10#####
// 1 s-11 s-110 s-110# s-110## s-110### s-110####
// 2 s-111 s-1110 s-1110# s-1110## s-1110###
// 3 s-1111 s-11110 s-11110# s-11110##
// 4 s-11111 s-111110 s-111110#
// 5 s-111111 s-1111110
// 6 s-1111111
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define _POSIX_C_SOURCE 200809
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <string>
#include <iostream>
using namespace std;
#include "debug.h"
#include "repo.h"
#include "localrepo.h"
#include "server.h"
#include "fuse_cmd.h"
LocalRepo repository;
/********************************************************************
*
*
* Command Infrastructure
*
*
********************************************************************/
typedef struct Cmd {
const char *name;
const char *desc;
int (*cmd)(int argc, const char *argv[]);
void (*usage)(void);
} Cmd;
// repo.cc
int cmd_init(int argc, const char *argv[]);
int cmd_show(int argc, const char *argv[]);
int cmd_clone(int argc, const char *argv[]);
void usage_commit(void);
int cmd_commit(int argc, const char *argv[]);
//int cmd_oldcommit(int argc, const char *argv[]);
int cmd_snapshot(int argc, const char *argv[]);
int cmd_snapshots(int argc, const char *argv[]);
int cmd_checkout(int argc, const char *argv[]);
int cmd_pull(int argc, const char *argv[]);
int cmd_status(int argc, const char *argv[]);
int cmd_treediff(int argc, const char *argv[]);
int cmd_branches(int argc, const char *argv[]);
int cmd_branch(int argc, const char *argv[]);
int cmd_log(int argc, const char *argv[]);
int cmd_filelog(int argc, const char *argv[]);
int cmd_verify(int argc, const char *argv[]);
void usage_graft(void);
int cmd_graft(int argc, const char *argv[]);
int cmd_remote(int argc, const char *argv[]);
int cmd_catobj(int argc, const char *argv[]); // Debug
int cmd_listobj(int argc, const char *argv[]); // Debug
int cmd_findheads(int argc, const char *argv[]);
int cmd_rebuildrefs(int argc, const char *argv[]);
int cmd_rebuildindex(int argc, const char *argv[]);
int cmd_gc(int argc, const char *argv[]);
int cmd_refcount(int argc, const char *argv[]); // Debug
int cmd_stats(int argc, const char *argv[]); // Debug
int cmd_purgeobj(int argc, const char *argv[]); // Debug
int cmd_purgecommit(int argc, const char *argv[]);
int cmd_stripmetadata(int argc, const char *argv[]); // Debug
// server.cc
int cmd_sshserver(int argc, const char *argv[]);
// local
int cmd_sshclient(int argc, const char *argv[]); // Debug
#if !defined(WITHOUT_MDNS)
int cmd_mdnsserver(int argc, const char *argv[]); // Debug
#endif
int cmd_httpclient(int argc, const char *argv[]); // Debug
static int cmd_help(int argc, const char *argv[]);
static int cmd_selftest(int argc, const char *argv[]);
static Cmd commands[] = {
{
"init",
"Initialize the repository",
cmd_init,
NULL,
},
{
"show",
"Show repository information",
cmd_show,
NULL,
},
{
"status",
"Scan for changes since last commit",
cmd_status,
NULL,
},
{
"treediff",
"Compare two commits",
cmd_treediff,
NULL,
},
{
"branch",
"Set or print current branch",
cmd_branch,
NULL,
},
{
"branches",
"List all available branches",
cmd_branches,
NULL,
},
{
"clone",
"Clone a repository into the local directory",
cmd_clone,
NULL,
},
{
"commit",
"Commit changes into the repository",
cmd_commit,
usage_commit,
},
/*{
"oldcommit",
"Commit changes into the repository (pre-TreeDiff)",
cmd_oldcommit,
usage_commit,
},*/
{
"checkout",
"Checkout a revision of the repository",
cmd_checkout,
NULL,
},
{
"pull",
"Pull changes from a repository",
cmd_pull,
NULL,
},
{
"log",
"Display a log of commits to the repository",
cmd_log,
NULL,
},
{
"filelog",
"Display a log of commits to the repository for the specified file",
cmd_filelog,
NULL,
},
{
"verify",
"Verify the repository",
cmd_verify,
NULL,
},
{
"graft",
"Graft a subtree from a repository into the local repository",
cmd_graft,
usage_graft,
},
{
"findheads",
"Find lost heads",
cmd_findheads,
NULL,
},
{
"rebuildrefs",
"Rebuild references",
cmd_rebuildrefs,
NULL,
},
{
"rebuildindex",
"Rebuild index",
cmd_rebuildindex,
NULL,
},
{
"gc",
"Reclaim unused space",
cmd_gc,
NULL,
},
{
"snapshot",
"Create a repository snapshot",
cmd_snapshot,
NULL,
},
{
"snapshots",
"List all snapshots available in the repository",
cmd_snapshots,
NULL,
},
{
"remote",
"Remote connection management",
cmd_remote,
NULL,
},
/* Debugging */
{
"catobj",
"Print an object from the repository (DEBUG)",
cmd_catobj,
NULL,
},
{
"listobj",
"List objects (DEBUG)",
cmd_listobj,
NULL,
},
{
"refcount",
"Print the reference count for all objects (DEBUG)",
cmd_refcount,
NULL,
},
{
"stats",
"Print repository statistics (DEBUG)",
cmd_stats,
NULL,
},
{
"purgecommit",
"Purge commit",
cmd_purgecommit,
NULL,
},
{
"purgeobj",
"Purge object (DEBUG)",
cmd_purgeobj,
NULL,
},
{
"stripmetadata",
"Strip all object metadata including backreferences (DEBUG)",
cmd_stripmetadata,
NULL,
},
{
"sshserver",
"Run a simple stdin/out server, intended for SSH access",
cmd_sshserver,
NULL
},
{
"httpclient",
"Connect to a server via HTTP (DEBUG)",
cmd_httpclient,
NULL
},
{
"sshclient",
"Connect to a server via SSH (DEBUG)",
cmd_sshclient,
NULL
},
#if !defined(WITHOUT_MDNS)
{
"mdnsserver",
"Run the mDNS server (DEBUG)",
cmd_mdnsserver,
NULL
},
#endif
{
"selftest",
"Built-in unit tests (DEBUG)",
cmd_selftest,
NULL
},
{
"help",
"Show help for a given topic",
cmd_help,
NULL
},
{ NULL, NULL, NULL, NULL }
};
static int
lookupcmd(const char *cmd)
{
int i;
for (i = 0; commands[i].name != NULL; i++)
{
if (strcmp(commands[i].name, cmd) == 0)
return i;
}
return -1;
}
int util_selftest(void);
int LRUCache_selfTest(void);
static int
cmd_selftest(int argc, const char *argv[])
{
int result = 0;
result += util_selftest();
result += LRUCache_selfTest();
if (result != 0) {
cout << -result << " errors occurred." << endl;
}
return 0;
}
static int
cmd_help(int argc, const char *argv[])
{
int i = 0;
if (argc >= 2) {
i = lookupcmd(argv[1]);
if (i != -1 && commands[i].usage != NULL) {
commands[i].usage();
return 0;
}
if (i == -1) {
printf("Unknown command '%s'\n", argv[1]);
} else {
printf("No help for command '%s'\n", argv[1]);
return 0;
}
}
for (i = 0; commands[i].name != NULL; i++)
{
if (commands[i].desc != NULL)
printf("%-20s %s\n", commands[i].name, commands[i].desc);
}
return 0;
}
int
main(int argc, char *argv[])
{
int idx;
if (argc == 1) {
return cmd_help(0, NULL);
}
// Open the repository for all command except the following
bool has_repo = false;
if (strcmp(argv[1], "clone") != 0 &&
strcmp(argv[1], "help") != 0 &&
strcmp(argv[1], "init") != 0 &&
strcmp(argv[1], "selftest") != 0 &&
strcmp(argv[1], "sshserver") != 0)
{
if (repository.open()) {
has_repo = true;
if (ori_open_log(&repository) < 0) {
printf("Couldn't open log!\n");
exit(1);
}
}
}
else {
has_repo = true;
}
if (strcmp(argv[1], "status") == 0 ||
strcmp(argv[1], "commit") == 0) {
if (OF_ControlPath().size() > 0)
has_repo = true;
}
if (strcmp(argv[1], "clone") != 0 &&
strcmp(argv[1], "help") != 0 &&
strcmp(argv[1], "init") != 0 &&
strcmp(argv[1], "selftest") != 0 &&
strcmp(argv[1], "sshserver") != 0)
{
if (!has_repo) {
printf("No repository found!\n");
exit(1);
}
}
idx = lookupcmd(argv[1]);
if (idx == -1) {
printf("Unknown command '%s'\n", argv[1]);
cmd_help(0, NULL);
return 1;
}
LOG("Executing '%s'", argv[1]);
return commands[idx].cmd(argc-1, (const char **)argv+1);
}
<commit_msg>Alphabetizing command line help<commit_after>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define _POSIX_C_SOURCE 200809
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <string>
#include <iostream>
using namespace std;
#include "debug.h"
#include "repo.h"
#include "localrepo.h"
#include "server.h"
#include "fuse_cmd.h"
LocalRepo repository;
/********************************************************************
*
*
* Command Infrastructure
*
*
********************************************************************/
typedef struct Cmd {
const char *name;
const char *desc;
int (*cmd)(int argc, const char *argv[]);
void (*usage)(void);
} Cmd;
int cmd_init(int argc, const char *argv[]);
int cmd_show(int argc, const char *argv[]);
int cmd_clone(int argc, const char *argv[]);
void usage_commit(void);
int cmd_commit(int argc, const char *argv[]);
int cmd_snapshot(int argc, const char *argv[]);
int cmd_snapshots(int argc, const char *argv[]);
int cmd_checkout(int argc, const char *argv[]);
int cmd_pull(int argc, const char *argv[]);
int cmd_status(int argc, const char *argv[]);
int cmd_treediff(int argc, const char *argv[]);
int cmd_branches(int argc, const char *argv[]);
int cmd_branch(int argc, const char *argv[]);
int cmd_log(int argc, const char *argv[]);
int cmd_filelog(int argc, const char *argv[]);
int cmd_verify(int argc, const char *argv[]);
void usage_graft(void);
int cmd_graft(int argc, const char *argv[]);
int cmd_remote(int argc, const char *argv[]);
int cmd_catobj(int argc, const char *argv[]); // Debug
int cmd_listobj(int argc, const char *argv[]); // Debug
int cmd_findheads(int argc, const char *argv[]);
int cmd_rebuildrefs(int argc, const char *argv[]);
int cmd_rebuildindex(int argc, const char *argv[]);
int cmd_gc(int argc, const char *argv[]);
int cmd_refcount(int argc, const char *argv[]); // Debug
int cmd_stats(int argc, const char *argv[]); // Debug
int cmd_purgeobj(int argc, const char *argv[]); // Debug
int cmd_purgecommit(int argc, const char *argv[]);
int cmd_stripmetadata(int argc, const char *argv[]); // Debug
int cmd_sshserver(int argc, const char *argv[]); // Internal
int cmd_sshclient(int argc, const char *argv[]); // Debug
#if !defined(WITHOUT_MDNS)
int cmd_mdnsserver(int argc, const char *argv[]); // Debug
#endif
int cmd_httpclient(int argc, const char *argv[]); // Debug
static int cmd_help(int argc, const char *argv[]);
static int cmd_selftest(int argc, const char *argv[]);
static Cmd commands[] = {
{
"branch",
"Set or print current branch",
cmd_branch,
NULL,
},
{
"branches",
"List all available branches",
cmd_branches,
NULL,
},
{
"checkout",
"Checkout a revision of the repository",
cmd_checkout,
NULL,
},
{
"clone",
"Clone a repository into the local directory",
cmd_clone,
NULL,
},
{
"commit",
"Commit changes into the repository",
cmd_commit,
usage_commit,
},
{
"filelog",
"Display a log of commits to the repository for the specified file",
cmd_filelog,
NULL,
},
{
"findheads",
"Find lost heads",
cmd_findheads,
NULL,
},
{
"gc",
"Reclaim unused space",
cmd_gc,
NULL,
},
{
"graft",
"Graft a subtree from a repository into the local repository",
cmd_graft,
usage_graft,
},
{
"help",
"Show help for a given topic",
cmd_help,
NULL
},
{
"init",
"Initialize the repository",
cmd_init,
NULL,
},
{
"log",
"Display a log of commits to the repository",
cmd_log,
NULL,
},
{
"pull",
"Pull changes from a repository",
cmd_pull,
NULL,
},
{
"purgecommit",
"Purge commit",
cmd_purgecommit,
NULL,
},
{
"rebuildindex",
"Rebuild index",
cmd_rebuildindex,
NULL,
},
{
"rebuildrefs",
"Rebuild references",
cmd_rebuildrefs,
NULL,
},
{
"remote",
"Remote connection management",
cmd_remote,
NULL,
},
{
"show",
"Show repository information",
cmd_show,
NULL,
},
{
"snapshot",
"Create a repository snapshot",
cmd_snapshot,
NULL,
},
{
"snapshots",
"List all snapshots available in the repository",
cmd_snapshots,
NULL,
},
{
"status",
"Scan for changes since last commit",
cmd_status,
NULL,
},
{
"treediff",
"Compare two commits",
cmd_treediff,
NULL,
},
{
"verify",
"Verify the repository",
cmd_verify,
NULL,
},
/* Internal (always hidden) */
{
"sshserver",
NULL, // "Run a simple stdin/out server, intended for SSH access",
cmd_sshserver,
NULL
},
/* Debugging */
{
"catobj",
"Print an object from the repository (DEBUG)",
cmd_catobj,
NULL,
},
{
"listobj",
"List objects (DEBUG)",
cmd_listobj,
NULL,
},
{
"refcount",
"Print the reference count for all objects (DEBUG)",
cmd_refcount,
NULL,
},
{
"stats",
"Print repository statistics (DEBUG)",
cmd_stats,
NULL,
},
{
"purgeobj",
"Purge object (DEBUG)",
cmd_purgeobj,
NULL,
},
{
"stripmetadata",
"Strip all object metadata including backreferences (DEBUG)",
cmd_stripmetadata,
NULL,
},
{
"httpclient",
"Connect to a server via HTTP (DEBUG)",
cmd_httpclient,
NULL
},
{
"sshclient",
"Connect to a server via SSH (DEBUG)",
cmd_sshclient,
NULL
},
#if !defined(WITHOUT_MDNS)
{
"mdnsserver",
"Run the mDNS server (DEBUG)",
cmd_mdnsserver,
NULL
},
#endif
{
"selftest",
"Built-in unit tests (DEBUG)",
cmd_selftest,
NULL
},
{ NULL, NULL, NULL, NULL }
};
static int
lookupcmd(const char *cmd)
{
int i;
for (i = 0; commands[i].name != NULL; i++)
{
if (strcmp(commands[i].name, cmd) == 0)
return i;
}
return -1;
}
int util_selftest(void);
int LRUCache_selfTest(void);
static int
cmd_selftest(int argc, const char *argv[])
{
int result = 0;
result += util_selftest();
result += LRUCache_selfTest();
if (result != 0) {
cout << -result << " errors occurred." << endl;
}
return 0;
}
static int
cmd_help(int argc, const char *argv[])
{
int i = 0;
if (argc >= 2) {
i = lookupcmd(argv[1]);
if (i != -1 && commands[i].usage != NULL) {
commands[i].usage();
return 0;
}
if (i == -1) {
printf("Unknown command '%s'\n", argv[1]);
} else {
printf("No help for command '%s'\n", argv[1]);
return 0;
}
}
for (i = 0; commands[i].name != NULL; i++)
{
if (commands[i].desc != NULL)
printf("%-20s %s\n", commands[i].name, commands[i].desc);
}
return 0;
}
int
main(int argc, char *argv[])
{
int idx;
if (argc == 1) {
return cmd_help(0, NULL);
}
// Open the repository for all command except the following
bool has_repo = false;
if (strcmp(argv[1], "clone") != 0 &&
strcmp(argv[1], "help") != 0 &&
strcmp(argv[1], "init") != 0 &&
strcmp(argv[1], "selftest") != 0 &&
strcmp(argv[1], "sshserver") != 0)
{
if (repository.open()) {
has_repo = true;
if (ori_open_log(&repository) < 0) {
printf("Couldn't open log!\n");
exit(1);
}
}
}
else {
has_repo = true;
}
if (strcmp(argv[1], "status") == 0 ||
strcmp(argv[1], "commit") == 0) {
if (OF_ControlPath().size() > 0)
has_repo = true;
}
if (strcmp(argv[1], "clone") != 0 &&
strcmp(argv[1], "help") != 0 &&
strcmp(argv[1], "init") != 0 &&
strcmp(argv[1], "selftest") != 0 &&
strcmp(argv[1], "sshserver") != 0)
{
if (!has_repo) {
printf("No repository found!\n");
exit(1);
}
}
idx = lookupcmd(argv[1]);
if (idx == -1) {
printf("Unknown command '%s'\n", argv[1]);
cmd_help(0, NULL);
return 1;
}
LOG("Executing '%s'", argv[1]);
return commands[idx].cmd(argc-1, (const char **)argv+1);
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "Template.h"
#include "template_syntax.h"
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
Template::~Template()
{
multimap<string,Attribute *>::iterator it;
for ( it = attributes.begin(); it != attributes.end(); it++)
{
delete it->second;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
pthread_mutex_t Template::mutex = PTHREAD_MUTEX_INITIALIZER;
extern "C"
{
typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern FILE *template_in, *template_out;
int template_parse(Template * tmpl, char ** errmsg);
int template_lex_destroy();
YY_BUFFER_STATE template__scan_string(const char * str);
void template__delete_buffer(YY_BUFFER_STATE);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::parse(const char * filename, char **error_msg)
{
int rc;
pthread_mutex_lock(&mutex);
*error_msg = 0;
template_in = fopen (filename, "r");
if ( template_in == 0 )
{
goto error_open;
}
rc = template_parse(this,error_msg);
fclose(template_in);
template_lex_destroy();
pthread_mutex_unlock(&mutex);
return rc;
error_open:
*error_msg = strdup("Error opening template file");
pthread_mutex_unlock(&mutex);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::parse(const string &parse_str, char **error_msg)
{
YY_BUFFER_STATE str_buffer = 0;
const char * str;
int rc;
pthread_mutex_lock(&mutex);
*error_msg = 0;
str = parse_str.c_str();
str_buffer = template__scan_string(str);
if (str_buffer == 0)
{
goto error_yy;
}
rc = template_parse(this,error_msg);
template__delete_buffer(str_buffer);
template_lex_destroy();
pthread_mutex_unlock(&mutex);
return rc;
error_yy:
*error_msg=strdup("Error setting scan buffer");
pthread_mutex_unlock(&mutex);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::parse_str_or_xml(const string &parse_str, string& error_msg)
{
int rc;
if ( parse_str[0] == '<' )
{
rc = from_xml(parse_str);
if ( rc != 0 )
{
error_msg = "Parse error: XML Template malformed.";
}
}
else
{
char * error_char = 0;
ostringstream oss;
oss << parse_str << endl;
rc = parse(oss.str(), &error_char);
if ( rc != 0 )
{
ostringstream oss;
oss << "Parse error";
if (error_char != 0)
{
oss << ": " << error_char;
free(error_char);
}
else
{
oss << ".";
}
error_msg = oss.str();
}
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::marshall(string &str, const char delim)
{
multimap<string,Attribute *>::iterator it;
string * attr;
for(it=attributes.begin(),str="";it!=attributes.end();it++)
{
attr = it->second->marshall();
if ( attr == 0 )
{
continue;
}
str += it->first + "=" + *attr + delim;
delete attr;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::set(Attribute * attr)
{
if ( replace_mode == true )
{
multimap<string, Attribute *>::iterator i;
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
index = attributes.equal_range(attr->name());
for ( i = index.first; i != index.second; i++)
{
delete i->second;
}
attributes.erase(attr->name());
}
attributes.insert(make_pair(attr->name(),attr));
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::replace(const string& name, const string& value)
{
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
index = attributes.equal_range(name);
if (index.first != index.second )
{
multimap<string, Attribute *>::iterator i;
for ( i = index.first; i != index.second; i++)
{
Attribute * attr = i->second;
delete attr;
}
attributes.erase(index.first, index.second);
}
SingleAttribute * sattr = new SingleAttribute(name,value);
attributes.insert(make_pair(sattr->name(), sattr));
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::remove(const string& name, vector<Attribute *>& values)
{
multimap<string, Attribute *>::iterator i;
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(i->second);
}
attributes.erase(index.first, index.second);
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::erase(const string& name)
{
multimap<string, Attribute *>::iterator i;
pair<
multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator
> index;
int j;
index = attributes.equal_range(name);
if (index.first == index.second )
{
return 0;
}
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
Attribute * attr = i->second;
delete attr;
}
attributes.erase(index.first,index.second);
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
Attribute * Template::remove(Attribute * att)
{
multimap<string, Attribute *>::iterator i;
pair<
multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator
> index;
index = attributes.equal_range( att->name() );
for ( i = index.first; i != index.second; i++ )
{
if ( i->second == att )
{
attributes.erase(i);
return att;
}
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::get(
const string& name,
vector<const Attribute*>& values) const
{
multimap<string, Attribute *>::const_iterator i;
pair<multimap<string, Attribute *>::const_iterator,
multimap<string, Attribute *>::const_iterator> index;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(i->second);
}
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::get(
const string& name,
vector<Attribute*>& values)
{
multimap<string, Attribute *>::iterator i;
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(i->second);
}
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::get(
const string& name,
string& value) const
{
vector<const Attribute *> attrs;
const SingleAttribute * sattr;
int rc;
rc = get(name,attrs);
if (rc == 0)
{
value = "";
return;
}
sattr = dynamic_cast<const SingleAttribute *>(attrs[0]);
if ( sattr != 0 )
{
value = sattr->value();
}
else
{
value="";
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Template::get(
const string& name,
int& value) const
{
string sval;
get(name, sval);
if ( sval == "" )
{
value = 0;
return false;
}
istringstream iss(sval);
iss >> value;
return true;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Template::to_xml(string& xml) const
{
multimap<string,Attribute *>::const_iterator it;
ostringstream oss;
string * s;
oss << "<" << xml_root << ">";
for ( it = attributes.begin(); it!=attributes.end(); it++)
{
s = it->second->to_xml();
oss << *s;
delete s;
}
oss << "</" << xml_root << ">";
xml = oss.str();
return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Template::to_str(string& str) const
{
ostringstream os;
multimap<string,Attribute *>::const_iterator it;
string * s;
for ( it = attributes.begin(); it!=attributes.end(); it++)
{
s = it->second->marshall(",");
os << it->first << separator << *s << endl;
delete s;
}
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator << (ostream& os, const Template& t)
{
string str;
os << t.to_str(str);
return os;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
Attribute * Template::single_xml_att(const xmlNode * node)
{
Attribute * attr = 0;
xmlNode * child = node->children;
if( child->next == 0 && child != 0 &&
(child->type == XML_TEXT_NODE ||
child->type == XML_CDATA_SECTION_NODE))
{
attr = new SingleAttribute(
reinterpret_cast<const char *>(node->name),
reinterpret_cast<const char *>(child->content) );
}
return attr;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
Attribute * Template::vector_xml_att(const xmlNode * node)
{
VectorAttribute * attr = 0;
xmlNode * child = node->children;
xmlNode * grandchild = 0;
while(child != 0 && child->type != XML_ELEMENT_NODE)
{
child = child->next;
}
if(child != 0)
{
attr = new VectorAttribute(
reinterpret_cast<const char *>(node->name));
for(child = child; child != 0; child = child->next)
{
grandchild = child->children;
if( grandchild != 0 && (grandchild->type == XML_TEXT_NODE ||
grandchild->type == XML_CDATA_SECTION_NODE))
{
attr->replace(
reinterpret_cast<const char *>(child->name),
reinterpret_cast<const char *>(grandchild->content) );
}
}
}
return attr;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Template::from_xml(const string &xml_str)
{
xmlDocPtr xml_doc = 0;
xmlNode * root_element;
// Parse xml string as libxml document
xml_doc = xmlParseMemory (xml_str.c_str(),xml_str.length());
if (xml_doc == 0) // Error parsing XML Document
{
return -1;
}
// Get the <TEMPLATE> element
root_element = xmlDocGetRootElement(xml_doc);
if( root_element == 0 )
{
return -1;
}
rebuild_attributes(root_element);
xmlFreeDoc(xml_doc);
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Template::from_xml_node(const xmlNodePtr node)
{
if (node == 0)
{
return -1;
}
rebuild_attributes(node);
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
void Template::rebuild_attributes(const xmlNode * root_element)
{
xmlNode * cur_node = 0;
Attribute * attr;
//Clear the template if not empty
if (!attributes.empty())
{
multimap<string,Attribute *>::iterator it;
for ( it = attributes.begin(); it != attributes.end(); it++)
{
delete it->second;
}
attributes.clear();
}
// Get the root's children and try to build attributes.
for (cur_node = root_element->children;
cur_node != 0;
cur_node = cur_node->next)
{
if (cur_node->type == XML_ELEMENT_NODE)
{
// Try to build a single attr.
attr = single_xml_att(cur_node);
if(attr == 0) // The xml element wasn't a single attr.
{
// Try with a vector attr.
attr = vector_xml_att(cur_node);
}
if(attr != 0)
{
set(attr);
}
}
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::set_restricted_attributes( vector<const Attribute *>& rattrs,
vector<string>& restricted_attributes)
{
const SingleAttribute * sattr;
string attr;
for (unsigned int i = 0 ; i < rattrs.size() ; i++ )
{
sattr = static_cast<const SingleAttribute *>(rattrs[i]);
attr = sattr->value();
transform (attr.begin(),attr.end(),attr.begin(),(int(*)(int))toupper);
restricted_attributes.push_back(attr);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Template::check(string& rs_attr, const vector<string> &restricted_attributes)
{
size_t pos;
string avector, vattr;
vector<const Attribute *> values;
for (unsigned int i=0; i < restricted_attributes.size(); i++)
{
pos = restricted_attributes[i].find("/");
if (pos != string::npos) //Vector Attribute
{
int num;
avector = restricted_attributes[i].substr(0,pos);
vattr = restricted_attributes[i].substr(pos+1);
if ((num = get(avector,values)) > 0 ) //Template contains the attr
{
const VectorAttribute * attr;
for (int j=0; j<num ; j++ )
{
attr = dynamic_cast<const VectorAttribute *>(values[j]);
if (attr == 0)
{
continue;
}
if ( !attr->vector_value(vattr.c_str()).empty() )
{
rs_attr = restricted_attributes[i];
return true;
}
}
}
}
else //Single Attribute
{
if (get(restricted_attributes[i],values) > 0 )
{
rs_attr = restricted_attributes[i];
return true;
}
}
}
return false;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<commit_msg>Revert "bug #1258: Adds a endl character to any string before parsing"<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "Template.h"
#include "template_syntax.h"
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
Template::~Template()
{
multimap<string,Attribute *>::iterator it;
for ( it = attributes.begin(); it != attributes.end(); it++)
{
delete it->second;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
pthread_mutex_t Template::mutex = PTHREAD_MUTEX_INITIALIZER;
extern "C"
{
typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern FILE *template_in, *template_out;
int template_parse(Template * tmpl, char ** errmsg);
int template_lex_destroy();
YY_BUFFER_STATE template__scan_string(const char * str);
void template__delete_buffer(YY_BUFFER_STATE);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::parse(const char * filename, char **error_msg)
{
int rc;
pthread_mutex_lock(&mutex);
*error_msg = 0;
template_in = fopen (filename, "r");
if ( template_in == 0 )
{
goto error_open;
}
rc = template_parse(this,error_msg);
fclose(template_in);
template_lex_destroy();
pthread_mutex_unlock(&mutex);
return rc;
error_open:
*error_msg = strdup("Error opening template file");
pthread_mutex_unlock(&mutex);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::parse(const string &parse_str, char **error_msg)
{
YY_BUFFER_STATE str_buffer = 0;
const char * str;
int rc;
pthread_mutex_lock(&mutex);
*error_msg = 0;
str = parse_str.c_str();
str_buffer = template__scan_string(str);
if (str_buffer == 0)
{
goto error_yy;
}
rc = template_parse(this,error_msg);
template__delete_buffer(str_buffer);
template_lex_destroy();
pthread_mutex_unlock(&mutex);
return rc;
error_yy:
*error_msg=strdup("Error setting scan buffer");
pthread_mutex_unlock(&mutex);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::parse_str_or_xml(const string &parse_str, string& error_msg)
{
int rc;
if ( parse_str[0] == '<' )
{
rc = from_xml(parse_str);
if ( rc != 0 )
{
error_msg = "Parse error: XML Template malformed.";
}
}
else
{
char * error_char = 0;
rc = parse(parse_str, &error_char);
if ( rc != 0 )
{
ostringstream oss;
oss << "Parse error";
if (error_char != 0)
{
oss << ": " << error_char;
free(error_char);
}
else
{
oss << ".";
}
error_msg = oss.str();
}
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::marshall(string &str, const char delim)
{
multimap<string,Attribute *>::iterator it;
string * attr;
for(it=attributes.begin(),str="";it!=attributes.end();it++)
{
attr = it->second->marshall();
if ( attr == 0 )
{
continue;
}
str += it->first + "=" + *attr + delim;
delete attr;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::set(Attribute * attr)
{
if ( replace_mode == true )
{
multimap<string, Attribute *>::iterator i;
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
index = attributes.equal_range(attr->name());
for ( i = index.first; i != index.second; i++)
{
delete i->second;
}
attributes.erase(attr->name());
}
attributes.insert(make_pair(attr->name(),attr));
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::replace(const string& name, const string& value)
{
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
index = attributes.equal_range(name);
if (index.first != index.second )
{
multimap<string, Attribute *>::iterator i;
for ( i = index.first; i != index.second; i++)
{
Attribute * attr = i->second;
delete attr;
}
attributes.erase(index.first, index.second);
}
SingleAttribute * sattr = new SingleAttribute(name,value);
attributes.insert(make_pair(sattr->name(), sattr));
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::remove(const string& name, vector<Attribute *>& values)
{
multimap<string, Attribute *>::iterator i;
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(i->second);
}
attributes.erase(index.first, index.second);
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::erase(const string& name)
{
multimap<string, Attribute *>::iterator i;
pair<
multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator
> index;
int j;
index = attributes.equal_range(name);
if (index.first == index.second )
{
return 0;
}
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
Attribute * attr = i->second;
delete attr;
}
attributes.erase(index.first,index.second);
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
Attribute * Template::remove(Attribute * att)
{
multimap<string, Attribute *>::iterator i;
pair<
multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator
> index;
index = attributes.equal_range( att->name() );
for ( i = index.first; i != index.second; i++ )
{
if ( i->second == att )
{
attributes.erase(i);
return att;
}
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::get(
const string& name,
vector<const Attribute*>& values) const
{
multimap<string, Attribute *>::const_iterator i;
pair<multimap<string, Attribute *>::const_iterator,
multimap<string, Attribute *>::const_iterator> index;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(i->second);
}
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Template::get(
const string& name,
vector<Attribute*>& values)
{
multimap<string, Attribute *>::iterator i;
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(i->second);
}
return j;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::get(
const string& name,
string& value) const
{
vector<const Attribute *> attrs;
const SingleAttribute * sattr;
int rc;
rc = get(name,attrs);
if (rc == 0)
{
value = "";
return;
}
sattr = dynamic_cast<const SingleAttribute *>(attrs[0]);
if ( sattr != 0 )
{
value = sattr->value();
}
else
{
value="";
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Template::get(
const string& name,
int& value) const
{
string sval;
get(name, sval);
if ( sval == "" )
{
value = 0;
return false;
}
istringstream iss(sval);
iss >> value;
return true;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Template::to_xml(string& xml) const
{
multimap<string,Attribute *>::const_iterator it;
ostringstream oss;
string * s;
oss << "<" << xml_root << ">";
for ( it = attributes.begin(); it!=attributes.end(); it++)
{
s = it->second->to_xml();
oss << *s;
delete s;
}
oss << "</" << xml_root << ">";
xml = oss.str();
return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Template::to_str(string& str) const
{
ostringstream os;
multimap<string,Attribute *>::const_iterator it;
string * s;
for ( it = attributes.begin(); it!=attributes.end(); it++)
{
s = it->second->marshall(",");
os << it->first << separator << *s << endl;
delete s;
}
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator << (ostream& os, const Template& t)
{
string str;
os << t.to_str(str);
return os;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
Attribute * Template::single_xml_att(const xmlNode * node)
{
Attribute * attr = 0;
xmlNode * child = node->children;
if( child->next == 0 && child != 0 &&
(child->type == XML_TEXT_NODE ||
child->type == XML_CDATA_SECTION_NODE))
{
attr = new SingleAttribute(
reinterpret_cast<const char *>(node->name),
reinterpret_cast<const char *>(child->content) );
}
return attr;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
Attribute * Template::vector_xml_att(const xmlNode * node)
{
VectorAttribute * attr = 0;
xmlNode * child = node->children;
xmlNode * grandchild = 0;
while(child != 0 && child->type != XML_ELEMENT_NODE)
{
child = child->next;
}
if(child != 0)
{
attr = new VectorAttribute(
reinterpret_cast<const char *>(node->name));
for(child = child; child != 0; child = child->next)
{
grandchild = child->children;
if( grandchild != 0 && (grandchild->type == XML_TEXT_NODE ||
grandchild->type == XML_CDATA_SECTION_NODE))
{
attr->replace(
reinterpret_cast<const char *>(child->name),
reinterpret_cast<const char *>(grandchild->content) );
}
}
}
return attr;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Template::from_xml(const string &xml_str)
{
xmlDocPtr xml_doc = 0;
xmlNode * root_element;
// Parse xml string as libxml document
xml_doc = xmlParseMemory (xml_str.c_str(),xml_str.length());
if (xml_doc == 0) // Error parsing XML Document
{
return -1;
}
// Get the <TEMPLATE> element
root_element = xmlDocGetRootElement(xml_doc);
if( root_element == 0 )
{
return -1;
}
rebuild_attributes(root_element);
xmlFreeDoc(xml_doc);
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Template::from_xml_node(const xmlNodePtr node)
{
if (node == 0)
{
return -1;
}
rebuild_attributes(node);
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
void Template::rebuild_attributes(const xmlNode * root_element)
{
xmlNode * cur_node = 0;
Attribute * attr;
//Clear the template if not empty
if (!attributes.empty())
{
multimap<string,Attribute *>::iterator it;
for ( it = attributes.begin(); it != attributes.end(); it++)
{
delete it->second;
}
attributes.clear();
}
// Get the root's children and try to build attributes.
for (cur_node = root_element->children;
cur_node != 0;
cur_node = cur_node->next)
{
if (cur_node->type == XML_ELEMENT_NODE)
{
// Try to build a single attr.
attr = single_xml_att(cur_node);
if(attr == 0) // The xml element wasn't a single attr.
{
// Try with a vector attr.
attr = vector_xml_att(cur_node);
}
if(attr != 0)
{
set(attr);
}
}
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::set_restricted_attributes( vector<const Attribute *>& rattrs,
vector<string>& restricted_attributes)
{
const SingleAttribute * sattr;
string attr;
for (unsigned int i = 0 ; i < rattrs.size() ; i++ )
{
sattr = static_cast<const SingleAttribute *>(rattrs[i]);
attr = sattr->value();
transform (attr.begin(),attr.end(),attr.begin(),(int(*)(int))toupper);
restricted_attributes.push_back(attr);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Template::check(string& rs_attr, const vector<string> &restricted_attributes)
{
size_t pos;
string avector, vattr;
vector<const Attribute *> values;
for (unsigned int i=0; i < restricted_attributes.size(); i++)
{
pos = restricted_attributes[i].find("/");
if (pos != string::npos) //Vector Attribute
{
int num;
avector = restricted_attributes[i].substr(0,pos);
vattr = restricted_attributes[i].substr(pos+1);
if ((num = get(avector,values)) > 0 ) //Template contains the attr
{
const VectorAttribute * attr;
for (int j=0; j<num ; j++ )
{
attr = dynamic_cast<const VectorAttribute *>(values[j]);
if (attr == 0)
{
continue;
}
if ( !attr->vector_value(vattr.c_str()).empty() )
{
rs_attr = restricted_attributes[i];
return true;
}
}
}
}
else //Single Attribute
{
if (get(restricted_attributes[i],values) > 0 )
{
rs_attr = restricted_attributes[i];
return true;
}
}
}
return false;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<|endoftext|> |
<commit_before>#pragma once
#ifdef AUTOCXXPY_INCLUDED_PYBIND11
#include <unordered_map>
namespace c2py
{
using object_store = std::unordered_map<std::string, pybind11::object>;
class cross_assign
{
public:
void record_assign(pybind11::object& scope,
const std::string& name_in_scope,
const std::string& full_name,
const std::string& target)
{
_delay_assings.emplace_back(scope, name_in_scope, full_name, target);
}
// make all recored assign available
void process_assign(object_store& os)
{
for (auto& [scope, name_in_scope, full_name, target] : _delay_assings)
{
if (target.length() > 0)
{
if (os.count(target) == 0)
{
if (target[0] == ':')
target = target.substr(2);
else
target = std::string("::") + target;
}
auto target_obj = os.at(target);
scope.attr(name_in_scope.c_str()) = target_obj;
os.emplace(full_name, target_obj);
}
}
}
void clear()
{
_delay_assings.clear();
}
private:
std::vector<std::tuple<pybind11::object, std::string, std::string, std::string>> _delay_assings;
};
}
#endif
<commit_msg>Delete cross_assign.hpp<commit_after><|endoftext|> |
<commit_before>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static WalletModel *walletmodel;
static ClientModel *clientmodel;
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & wxMODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
void MainFrameRepaint()
{
if(clientmodel)
QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection);
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection);
}
void AddressBookRepaint()
{
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection);
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifdef WIN32
#define strncasecmp strnicmp
#endif
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if(mq.try_send(strURI, strlen(strURI), 0))
exit(0);
else
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
break;
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Bitcoin");
app.setOrganizationDomain("bitcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Bitcoin-Qt-testnet");
else
app.setApplicationName("Bitcoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
BitcoinGUI window;
guiref = &window;
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
clientmodel = &clientModel;
WalletModel walletModel(pwalletMain, &optionsModel);
walletmodel = &walletModel;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
}
}
}
#endif
app.exec();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
clientmodel = 0;
walletmodel = 0;
}
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>Hide UI immediately after leaving the main loop.<commit_after>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static WalletModel *walletmodel;
static ClientModel *clientmodel;
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & wxMODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
void MainFrameRepaint()
{
if(clientmodel)
QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection);
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection);
}
void AddressBookRepaint()
{
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection);
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifdef WIN32
#define strncasecmp strnicmp
#endif
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if(mq.try_send(strURI, strlen(strURI), 0))
exit(0);
else
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
break;
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Bitcoin");
app.setOrganizationDomain("bitcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Bitcoin-Qt-testnet");
else
app.setApplicationName("Bitcoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
BitcoinGUI window;
guiref = &window;
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
clientmodel = &clientModel;
WalletModel walletModel(pwalletMain, &optionsModel);
walletmodel = &walletModel;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
clientmodel = 0;
walletmodel = 0;
}
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|> |
<commit_before>/*
* W.J. van der Laan 2011
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "headers.h"
#include "init.h"
#include <QApplication>
#include <QMessageBox>
#include <QThread>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
// Need a global reference for the notifications to find the GUI
BitcoinGUI *guiref;
QSplashScreen *splashref;
int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
// Message from main thread
if(guiref)
{
guiref->error(QString::fromStdString(caption),
QString::fromStdString(message));
}
else
{
QMessageBox::critical(0, QString::fromStdString(caption),
QString::fromStdString(message),
QMessageBox::Ok, QMessageBox::Ok);
}
return 4;
}
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
// Message from network thread
if(guiref)
{
QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
// Call slot on GUI thread.
// If called from another thread, use a blocking QueuedConnection.
Qt::ConnectionType connectionType = Qt::DirectConnection;
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
connectionType = Qt::BlockingQueuedConnection;
}
QMetaObject::invokeMethod(guiref, "askFee", connectionType,
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void CalledSetStatusBar(const std::string& strText, int nField)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void UIThreadCall(boost::function0<void> fn)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void MainFrameRepaint()
{
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
int main(int argc, char *argv[])
{
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Load language files for system locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
QString lang_territory = QLocale::system().name(); // "en_US"
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_')); // "en"
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
if (!qtTranslatorBase.isEmpty())
app.installTranslator(&qtTranslatorBase);
qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
if (!qtTranslator.isEmpty())
app.installTranslator(&qtTranslator);
translatorBase.load(":/translations/"+lang);
if (!translatorBase.isEmpty())
app.installTranslator(&translatorBase);
translator.load(":/translations/"+lang_territory);
if (!translator.isEmpty())
app.installTranslator(&translator);
app.setApplicationName(QApplication::translate("main", "Bitcoin-Qt"));
QSplashScreen splash(QPixmap(":/images/splash"), 0);
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that BitcoinGUI is cleaned up properly before
// calling Shutdown().
BitcoinGUI window;
splash.finish(&window);
OptionsModel optionsModel(pwalletMain);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
guiref = &window;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
window.show();
app.exec();
guiref = 0;
}
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
PrintException(&e, "Runaway exception");
} catch (...) {
PrintException(NULL, "Runaway exception");
}
return 0;
}
<commit_msg>Implement -min option to start minimized<commit_after>/*
* W.J. van der Laan 2011
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "headers.h"
#include "init.h"
#include <QApplication>
#include <QMessageBox>
#include <QThread>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
// Need a global reference for the notifications to find the GUI
BitcoinGUI *guiref;
QSplashScreen *splashref;
int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
// Message from main thread
if(guiref)
{
guiref->error(QString::fromStdString(caption),
QString::fromStdString(message));
}
else
{
QMessageBox::critical(0, QString::fromStdString(caption),
QString::fromStdString(message),
QMessageBox::Ok, QMessageBox::Ok);
}
return 4;
}
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
// Message from network thread
if(guiref)
{
QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
// Call slot on GUI thread.
// If called from another thread, use a blocking QueuedConnection.
Qt::ConnectionType connectionType = Qt::DirectConnection;
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
connectionType = Qt::BlockingQueuedConnection;
}
QMetaObject::invokeMethod(guiref, "askFee", connectionType,
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void CalledSetStatusBar(const std::string& strText, int nField)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void UIThreadCall(boost::function0<void> fn)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void MainFrameRepaint()
{
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
int main(int argc, char *argv[])
{
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Load language files for system locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
QString lang_territory = QLocale::system().name(); // "en_US"
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_')); // "en"
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
if (!qtTranslatorBase.isEmpty())
app.installTranslator(&qtTranslatorBase);
qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
if (!qtTranslator.isEmpty())
app.installTranslator(&qtTranslator);
translatorBase.load(":/translations/"+lang);
if (!translatorBase.isEmpty())
app.installTranslator(&translatorBase);
translator.load(":/translations/"+lang_territory);
if (!translator.isEmpty())
app.installTranslator(&translator);
app.setApplicationName(QApplication::translate("main", "Bitcoin-Qt"));
QSplashScreen splash(QPixmap(":/images/splash"), 0);
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that BitcoinGUI is cleaned up properly before
// calling Shutdown() in case of exceptions.
BitcoinGUI window;
splash.finish(&window);
OptionsModel optionsModel(pwalletMain);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
guiref = &window;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
app.exec();
guiref = 0;
}
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
PrintException(&e, "Runaway exception");
} catch (...) {
PrintException(NULL, "Runaway exception");
}
return 0;
}
<|endoftext|> |
<commit_before>// LoginMng.cpp : t@C
//
#include "stdafx.h"
#include "MZ3.h"
#include "LoginMng.h"
#include "bf.h"
#include "Winsock2.h"
#include "util.h"
/// IvVf[^
namespace option {
#define CRYPT_KEY _T("Mixi_browser_for_W-ZERO3")
// Login
Login::Login()
{
m_ownerId = _T("");
}
Login::~Login()
{
}
/**
* t@C烍OC擾
*/
void Login::Read()
{
// ----------------------------------------
// IDƃpX[h擾
// ----------------------------------------
// st@C̃pXf[^t@C쐬
CString fileName = theApp.GetAppDirPath() + _T("\\user.dat");
// t@C݂Ẵt@Cǂݍ
if( util::ExistFile(fileName) ) {
// ----------------------------------------
// fR[h
// ----------------------------------------
FILE* fp = _wfopen(fileName, _T("rb"));
if (fp == NULL) {
return;
}
m_loginMail = Read(fp);
m_loginPwd = Read(fp);
m_ownerId = Read(fp);
TRACE(_T("Mail = %s\n"), m_loginMail);
TRACE(_T("Password = %s\n"), m_loginPwd);
TRACE(_T("OwnerId = %s\n"), m_ownerId);
if (m_ownerId == _T("ERROR")) {
m_ownerId = _T("");
}
fclose(fp);
}
else {
// t@C݂Ȃ̂ŏlݒ
m_loginMail = _T("");
m_loginPwd = _T("");
m_ownerId = _T("");
}
}
/**
* t@C烍OCo
*/
void Login::Write()
{
// st@C̃pXf[^t@C쐬
CString fileName = theApp.GetAppDirPath() + _T("\\user.dat");
// ----------------------------------------
// GR[h
// ----------------------------------------
if (m_loginMail.GetLength() == 0 && m_loginPwd.GetLength() == 0) {
return;
}
if (m_ownerId.GetLength() == 0) {
m_ownerId = _T("");
}
FILE* fp = _wfopen(fileName, _T("wb"));
if (fp == NULL) {
return;
}
Write(fp, m_loginMail);
Write(fp, m_loginPwd);
Write(fp, m_ownerId);
fclose(fp);
}
CString Login::Read(FILE* fp)
{
// blowfish̏
char key[256];
memset(key, 0x00, 256);
wcstombs(key, CRYPT_KEY, 255); // ÍL[
bf::bf bf;
bf.init((unsigned char*)key, strlen(key)); //
CString ret = _T("");
int len = (int)fgetc(fp);
// ꕶڂo
char buf[256];
memset(buf, 0x00, sizeof(char) * 256);
int num = (int)fread(buf, sizeof(char), ((len/8)+1)*8, fp);
for (int i=0; i<(int)(len / 8) + 1; i++) {
char dBuf[9];
memset(dBuf, 0x00, sizeof(char) * 9);
memcpy(dBuf, buf+i*8, 8);
bf.decrypt((unsigned char*)dBuf);
TCHAR str[256];
memset(str, 0x00, sizeof(TCHAR) * 256);
mbstowcs(str, dBuf, 8);
ret += str;
}
return ret.Mid(0, len);
}
void Login::Write(FILE* fp, LPCTSTR tmp)
{
CString str = tmp;
// blowfish̏
char key[256];
memset(key, 0x00, 256);
wcstombs(key, CRYPT_KEY, 255); // ÍL[
bf::bf bf;
bf.init((unsigned char*)key, strlen(key)); //
int len = wcslen(tmp);
fputc(len, fp);
// peBO
for (int i=0; i<(((len / 8) + 1) * 8) - len; i++) {
str += _T("0");
}
for (int i=0; i<(int)(len / 8) + 1; i++) {
CString buf = str.Mid(i * 8, 8);
char mchar[256];
memset(mchar, '\0', sizeof(char) * 9);
wcstombs(mchar, buf, 8);
bf.encrypt((unsigned char*)mchar);
fwrite(mchar, sizeof(char), 8, fp);
}
}
}// namespace option
<commit_msg>- オーナーIDをuser.datに保存しないようにした。<commit_after>// LoginMng.cpp : t@C
//
#include "stdafx.h"
#include "MZ3.h"
#include "LoginMng.h"
#include "bf.h"
#include "Winsock2.h"
#include "util.h"
/// IvVf[^
namespace option {
#define CRYPT_KEY _T("Mixi_browser_for_W-ZERO3")
// Login
Login::Login()
{
m_ownerId = _T("");
}
Login::~Login()
{
}
/**
* t@C烍OC擾
*/
void Login::Read()
{
// ----------------------------------------
// IDƃpX[h擾
// ----------------------------------------
// lݒ
m_loginMail = _T("");
m_loginPwd = _T("");
m_ownerId = _T("");
// st@C̃pXf[^t@C쐬
CString fileName = theApp.GetAppDirPath() + _T("\\user.dat");
// t@C݂Ẵt@Cǂݍ
if( util::ExistFile(fileName) ) {
// ----------------------------------------
// fR[h
// ----------------------------------------
FILE* fp = _wfopen(fileName, _T("rb"));
if (fp == NULL) {
return;
}
m_loginMail = Read(fp);
m_loginPwd = Read(fp);
// TRACE(_T("Mail = %s\n"), m_loginMail);
// TRACE(_T("Password = %s\n"), m_loginPwd);
fclose(fp);
}
}
/**
* t@C烍OCo
*/
void Login::Write()
{
// st@C̃pXf[^t@C쐬
CString fileName = theApp.GetAppDirPath() + _T("\\user.dat");
// ----------------------------------------
// GR[h
// ----------------------------------------
if (m_loginMail.GetLength() == 0 && m_loginPwd.GetLength() == 0) {
return;
}
FILE* fp = _wfopen(fileName, _T("wb"));
if (fp == NULL) {
return;
}
Write(fp, m_loginMail);
Write(fp, m_loginPwd);
fclose(fp);
}
CString Login::Read(FILE* fp)
{
// blowfish̏
char key[256];
memset(key, 0x00, 256);
wcstombs(key, CRYPT_KEY, 255); // ÍL[
bf::bf bf;
bf.init((unsigned char*)key, strlen(key)); //
CString ret = _T("");
int len = (int)fgetc(fp);
// ꕶڂo
char buf[256];
memset(buf, 0x00, sizeof(char) * 256);
int num = (int)fread(buf, sizeof(char), ((len/8)+1)*8, fp);
for (int i=0; i<(int)(len / 8) + 1; i++) {
char dBuf[9];
memset(dBuf, 0x00, sizeof(char) * 9);
memcpy(dBuf, buf+i*8, 8);
bf.decrypt((unsigned char*)dBuf);
TCHAR str[256];
memset(str, 0x00, sizeof(TCHAR) * 256);
mbstowcs(str, dBuf, 8);
ret += str;
}
return ret.Mid(0, len);
}
void Login::Write(FILE* fp, LPCTSTR tmp)
{
CString str = tmp;
// blowfish̏
char key[256];
memset(key, 0x00, 256);
wcstombs(key, CRYPT_KEY, 255); // ÍL[
bf::bf bf;
bf.init((unsigned char*)key, strlen(key)); //
int len = wcslen(tmp);
fputc(len, fp);
// peBO
for (int i=0; i<(((len / 8) + 1) * 8) - len; i++) {
str += _T("0");
}
for (int i=0; i<(int)(len / 8) + 1; i++) {
CString buf = str.Mid(i * 8, 8);
char mchar[256];
memset(mchar, '\0', sizeof(char) * 9);
wcstombs(mchar, buf, 8);
bf.encrypt((unsigned char*)mchar);
fwrite(mchar, sizeof(char), 8, fp);
}
}
}// namespace option
<|endoftext|> |
<commit_before>// MachineState.cpp
/*
* Copyright (c) 2009, Dan Heeks
* This program is released under the BSD license. See the file COPYING for
* details.
*/
#include "stdafx.h"
#include "MachineState.h"
#include "CuttingTool.h"
class CFixture;
CMachineState::CMachineState() : m_fixture(NULL, CFixture::G54)
{
m_location = gp_Pnt(0.0, 0.0, 0.0);
m_cutting_tool_number = 0; // No tool assigned.
m_fixture_has_been_set = false;
}
CMachineState::~CMachineState() { }
CMachineState::CMachineState(CMachineState & rhs) : m_fixture(rhs.Fixture())
{
*this = rhs; // Call the assignment operator
}
CMachineState & CMachineState::operator= ( CMachineState & rhs )
{
if (this != &rhs)
{
m_location = rhs.Location();
m_fixture = rhs.Fixture();
m_cutting_tool_number = rhs.CuttingTool();
m_fixture_has_been_set = rhs.m_fixture_has_been_set;
}
return(*this);
}
bool CMachineState::operator== ( const CMachineState & rhs ) const
{
if (m_fixture != rhs.Fixture()) return(false);
if (m_cutting_tool_number != rhs.m_cutting_tool_number) return(false);
// Don't include the location in the state check. Moving around the machine is nothing to reset ourselves
// over.
// Don't worry about m_fixture_has_been_set
return(true);
}
/**
The machine's cutting tool has changed. Issue the appropriate GCode if necessary.
*/
Python CMachineState::CuttingTool( const int new_cutting_tool )
{
Python python;
if (m_cutting_tool_number != new_cutting_tool)
{
m_cutting_tool_number = new_cutting_tool;
// Select the right tool.
CCuttingTool *pCuttingTool = (CCuttingTool *) CCuttingTool::Find(new_cutting_tool);
if (pCuttingTool != NULL)
{
python << _T("comment(") << PythonString(_T("tool change to ") + pCuttingTool->m_title) << _T(")\n");
python << _T("tool_change( id=") << new_cutting_tool << _T(")\n");
} // End if - then
}
return(python);
}
/**
If the machine is changing fixtures, we may need to move up to a safety height before moving on to the
next fixture. If it is, indeed, a different fixture then issue the appropriate GCode to make the switch. This
routine should not add the GCode unless it's necessary. We want the AppendTextToProgram() methods to be
able to call this routine repeatedly without worrying about unnecessary movements.
If we're moving between two different fixtures, move above the new fixture's touch-off point before
continuing on with the other machine operations. This ensures that the cutting tool is somewhere above
the new fixture before we start any other movements.
*/
Python CMachineState::Fixture( CFixture new_fixture )
{
Python python;
if ((m_fixture != new_fixture) || (! m_fixture_has_been_set))
{
// The fixture has been changed. Move to the highest safety-height between the two fixtures.
if (m_fixture.m_params.m_safety_height_defined)
{
if (new_fixture.m_params.m_safety_height_defined)
{
wxString comment;
comment << _("Moving to a safety height common to both ") << m_fixture.m_coordinate_system_number << _(" and ") << new_fixture.m_coordinate_system_number;
python << _T("comment(") << PythonString(comment) << _T(")\n");
// Both fixtures have a safety height defined. Move the highest of the two.
if (m_fixture.m_params.m_safety_height > new_fixture.m_params.m_safety_height)
{
python << _T("rapid(z=") << m_fixture.m_params.m_safety_height / theApp.m_program->m_units << _T(", machine_coordinates='True')\n");
} // End if - then
else
{
python << _T("rapid(z=") << new_fixture.m_params.m_safety_height / theApp.m_program->m_units << _T(", machine_coordinates='True')\n");
} // End if - else
} // End if - then
else
{
// The old fixture has a safety height but the new one doesn't
python << _T("rapid(z=") << m_fixture.m_params.m_safety_height / theApp.m_program->m_units << _T(", machine_coordinates='True')\n");
} // End if - else
}
// Invoke new coordinate system.
python << new_fixture.AppendTextToProgram();
if (m_fixture_has_been_set == true)
{
// We must be moving between fixtures rather than an initial fixture setup.
// Now move to above the touch-off point so that, when we plunge down, we won't hit the old fixture.
if (new_fixture.m_params.m_touch_off_description.Length() > 0)
{
python << _T("comment(") << PythonString(new_fixture.m_params.m_touch_off_description) << _T(")\n");
}
wxString comment;
comment << _("Move above touch-off point for ") << new_fixture.m_coordinate_system_number;
python << _T("comment(") << PythonString(comment) << _T(")\n");
python << _T("rapid(x=") << new_fixture.m_params.m_touch_off_point.X() << _T(", y=") << new_fixture.m_params.m_touch_off_point.Y() << _T(")\n");
} // End if - then
m_fixture_has_been_set = true;
}
m_fixture = new_fixture;
return(python);
}
/**
Look to see if this object has been handled for this fixture already.
*/
bool CMachineState::AlreadyProcessed( const int object_type, const unsigned int object_id, const CFixture fixture )
{
Instance instance;
instance.Type(object_type);
instance.Id(object_id);
instance.Fixture(fixture);
return(m_already_processed.find(instance) != m_already_processed.end());
}
/**
Remember which objects have been processed for which fixtures.
*/
void CMachineState::MarkAsProcessed( const int object_type, const unsigned int object_id, const CFixture fixture )
{
Instance instance;
instance.Type(object_type);
instance.Id(object_id);
instance.Fixture(fixture);
m_already_processed.insert( instance );
}
CMachineState::Instance::Instance( const CMachineState::Instance & rhs ) : m_fixture(NULL, CFixture::G54)
{
*this = rhs;
}
CMachineState::Instance & CMachineState::Instance::operator= ( const CMachineState::Instance & rhs )
{
if (this != &rhs)
{
m_object_id = rhs.m_object_id;
m_object_type = rhs.m_object_type;
m_fixture = rhs.m_fixture;
}
return(*this);
}
bool CMachineState::Instance::operator== ( const CMachineState::Instance & rhs ) const
{
if (m_object_id != rhs.m_object_id) return(false);
if (m_object_type != rhs.m_object_type) return(false);
if (m_fixture != rhs.m_fixture) return(false);
return(true);
}
bool CMachineState::Instance::operator< ( const CMachineState::Instance & rhs ) const
{
if (m_object_type < rhs.m_object_type) return(true);
if (m_object_type > rhs.m_object_type) return(false);
if (m_object_id < rhs.m_object_id) return(true);
if (m_object_id > rhs.m_object_id) return(false);
return(m_fixture < rhs.m_fixture);
}
<commit_msg>I figured out part of the problem with touch off ignoring units<commit_after>// MachineState.cpp
/*
* Copyright (c) 2009, Dan Heeks
* This program is released under the BSD license. See the file COPYING for
* details.
*/
#include "stdafx.h"
#include "MachineState.h"
#include "CuttingTool.h"
class CFixture;
CMachineState::CMachineState() : m_fixture(NULL, CFixture::G54)
{
m_location = gp_Pnt(0.0, 0.0, 0.0);
m_cutting_tool_number = 0; // No tool assigned.
m_fixture_has_been_set = false;
}
CMachineState::~CMachineState() { }
CMachineState::CMachineState(CMachineState & rhs) : m_fixture(rhs.Fixture())
{
*this = rhs; // Call the assignment operator
}
CMachineState & CMachineState::operator= ( CMachineState & rhs )
{
if (this != &rhs)
{
m_location = rhs.Location();
m_fixture = rhs.Fixture();
m_cutting_tool_number = rhs.CuttingTool();
m_fixture_has_been_set = rhs.m_fixture_has_been_set;
}
return(*this);
}
bool CMachineState::operator== ( const CMachineState & rhs ) const
{
if (m_fixture != rhs.Fixture()) return(false);
if (m_cutting_tool_number != rhs.m_cutting_tool_number) return(false);
// Don't include the location in the state check. Moving around the machine is nothing to reset ourselves
// over.
// Don't worry about m_fixture_has_been_set
return(true);
}
/**
The machine's cutting tool has changed. Issue the appropriate GCode if necessary.
*/
Python CMachineState::CuttingTool( const int new_cutting_tool )
{
Python python;
if (m_cutting_tool_number != new_cutting_tool)
{
m_cutting_tool_number = new_cutting_tool;
// Select the right tool.
CCuttingTool *pCuttingTool = (CCuttingTool *) CCuttingTool::Find(new_cutting_tool);
if (pCuttingTool != NULL)
{
python << _T("comment(") << PythonString(_T("tool change to ") + pCuttingTool->m_title) << _T(")\n");
python << _T("tool_change( id=") << new_cutting_tool << _T(")\n");
} // End if - then
}
return(python);
}
/**
If the machine is changing fixtures, we may need to move up to a safety height before moving on to the
next fixture. If it is, indeed, a different fixture then issue the appropriate GCode to make the switch. This
routine should not add the GCode unless it's necessary. We want the AppendTextToProgram() methods to be
able to call this routine repeatedly without worrying about unnecessary movements.
If we're moving between two different fixtures, move above the new fixture's touch-off point before
continuing on with the other machine operations. This ensures that the cutting tool is somewhere above
the new fixture before we start any other movements.
*/
Python CMachineState::Fixture( CFixture new_fixture )
{
Python python;
if ((m_fixture != new_fixture) || (! m_fixture_has_been_set))
{
// The fixture has been changed. Move to the highest safety-height between the two fixtures.
if (m_fixture.m_params.m_safety_height_defined)
{
if (new_fixture.m_params.m_safety_height_defined)
{
wxString comment;
comment << _("Moving to a safety height common to both ") << m_fixture.m_coordinate_system_number << _(" and ") << new_fixture.m_coordinate_system_number;
python << _T("comment(") << PythonString(comment) << _T(")\n");
// Both fixtures have a safety height defined. Move the highest of the two.
if (m_fixture.m_params.m_safety_height > new_fixture.m_params.m_safety_height)
{
python << _T("rapid(z=") << m_fixture.m_params.m_safety_height / theApp.m_program->m_units << _T(", machine_coordinates='True')\n");
} // End if - then
else
{
python << _T("rapid(z=") << new_fixture.m_params.m_safety_height / theApp.m_program->m_units << _T(", machine_coordinates='True')\n");
} // End if - else
} // End if - then
else
{
// The old fixture has a safety height but the new one doesn't
python << _T("rapid(z=") << m_fixture.m_params.m_safety_height / theApp.m_program->m_units << _T(", machine_coordinates='True')\n");
} // End if - else
}
// Invoke new coordinate system.
python << new_fixture.AppendTextToProgram();
if (m_fixture_has_been_set == true)
{
// We must be moving between fixtures rather than an initial fixture setup.
// Now move to above the touch-off point so that, when we plunge down, we won't hit the old fixture.
if (new_fixture.m_params.m_touch_off_description.Length() > 0)
{
python << _T("comment(") << PythonString(new_fixture.m_params.m_touch_off_description) << _T(")\n");
}
wxString comment;
comment << _("Move above touch-off point for ") << new_fixture.m_coordinate_system_number;
python << _T("comment(") << PythonString(comment) << _T(")\n");
python << _T("rapid(x=") << new_fixture.m_params.m_touch_off_point.X()/theApp.m_program->m_units << _T(", y=") << new_fixture.m_params.m_touch_off_point.Y()/theApp.m_program->m_units << _T(")\n");
} // End if - then
m_fixture_has_been_set = true;
}
m_fixture = new_fixture;
return(python);
}
/**
Look to see if this object has been handled for this fixture already.
*/
bool CMachineState::AlreadyProcessed( const int object_type, const unsigned int object_id, const CFixture fixture )
{
Instance instance;
instance.Type(object_type);
instance.Id(object_id);
instance.Fixture(fixture);
return(m_already_processed.find(instance) != m_already_processed.end());
}
/**
Remember which objects have been processed for which fixtures.
*/
void CMachineState::MarkAsProcessed( const int object_type, const unsigned int object_id, const CFixture fixture )
{
Instance instance;
instance.Type(object_type);
instance.Id(object_id);
instance.Fixture(fixture);
m_already_processed.insert( instance );
}
CMachineState::Instance::Instance( const CMachineState::Instance & rhs ) : m_fixture(NULL, CFixture::G54)
{
*this = rhs;
}
CMachineState::Instance & CMachineState::Instance::operator= ( const CMachineState::Instance & rhs )
{
if (this != &rhs)
{
m_object_id = rhs.m_object_id;
m_object_type = rhs.m_object_type;
m_fixture = rhs.m_fixture;
}
return(*this);
}
bool CMachineState::Instance::operator== ( const CMachineState::Instance & rhs ) const
{
if (m_object_id != rhs.m_object_id) return(false);
if (m_object_type != rhs.m_object_type) return(false);
if (m_fixture != rhs.m_fixture) return(false);
return(true);
}
bool CMachineState::Instance::operator< ( const CMachineState::Instance & rhs ) const
{
if (m_object_type < rhs.m_object_type) return(true);
if (m_object_type > rhs.m_object_type) return(false);
if (m_object_id < rhs.m_object_id) return(true);
if (m_object_id > rhs.m_object_id) return(false);
return(m_fixture < rhs.m_fixture);
}
<|endoftext|> |
<commit_before>/* grakopp/ast-io.hpp - Grako++ AST I/O header file
Copyright (C) 2014 semantics Kommunikationsmanagement GmbH
Written by Marcus Brinkmann <m.brinkmann@semantics.de>
This file is part of Grako++. Grako++ is free software; you can
redistribute it and/or modify it under the terms of the 2-clause
BSD license, see file LICENSE.TXT.
*/
#ifndef _GRAKOPP_AST_IO_HPP
#define _GRAKOPP_AST_IO_HPP 1
#include <ostream>
#include <streambuf>
#include <boost/algorithm/string/replace.hpp>
#include "ast.hpp"
class AstIndentGuard : public std::streambuf
{
std::streambuf* _out;
bool _bol;
std::string _indent;
std::ostream* _owner;
protected:
virtual int overflow(int ch)
{
if (_bol && ch != '\n')
{
_out->sputn(_indent.data(), _indent.size());
_bol = false;
}
else if (ch == '\n')
_bol = true;
return _out->sputc(ch);
}
public:
explicit AstIndentGuard(std::streambuf* out, int indent=4)
: _out(out), _bol(true), _indent(indent, ' '), _owner(0)
{
}
explicit AstIndentGuard(std::ostream& out, int indent=4)
: _out(out.rdbuf()), _bol(true), _indent(indent, ' '), _owner(&out)
{
_owner->rdbuf(this);
}
~AstIndentGuard()
{
if (_out)
_owner->rdbuf(_out);
}
};
std::ostream& operator<< (std::ostream& cout, const Ast& ast)
{
class AstDumper : public boost::static_visitor<void>
{
void xml_escape(std::string* data) const
{
using boost::algorithm::replace_all;
replace_all(*data, "&", "&");
replace_all(*data, "\"", """);
replace_all(*data, "\'", "'");
replace_all(*data, "<", "<");
replace_all(*data, ">", ">");
}
void json_escape(std::string* data) const
{
using boost::algorithm::replace_all;
replace_all(*data, "\\", "\\\\");
replace_all(*data, "\"", "\\\"");
replace_all(*data, "\b", "\\\b");
replace_all(*data, "\f", "\\\f");
replace_all(*data, "\n", "\\\n");
replace_all(*data, "\t", "\\\t");
/* FIXME: Replace all < 32 */
}
public:
AstDumper(std::ostream& cout) : _cout(cout) {}
std::ostream& _cout;
void operator() (const AstNone& none) const
{
_cout << "null";
}
void operator() (const AstString& leaf) const
{
std::string _leaf = leaf;
json_escape(&_leaf);
_cout << "\"" << _leaf << "\"";
}
void operator() (const AstList& list) const
{
bool first = true;
_cout << "[";
{
AstIndentGuard ind_cout(_cout);
for (auto& child: list)
{
if (first)
{
first = false;
_cout << "\n";
}
else
_cout << ",\n";
_cout << *child;
}
}
if (!first)
_cout << "\n";
_cout << "]";
}
void operator() (const AstMap& map) const
{
bool first = true;
_cout << "{";
{
AstIndentGuard ind_out(_cout);
for (auto& key: map._order)
{
if (first)
{
first = false;
_cout << "\n";
}
else
_cout << ",\n";
_cout << "\"" << key << "\" : " << *map.at(key);
}
}
if (!first)
_cout << "\n";
_cout << "}";
}
void operator() (const AstException& exc) const
{
std::string msg = (*exc).what();
json_escape(&msg);
_cout << (*exc).type() << "(\"" << msg << "\")";
}
};
AstDumper dumper(cout);
boost::apply_visitor(dumper, ast._content);
return cout;
}
/* Forward declaration. */
std::istream& operator>> (std::istream& is, AstPtr& val);
std::istream& operator>> (std::istream& is, AstNone& val)
{
char ch;
is >> ch;
if (ch != 'n')
throw std::invalid_argument("null expected");
is >> ch;
if (ch != 'u')
throw std::invalid_argument("null expected");
is >> ch;
if (ch != 'l')
throw std::invalid_argument("null expected");
is >> ch;
if (ch != 'l')
throw std::invalid_argument("null expected");
return is;
}
std::istream& operator>> (std::istream& is, AstString& val)
{
char ch;
if (is.peek() != '"')
throw std::invalid_argument("quote expected");
is >> ch;
while (! is.eof())
{
is >> ch;
if (ch == '"')
return is;
else if (ch == '\\')
{
is >> ch;
if (ch == 'b')
val += '\b';
else if (ch == 'f')
val += '\f';
else if (ch == 'n')
val += '\n';
else if (ch == 'r')
val += '\r';
else if (ch == 't')
val += '\t';
else if (ch == 'u')
throw std::invalid_argument("unicode support not implemented yet");
else
val += ch;
}
else
val += ch;
}
throw std::invalid_argument("EOF in string");
}
std::istream& operator>> (std::istream& is, AstList& val)
{
char ch;
if (is.peek() != '[')
throw std::invalid_argument("list expected");
is >> ch >> std::ws;
while (! is.eof() )
{
if (is.peek() == ']')
{
is >> ch;
return is;
}
AstPtr ast = std::make_shared<Ast>();
is >> ast >> std::ws;
val.push_back(ast);
ch = is.peek();
if (ch == ',')
is >> ch >> std::ws;
if (ch != ',' && ch != ']')
throw std::invalid_argument("expected comma");
}
throw std::invalid_argument("EOF in list");
}
std::istream& operator>> (std::istream& is, AstMap& val)
{
char ch;
if (is.peek() != '{')
throw std::invalid_argument("map expected");
is >> ch >> std::ws;
while (! is.eof())
{
if (is.peek() == '}')
{
is >> ch;
return is;
}
AstString key;
is >> key >> std::ws;
if (is.peek() != ':')
throw std::invalid_argument("expected colon");
is >> ch >> std::ws;
AstPtr ast = std::make_shared<Ast>();
is >> ast >> std::ws;
/* FIXME: Maybe override in AstMap. */
val._order.push_back(key);
val[key] = ast;
ch = is.peek();
if (ch == ',')
is >> ch >> std::ws;
if (ch != ',' && ch != '}')
throw std::invalid_argument("expected comma");
}
throw std::invalid_argument("EOF in list");
}
std::istream& operator>> (std::istream& is, AstException& exc)
{
#define MAX_TOKEN 40
char token[MAX_TOKEN];
is.getline(token, MAX_TOKEN, '(');
/* Paranoia. */
token[MAX_TOKEN - 1] = '\0';
/* FIXME: Report better error on invalid input, in particular if
opening parenthesis is missing. */
AstString msg;
is >> msg;
if (is.peek() != ')')
throw std::invalid_argument("closing parenthesis expected");
is.ignore(1);
if (!strcmp(token, "FailedParse"))
exc._exc = std::make_shared<FailedParse>(msg);
else if (!strcmp(token, "FailedToken"))
exc._exc = std::make_shared<FailedToken>(msg);
else if (!strcmp(token, "FailedPattern"))
exc._exc = std::make_shared<FailedPattern>(msg);
else if (!strcmp(token, "FailedLookahead"))
exc._exc = std::make_shared<FailedLookahead>(msg);
else
throw std::invalid_argument("unknown exception");
return is;
}
std::istream& operator>> (std::istream& is, AstPtr& val)
{
char ch = is.peek();
if (ch == '"')
{
AstString str;
is >> str;
val->_content = str;
}
else if (ch == '[')
{
AstList list;
is >> list;
val->_content = list;
}
else if (ch == '{')
{
AstMap map;
is >> map;
val->_content = map;
}
else if (ch == 'F')
{
AstException exc;
is >> exc;
val->_content = exc;
}
else if (ch == 'n')
{
AstNone none;
is >> none;
val->_content = none;
}
else
throw std::invalid_argument("AST expected");
return is;
}
#endif /* _GRAKOPP_AST_IO_HPP */
<commit_msg>Fix json_escape.<commit_after>/* grakopp/ast-io.hpp - Grako++ AST I/O header file
Copyright (C) 2014 semantics Kommunikationsmanagement GmbH
Written by Marcus Brinkmann <m.brinkmann@semantics.de>
This file is part of Grako++. Grako++ is free software; you can
redistribute it and/or modify it under the terms of the 2-clause
BSD license, see file LICENSE.TXT.
*/
#ifndef _GRAKOPP_AST_IO_HPP
#define _GRAKOPP_AST_IO_HPP 1
#include <ostream>
#include <streambuf>
#include <boost/algorithm/string/replace.hpp>
#include "ast.hpp"
class AstIndentGuard : public std::streambuf
{
std::streambuf* _out;
bool _bol;
std::string _indent;
std::ostream* _owner;
protected:
virtual int overflow(int ch)
{
if (_bol && ch != '\n')
{
_out->sputn(_indent.data(), _indent.size());
_bol = false;
}
else if (ch == '\n')
_bol = true;
return _out->sputc(ch);
}
public:
explicit AstIndentGuard(std::streambuf* out, int indent=4)
: _out(out), _bol(true), _indent(indent, ' '), _owner(0)
{
}
explicit AstIndentGuard(std::ostream& out, int indent=4)
: _out(out.rdbuf()), _bol(true), _indent(indent, ' '), _owner(&out)
{
_owner->rdbuf(this);
}
~AstIndentGuard()
{
if (_out)
_owner->rdbuf(_out);
}
};
std::ostream& operator<< (std::ostream& cout, const Ast& ast)
{
class AstDumper : public boost::static_visitor<void>
{
void json_escape(std::string* data) const
{
using boost::algorithm::replace_all;
replace_all(*data, "\\", "\\\\");
replace_all(*data, "\"", "\\\"");
replace_all(*data, "\b", "\\b");
replace_all(*data, "\f", "\\f");
replace_all(*data, "\n", "\\n");
replace_all(*data, "\t", "\\t");
/* FIXME: Replace all < 32 */
}
public:
AstDumper(std::ostream& cout) : _cout(cout) {}
std::ostream& _cout;
void operator() (const AstNone& none) const
{
_cout << "null";
}
void operator() (const AstString& leaf) const
{
std::string _leaf = leaf;
json_escape(&_leaf);
_cout << "\"" << _leaf << "\"";
}
void operator() (const AstList& list) const
{
bool first = true;
_cout << "[";
{
AstIndentGuard ind_cout(_cout);
for (auto& child: list)
{
if (first)
{
first = false;
_cout << "\n";
}
else
_cout << ",\n";
_cout << *child;
}
}
if (!first)
_cout << "\n";
_cout << "]";
}
void operator() (const AstMap& map) const
{
bool first = true;
_cout << "{";
{
AstIndentGuard ind_out(_cout);
for (auto& key: map._order)
{
if (first)
{
first = false;
_cout << "\n";
}
else
_cout << ",\n";
_cout << "\"" << key << "\" : " << *map.at(key);
}
}
if (!first)
_cout << "\n";
_cout << "}";
}
void operator() (const AstException& exc) const
{
std::string msg = (*exc).what();
json_escape(&msg);
_cout << (*exc).type() << "(\"" << msg << "\")";
}
};
AstDumper dumper(cout);
boost::apply_visitor(dumper, ast._content);
return cout;
}
/* Forward declaration. */
std::istream& operator>> (std::istream& is, AstPtr& val);
std::istream& operator>> (std::istream& is, AstNone& val)
{
char ch;
is >> ch;
if (ch != 'n')
throw std::invalid_argument("null expected");
is >> ch;
if (ch != 'u')
throw std::invalid_argument("null expected");
is >> ch;
if (ch != 'l')
throw std::invalid_argument("null expected");
is >> ch;
if (ch != 'l')
throw std::invalid_argument("null expected");
return is;
}
std::istream& operator>> (std::istream& is, AstString& val)
{
char ch;
if (is.peek() != '"')
throw std::invalid_argument("quote expected");
is >> ch;
while (! is.eof())
{
is >> ch;
if (ch == '"')
return is;
else if (ch == '\\')
{
is >> ch;
if (ch == 'b')
val += '\b';
else if (ch == 'f')
val += '\f';
else if (ch == 'n')
val += '\n';
else if (ch == 'r')
val += '\r';
else if (ch == 't')
val += '\t';
else if (ch == 'u')
throw std::invalid_argument("unicode support not implemented yet");
else
val += ch;
}
else
val += ch;
}
throw std::invalid_argument("EOF in string");
}
std::istream& operator>> (std::istream& is, AstList& val)
{
char ch;
if (is.peek() != '[')
throw std::invalid_argument("list expected");
is >> ch >> std::ws;
while (! is.eof() )
{
if (is.peek() == ']')
{
is >> ch;
return is;
}
AstPtr ast = std::make_shared<Ast>();
is >> ast >> std::ws;
val.push_back(ast);
ch = is.peek();
if (ch == ',')
is >> ch >> std::ws;
if (ch != ',' && ch != ']')
throw std::invalid_argument("expected comma");
}
throw std::invalid_argument("EOF in list");
}
std::istream& operator>> (std::istream& is, AstMap& val)
{
char ch;
if (is.peek() != '{')
throw std::invalid_argument("map expected");
is >> ch >> std::ws;
while (! is.eof())
{
if (is.peek() == '}')
{
is >> ch;
return is;
}
AstString key;
is >> key >> std::ws;
if (is.peek() != ':')
throw std::invalid_argument("expected colon");
is >> ch >> std::ws;
AstPtr ast = std::make_shared<Ast>();
is >> ast >> std::ws;
/* FIXME: Maybe override in AstMap. */
val._order.push_back(key);
val[key] = ast;
ch = is.peek();
if (ch == ',')
is >> ch >> std::ws;
if (ch != ',' && ch != '}')
throw std::invalid_argument("expected comma");
}
throw std::invalid_argument("EOF in list");
}
std::istream& operator>> (std::istream& is, AstException& exc)
{
#define MAX_TOKEN 40
char token[MAX_TOKEN];
is.getline(token, MAX_TOKEN, '(');
/* Paranoia. */
token[MAX_TOKEN - 1] = '\0';
/* FIXME: Report better error on invalid input, in particular if
opening parenthesis is missing. */
AstString msg;
is >> msg;
if (is.peek() != ')')
throw std::invalid_argument("closing parenthesis expected");
is.ignore(1);
if (!strcmp(token, "FailedParse"))
exc._exc = std::make_shared<FailedParse>(msg);
else if (!strcmp(token, "FailedToken"))
exc._exc = std::make_shared<FailedToken>(msg);
else if (!strcmp(token, "FailedPattern"))
exc._exc = std::make_shared<FailedPattern>(msg);
else if (!strcmp(token, "FailedLookahead"))
exc._exc = std::make_shared<FailedLookahead>(msg);
else
throw std::invalid_argument("unknown exception");
return is;
}
std::istream& operator>> (std::istream& is, AstPtr& val)
{
char ch = is.peek();
if (ch == '"')
{
AstString str;
is >> str;
val->_content = str;
}
else if (ch == '[')
{
AstList list;
is >> list;
val->_content = list;
}
else if (ch == '{')
{
AstMap map;
is >> map;
val->_content = map;
}
else if (ch == 'F')
{
AstException exc;
is >> exc;
val->_content = exc;
}
else if (ch == 'n')
{
AstNone none;
is >> none;
val->_content = none;
}
else
throw std::invalid_argument("AST expected");
return is;
}
#endif /* _GRAKOPP_AST_IO_HPP */
<|endoftext|> |
<commit_before>//===- PostDominators.cpp - Post-Dominator Calculation --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the post-dominator construction algorithms.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Instructions.h"
#include "llvm/Support/CFG.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SetOperations.h"
#include <iostream>
using namespace llvm;
//===----------------------------------------------------------------------===//
// ImmediatePostDominators Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<ImmediatePostDominators>
D("postidom", "Immediate Post-Dominators Construction", true);
unsigned ImmediatePostDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
unsigned N) {
VInfo.Semi = ++N;
VInfo.Label = V;
Vertex.push_back(V); // Vertex[n] = V;
//Info[V].Ancestor = 0; // Ancestor[n] = 0
//Child[V] = 0; // Child[v] = 0
VInfo.Size = 1; // Size[v] = 1
// For PostDominators, we want to walk predecessors rather than successors
// as we do in forward Dominators.
for (pred_iterator PI = pred_begin(V), PE = pred_end(V); PI != PE; ++PI) {
InfoRec &SuccVInfo = Info[*PI];
if (SuccVInfo.Semi == 0) {
SuccVInfo.Parent = V;
N = DFSPass(*PI, SuccVInfo, N);
}
}
return N;
}
void ImmediatePostDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
BasicBlock *VAncestor = VInfo.Ancestor;
InfoRec &VAInfo = Info[VAncestor];
if (VAInfo.Ancestor == 0)
return;
Compress(VAncestor, VAInfo);
BasicBlock *VAncestorLabel = VAInfo.Label;
BasicBlock *VLabel = VInfo.Label;
if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
VInfo.Label = VAncestorLabel;
VInfo.Ancestor = VAInfo.Ancestor;
}
BasicBlock *ImmediatePostDominators::Eval(BasicBlock *V) {
InfoRec &VInfo = Info[V];
// Higher-complexity but faster implementation
if (VInfo.Ancestor == 0)
return V;
Compress(V, VInfo);
return VInfo.Label;
}
void ImmediatePostDominators::Link(BasicBlock *V, BasicBlock *W,
InfoRec &WInfo) {
// Higher-complexity but faster implementation
WInfo.Ancestor = V;
}
bool ImmediatePostDominators::runOnFunction(Function &F) {
IDoms.clear(); // Reset from the last time we were run...
Roots.clear();
// Step #0: Scan the function looking for the root nodes of the post-dominance
// relationships. These blocks, which have no successors, end with return and
// unwind instructions.
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (succ_begin(I) == succ_end(I))
Roots.push_back(I);
Vertex.push_back(0);
// Step #1: Number blocks in depth-first order and initialize variables used
// in later stages of the algorithm.
unsigned N = 0;
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
N = DFSPass(Roots[i], Info[Roots[i]], N);
for (unsigned i = N; i >= 2; --i) {
BasicBlock *W = Vertex[i];
InfoRec &WInfo = Info[W];
// Step #2: Calculate the semidominators of all vertices
for (succ_iterator SI = succ_begin(W), SE = succ_end(W); SI != SE; ++SI)
if (Info.count(*SI)) { // Only if this predecessor is reachable!
unsigned SemiU = Info[Eval(*SI)].Semi;
if (SemiU < WInfo.Semi)
WInfo.Semi = SemiU;
}
Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
BasicBlock *WParent = WInfo.Parent;
Link(WParent, W, WInfo);
// Step #3: Implicitly define the immediate dominator of vertices
std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
while (!WParentBucket.empty()) {
BasicBlock *V = WParentBucket.back();
WParentBucket.pop_back();
BasicBlock *U = Eval(V);
IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
}
}
// Step #4: Explicitly define the immediate dominator of each vertex
for (unsigned i = 2; i <= N; ++i) {
BasicBlock *W = Vertex[i];
BasicBlock *&WIDom = IDoms[W];
if (WIDom != Vertex[Info[W].Semi])
WIDom = IDoms[WIDom];
}
// Free temporary memory used to construct idom's
Info.clear();
std::vector<BasicBlock*>().swap(Vertex);
return false;
}
//===----------------------------------------------------------------------===//
// PostDominatorSet Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostDominatorSet>
B("postdomset", "Post-Dominator Set Construction", true);
// Postdominator set construction. This converts the specified function to only
// have a single exit node (return stmt), then calculates the post dominance
// sets for the function.
//
bool PostDominatorSet::runOnFunction(Function &F) {
// Scan the function looking for the root nodes of the post-dominance
// relationships. These blocks end with return and unwind instructions.
// While we are iterating over the function, we also initialize all of the
// domsets to empty.
Roots.clear();
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (succ_begin(I) == succ_end(I))
Roots.push_back(I);
// If there are no exit nodes for the function, postdomsets are all empty.
// This can happen if the function just contains an infinite loop, for
// example.
ImmediatePostDominators &IPD = getAnalysis<ImmediatePostDominators>();
Doms.clear(); // Reset from the last time we were run...
if (Roots.empty()) return false;
// If we have more than one root, we insert an artificial "null" exit, which
// has "virtual edges" to each of the real exit nodes.
//if (Roots.size() > 1)
// Doms[0].insert(0);
// Root nodes only dominate themselves.
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
Doms[Roots[i]].insert(Roots[i]);
// Loop over all of the blocks in the function, calculating dominator sets for
// each function.
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (BasicBlock *IPDom = IPD[I]) { // Get idom if block is reachable
DomSetType &DS = Doms[I];
assert(DS.empty() && "PostDomset already filled in for this block?");
DS.insert(I); // Blocks always dominate themselves
// Insert all dominators into the set...
while (IPDom) {
// If we have already computed the dominator sets for our immediate post
// dominator, just use it instead of walking all the way up to the root.
DomSetType &IPDS = Doms[IPDom];
if (!IPDS.empty()) {
DS.insert(IPDS.begin(), IPDS.end());
break;
} else {
DS.insert(IPDom);
IPDom = IPD[IPDom];
}
}
} else {
// Ensure that every basic block has at least an empty set of nodes. This
// is important for the case when there is unreachable blocks.
Doms[I];
}
return false;
}
//===----------------------------------------------------------------------===//
// PostDominatorTree Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostDominatorTree>
F("postdomtree", "Post-Dominator Tree Construction", true);
DominatorTreeBase::Node *PostDominatorTree::getNodeForBlock(BasicBlock *BB) {
Node *&BBNode = Nodes[BB];
if (BBNode) return BBNode;
// Haven't calculated this node yet? Get or calculate the node for the
// immediate postdominator.
BasicBlock *IPDom = getAnalysis<ImmediatePostDominators>()[BB];
Node *IPDomNode = getNodeForBlock(IPDom);
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
return BBNode = IPDomNode->addChild(new Node(BB, IPDomNode));
}
void PostDominatorTree::calculate(const ImmediatePostDominators &IPD) {
if (Roots.empty()) return;
// Add a node for the root. This node might be the actual root, if there is
// one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
// which postdominates all real exits if there are multiple exit blocks.
BasicBlock *Root = Roots.size() == 1 ? Roots[0] : 0;
Nodes[Root] = RootNode = new Node(Root, 0);
Function *F = Roots[0]->getParent();
// Loop over all of the reachable blocks in the function...
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
if (BasicBlock *ImmPostDom = IPD.get(I)) { // Reachable block.
Node *&BBNode = Nodes[I];
if (!BBNode) { // Haven't calculated this node yet?
// Get or calculate the node for the immediate dominator
Node *IPDomNode = getNodeForBlock(ImmPostDom);
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
BBNode = IPDomNode->addChild(new Node(I, IPDomNode));
}
}
}
//===----------------------------------------------------------------------===//
// PostETForest Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostETForest>
G("postetforest", "Post-ET-Forest Construction", true);
ETNode *PostETForest::getNodeForBlock(BasicBlock *BB) {
ETNode *&BBNode = Nodes[BB];
if (BBNode) return BBNode;
// Haven't calculated this node yet? Get or calculate the node for the
// immediate dominator.
BasicBlock *IDom = getAnalysis<ImmediatePostDominators>()[BB];
// If we are unreachable, we may not have an immediate dominator.
if (!IDom)
return BBNode = new ETNode(BB);
else {
ETNode *IDomNode = getNodeForBlock(IDom);
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
BBNode = new ETNode(BB);
BBNode->setFather(IDomNode);
return BBNode;
}
}
void PostETForest::calculate(const ImmediatePostDominators &ID) {
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
Nodes[Roots[i]] = new ETNode(Roots[i]); // Add a node for the root
// Iterate over all nodes in inverse depth first order.
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
E = idf_end(Roots[i]); I != E; ++I) {
BasicBlock *BB = *I;
ETNode *&BBNode = Nodes[BB];
if (!BBNode) {
ETNode *IDomNode = NULL;
if (ID.get(BB))
IDomNode = getNodeForBlock(ID.get(BB));
// Add a new ETNode for this BasicBlock, and set it's parent
// to it's immediate dominator.
BBNode = new ETNode(BB);
if (IDomNode)
BBNode->setFather(IDomNode);
}
}
int dfsnum = 0;
// Iterate over all nodes in depth first order...
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
E = idf_end(Roots[i]); I != E; ++I) {
if (!getNodeForBlock(*I)->hasFather())
getNodeForBlock(*I)->assignDFSNumber(dfsnum);
}
DFSInfoValid = true;
}
//===----------------------------------------------------------------------===//
// PostDominanceFrontier Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostDominanceFrontier>
H("postdomfrontier", "Post-Dominance Frontier Construction", true);
const DominanceFrontier::DomSetType &
PostDominanceFrontier::calculate(const PostDominatorTree &DT,
const DominatorTree::Node *Node) {
// Loop over CFG successors to calculate DFlocal[Node]
BasicBlock *BB = Node->getBlock();
DomSetType &S = Frontiers[BB]; // The new set to fill in...
if (getRoots().empty()) return S;
if (BB)
for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB);
SI != SE; ++SI)
// Does Node immediately dominate this predecessor?
if (DT[*SI]->getIDom() != Node)
S.insert(*SI);
// At this point, S is DFlocal. Now we union in DFup's of our children...
// Loop through and visit the nodes that Node immediately dominates (Node's
// children in the IDomTree)
//
for (PostDominatorTree::Node::const_iterator
NI = Node->begin(), NE = Node->end(); NI != NE; ++NI) {
DominatorTree::Node *IDominee = *NI;
const DomSetType &ChildDF = calculate(DT, IDominee);
DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
for (; CDFI != CDFE; ++CDFI) {
if (!Node->properlyDominates(DT[*CDFI]))
S.insert(*CDFI);
}
}
return S;
}
// Ensure that this .cpp file gets linked when PostDominators.h is used.
DEFINING_FILE_FOR(PostDominanceFrontier)
<commit_msg>Use iterative do-while loop instead of recursive DFSPass calls to reduce amount of stack space used at runtime.<commit_after>//===- PostDominators.cpp - Post-Dominator Calculation --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the post-dominator construction algorithms.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Instructions.h"
#include "llvm/Support/CFG.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SetOperations.h"
#include <iostream>
using namespace llvm;
//===----------------------------------------------------------------------===//
// ImmediatePostDominators Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<ImmediatePostDominators>
D("postidom", "Immediate Post-Dominators Construction", true);
unsigned ImmediatePostDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
unsigned N) {
std::vector<std::pair<BasicBlock *, InfoRec *> > workStack;
workStack.push_back(std::make_pair(V, &VInfo));
do {
BasicBlock *currentBB = workStack.back().first;
InfoRec *currentVInfo = workStack.back().second;
workStack.pop_back();
currentVInfo->Semi = ++N;
currentVInfo->Label = currentBB;
Vertex.push_back(currentBB); // Vertex[n] = current;
// Info[currentBB].Ancestor = 0;
// Ancestor[n] = 0
// Child[currentBB] = 0;
currentVInfo->Size = 1; // Size[currentBB] = 1
// For PostDominators, we want to walk predecessors rather than successors
// as we do in forward Dominators.
for (pred_iterator PI = pred_begin(currentBB), PE = pred_end(currentBB);
PI != PE; ++PI) {
InfoRec &SuccVInfo = Info[*PI];
if (SuccVInfo.Semi == 0) {
SuccVInfo.Parent = currentBB;
workStack.push_back(std::make_pair(*PI, &SuccVInfo));
}
}
} while (!workStack.empty());
return N;
}
void ImmediatePostDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
BasicBlock *VAncestor = VInfo.Ancestor;
InfoRec &VAInfo = Info[VAncestor];
if (VAInfo.Ancestor == 0)
return;
Compress(VAncestor, VAInfo);
BasicBlock *VAncestorLabel = VAInfo.Label;
BasicBlock *VLabel = VInfo.Label;
if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
VInfo.Label = VAncestorLabel;
VInfo.Ancestor = VAInfo.Ancestor;
}
BasicBlock *ImmediatePostDominators::Eval(BasicBlock *V) {
InfoRec &VInfo = Info[V];
// Higher-complexity but faster implementation
if (VInfo.Ancestor == 0)
return V;
Compress(V, VInfo);
return VInfo.Label;
}
void ImmediatePostDominators::Link(BasicBlock *V, BasicBlock *W,
InfoRec &WInfo) {
// Higher-complexity but faster implementation
WInfo.Ancestor = V;
}
bool ImmediatePostDominators::runOnFunction(Function &F) {
IDoms.clear(); // Reset from the last time we were run...
Roots.clear();
// Step #0: Scan the function looking for the root nodes of the post-dominance
// relationships. These blocks, which have no successors, end with return and
// unwind instructions.
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (succ_begin(I) == succ_end(I))
Roots.push_back(I);
Vertex.push_back(0);
// Step #1: Number blocks in depth-first order and initialize variables used
// in later stages of the algorithm.
unsigned N = 0;
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
N = DFSPass(Roots[i], Info[Roots[i]], N);
for (unsigned i = N; i >= 2; --i) {
BasicBlock *W = Vertex[i];
InfoRec &WInfo = Info[W];
// Step #2: Calculate the semidominators of all vertices
for (succ_iterator SI = succ_begin(W), SE = succ_end(W); SI != SE; ++SI)
if (Info.count(*SI)) { // Only if this predecessor is reachable!
unsigned SemiU = Info[Eval(*SI)].Semi;
if (SemiU < WInfo.Semi)
WInfo.Semi = SemiU;
}
Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
BasicBlock *WParent = WInfo.Parent;
Link(WParent, W, WInfo);
// Step #3: Implicitly define the immediate dominator of vertices
std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
while (!WParentBucket.empty()) {
BasicBlock *V = WParentBucket.back();
WParentBucket.pop_back();
BasicBlock *U = Eval(V);
IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
}
}
// Step #4: Explicitly define the immediate dominator of each vertex
for (unsigned i = 2; i <= N; ++i) {
BasicBlock *W = Vertex[i];
BasicBlock *&WIDom = IDoms[W];
if (WIDom != Vertex[Info[W].Semi])
WIDom = IDoms[WIDom];
}
// Free temporary memory used to construct idom's
Info.clear();
std::vector<BasicBlock*>().swap(Vertex);
return false;
}
//===----------------------------------------------------------------------===//
// PostDominatorSet Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostDominatorSet>
B("postdomset", "Post-Dominator Set Construction", true);
// Postdominator set construction. This converts the specified function to only
// have a single exit node (return stmt), then calculates the post dominance
// sets for the function.
//
bool PostDominatorSet::runOnFunction(Function &F) {
// Scan the function looking for the root nodes of the post-dominance
// relationships. These blocks end with return and unwind instructions.
// While we are iterating over the function, we also initialize all of the
// domsets to empty.
Roots.clear();
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (succ_begin(I) == succ_end(I))
Roots.push_back(I);
// If there are no exit nodes for the function, postdomsets are all empty.
// This can happen if the function just contains an infinite loop, for
// example.
ImmediatePostDominators &IPD = getAnalysis<ImmediatePostDominators>();
Doms.clear(); // Reset from the last time we were run...
if (Roots.empty()) return false;
// If we have more than one root, we insert an artificial "null" exit, which
// has "virtual edges" to each of the real exit nodes.
//if (Roots.size() > 1)
// Doms[0].insert(0);
// Root nodes only dominate themselves.
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
Doms[Roots[i]].insert(Roots[i]);
// Loop over all of the blocks in the function, calculating dominator sets for
// each function.
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (BasicBlock *IPDom = IPD[I]) { // Get idom if block is reachable
DomSetType &DS = Doms[I];
assert(DS.empty() && "PostDomset already filled in for this block?");
DS.insert(I); // Blocks always dominate themselves
// Insert all dominators into the set...
while (IPDom) {
// If we have already computed the dominator sets for our immediate post
// dominator, just use it instead of walking all the way up to the root.
DomSetType &IPDS = Doms[IPDom];
if (!IPDS.empty()) {
DS.insert(IPDS.begin(), IPDS.end());
break;
} else {
DS.insert(IPDom);
IPDom = IPD[IPDom];
}
}
} else {
// Ensure that every basic block has at least an empty set of nodes. This
// is important for the case when there is unreachable blocks.
Doms[I];
}
return false;
}
//===----------------------------------------------------------------------===//
// PostDominatorTree Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostDominatorTree>
F("postdomtree", "Post-Dominator Tree Construction", true);
DominatorTreeBase::Node *PostDominatorTree::getNodeForBlock(BasicBlock *BB) {
Node *&BBNode = Nodes[BB];
if (BBNode) return BBNode;
// Haven't calculated this node yet? Get or calculate the node for the
// immediate postdominator.
BasicBlock *IPDom = getAnalysis<ImmediatePostDominators>()[BB];
Node *IPDomNode = getNodeForBlock(IPDom);
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
return BBNode = IPDomNode->addChild(new Node(BB, IPDomNode));
}
void PostDominatorTree::calculate(const ImmediatePostDominators &IPD) {
if (Roots.empty()) return;
// Add a node for the root. This node might be the actual root, if there is
// one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
// which postdominates all real exits if there are multiple exit blocks.
BasicBlock *Root = Roots.size() == 1 ? Roots[0] : 0;
Nodes[Root] = RootNode = new Node(Root, 0);
Function *F = Roots[0]->getParent();
// Loop over all of the reachable blocks in the function...
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
if (BasicBlock *ImmPostDom = IPD.get(I)) { // Reachable block.
Node *&BBNode = Nodes[I];
if (!BBNode) { // Haven't calculated this node yet?
// Get or calculate the node for the immediate dominator
Node *IPDomNode = getNodeForBlock(ImmPostDom);
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
BBNode = IPDomNode->addChild(new Node(I, IPDomNode));
}
}
}
//===----------------------------------------------------------------------===//
// PostETForest Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostETForest>
G("postetforest", "Post-ET-Forest Construction", true);
ETNode *PostETForest::getNodeForBlock(BasicBlock *BB) {
ETNode *&BBNode = Nodes[BB];
if (BBNode) return BBNode;
// Haven't calculated this node yet? Get or calculate the node for the
// immediate dominator.
BasicBlock *IDom = getAnalysis<ImmediatePostDominators>()[BB];
// If we are unreachable, we may not have an immediate dominator.
if (!IDom)
return BBNode = new ETNode(BB);
else {
ETNode *IDomNode = getNodeForBlock(IDom);
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
BBNode = new ETNode(BB);
BBNode->setFather(IDomNode);
return BBNode;
}
}
void PostETForest::calculate(const ImmediatePostDominators &ID) {
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
Nodes[Roots[i]] = new ETNode(Roots[i]); // Add a node for the root
// Iterate over all nodes in inverse depth first order.
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
E = idf_end(Roots[i]); I != E; ++I) {
BasicBlock *BB = *I;
ETNode *&BBNode = Nodes[BB];
if (!BBNode) {
ETNode *IDomNode = NULL;
if (ID.get(BB))
IDomNode = getNodeForBlock(ID.get(BB));
// Add a new ETNode for this BasicBlock, and set it's parent
// to it's immediate dominator.
BBNode = new ETNode(BB);
if (IDomNode)
BBNode->setFather(IDomNode);
}
}
int dfsnum = 0;
// Iterate over all nodes in depth first order...
for (unsigned i = 0, e = Roots.size(); i != e; ++i)
for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
E = idf_end(Roots[i]); I != E; ++I) {
if (!getNodeForBlock(*I)->hasFather())
getNodeForBlock(*I)->assignDFSNumber(dfsnum);
}
DFSInfoValid = true;
}
//===----------------------------------------------------------------------===//
// PostDominanceFrontier Implementation
//===----------------------------------------------------------------------===//
static RegisterPass<PostDominanceFrontier>
H("postdomfrontier", "Post-Dominance Frontier Construction", true);
const DominanceFrontier::DomSetType &
PostDominanceFrontier::calculate(const PostDominatorTree &DT,
const DominatorTree::Node *Node) {
// Loop over CFG successors to calculate DFlocal[Node]
BasicBlock *BB = Node->getBlock();
DomSetType &S = Frontiers[BB]; // The new set to fill in...
if (getRoots().empty()) return S;
if (BB)
for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB);
SI != SE; ++SI)
// Does Node immediately dominate this predecessor?
if (DT[*SI]->getIDom() != Node)
S.insert(*SI);
// At this point, S is DFlocal. Now we union in DFup's of our children...
// Loop through and visit the nodes that Node immediately dominates (Node's
// children in the IDomTree)
//
for (PostDominatorTree::Node::const_iterator
NI = Node->begin(), NE = Node->end(); NI != NE; ++NI) {
DominatorTree::Node *IDominee = *NI;
const DomSetType &ChildDF = calculate(DT, IDominee);
DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
for (; CDFI != CDFE; ++CDFI) {
if (!Node->properlyDominates(DT[*CDFI]))
S.insert(*CDFI);
}
}
return S;
}
// Ensure that this .cpp file gets linked when PostDominators.h is used.
DEFINING_FILE_FOR(PostDominanceFrontier)
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee++ --- Site
*
* This file defines (Const)Site, (Const)SiteHost, (Const)SiteService, and
* (Const)SiteLocation, wrapper of ib_site_t, ib_site_host_t,
* ib_site_service_t, and ib_site_location_t, respectively.
*
* Provided functionality is currently minimal. It may be expanded once the
* C site code matures.
*
* @remark Developers should be familiar with @ref ironbeepp to understand
* aspects of this code, e.g., the public/non-virtual inheritance
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#ifndef __IBPP__SITE__
#define __IBPP__SITE__
#include <ironbeepp/abi_compatibility.hpp>
#include <ironbeepp/common_semantics.hpp>
#include <ironbeepp/engine.hpp>
#include <ironbeepp/memory_pool.hpp>
#include <boost/uuid/uuid.hpp>
#include <ostream>
// IronBee C
typedef struct ib_site_t ib_site_t;
typedef struct ib_site_host_t ib_site_host_t;
typedef struct ib_site_service_t ib_site_service_t;
typedef struct ib_site_location_t ib_site_location_t;
namespace IronBee {
class ConstSite;
/**
* Const SiteHost; equivalent to a const pointer to ib_site_host_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* @sa SiteHost
* @sa ironbeepp
* @sa ib_site_host_t
* @nosubgrouping
**/
class ConstSiteHost :
public CommonSemantics<ConstSiteHost>
{
public:
//! C Type.
typedef const ib_site_host_t* ib_type;
/**
* Construct singular ConstSiteHost.
*
* All behavior of a singular ConstSiteHost is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSiteHost();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_host_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteHost from ib_site_host_t.
explicit
ConstSiteHost(ib_type ib_site_host);
///@}
//! Site accessor.
ConstSite site() const;
//! Hostname accessor.
const char* hostname() const;
//! Suffix accessor.
const char* suffix() const;
private:
ib_type m_ib;
};
/**
* SiteHost; equivalent to a pointer to ib_site_host_t.
*
* SiteHost can be treated as ConstSiteHost. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSiteHost
* @sa ironbeepp
* @sa ib_site_host_t
* @nosubgrouping
**/
class SiteHost :
public ConstSiteHost
{
public:
//! C Type.
typedef ib_site_host_t* ib_type;
/**
* Remove the constness of a ConstSiteHost.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] site_host ConstSiteHost to remove const from.
* @returns SiteHost pointing to same underlying sitehost as @a site_host.
**/
static SiteHost remove_const(ConstSiteHost site_host);
/**
* Construct singular SiteHost.
*
* All behavior of a singular SiteHost is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
SiteHost();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_host_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteHost from ib_site_host_t.
explicit
SiteHost(ib_type ib_site_host);
///@}
private:
ib_type m_ib;
};
/**
* Output operator for SiteHost.
*
* Output IronBee::SiteHost[@e value] where @e value is the hostname.
*
* @param[in] o Ostream to output to.
* @param[in] site_host SiteHost to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSiteHost& site_host);
/**
* Const SiteService; equivalent to a const pointer to ib_site_service_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* @sa SiteService
* @sa ironbeepp
* @sa ib_site_service_t
* @nosubgrouping
**/
class ConstSiteService :
public CommonSemantics<ConstSiteService>
{
public:
//! C Type.
typedef const ib_site_service_t* ib_type;
/**
* Construct singular ConstSiteService.
*
* All behavior of a singular ConstSiteService is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSiteService();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_service_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteService from ib_site_service_t.
explicit
ConstSiteService(ib_type ib_site_service);
///@}
//! Site accessor.
ConstSite site() const;
//! IP address accessor.
const char* ip_as_s() const;
//! Port accessor.
int port() const;
private:
ib_type m_ib;
};
/**
* SiteService; equivalent to a pointer to ib_site_service_t.
*
* SiteService can be treated as ConstSiteService. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSiteService
* @sa ironbeepp
* @sa ib_site_service_t
* @nosubgrouping
**/
class SiteService :
public ConstSiteService
{
public:
//! C Type.
typedef ib_site_service_t* ib_type;
/**
* Remove the constness of a ConstSiteService.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] site_service ConstSiteService to remove const from.
* @returns SiteService pointing to same underlying site service as @a site_service.
**/
static SiteService remove_const(ConstSiteService site_service);
/**
* Construct singular SiteService.
*
* All behavior of a singular SiteService is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
SiteService();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_service_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteService from ib_site_service_t.
explicit
SiteService(ib_type ib_site_service);
///@}
private:
ib_type m_ib;
};
/**
* Const SiteLocation; equivalent to a const pointer to ib_site_location_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* @tparam T Value type for location.
*
* @sa SiteLocation
* @sa ironbeepp
* @sa ib_site_location_t
* @nosubgrouping
**/
class ConstSiteLocation :
public CommonSemantics<ConstSiteLocation>
{
public:
//! C Type.
typedef const ib_site_location_t* ib_type;
/**
* Construct singular ConstSiteLocation.
*
* All behavior of a singular ConstSiteLocation is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSiteLocation();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_location_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteLocation from ib_site_location_t.
explicit
ConstSiteLocation(ib_type ib_location);
///@}
//! Site accessor.
ConstSite site() const;
//! Path accessor.
const char* path() const;
//! Context accessor.
Context context() const;
private:
ib_type m_ib;
};
/**
* SiteLocation; equivalent to a pointer to ib_site_location_t.
*
* SiteLocation can be treated as ConstSiteLocation. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSiteLocation
* @sa ironbeepp
* @sa ib_site_location_t
* @nosubgrouping
**/
class SiteLocation :
public ConstSiteLocation
{
public:
//! C Type.
typedef ib_site_location_t* ib_type;
/**
* Remove the constness of a ConstSiteLocation.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] location ConstSiteLocation to remove const from.
* @returns SiteLocation pointing to same underlying location as @a location.
**/
static SiteLocation remove_const(ConstSiteLocation location);
/**
* Construct singular SiteLocation.
*
* All behavior of a singular SiteLocation is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
SiteLocation();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_location_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteLocation from ib_site_location_t.
explicit
SiteLocation(ib_type ib_location);
///@}
private:
ib_type m_ib;
};
/**
* Output operator for SiteLocation.
*
* Outputs SiteLocation[@e value] to @a o where @e value is replaced with
* the path of the location.
*
* @param[in] o Ostream to output to.
* @param[in] location SiteLocation to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSiteLocation& location);
/**
* Output operator for SiteService.
*
* Output IronBee::SiteService[@e value] where @e value is XXX.
*
* @param[in] o Ostream to output to.
* @param[in] site_service SiteService to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSiteService& site_service);
/**
* Const Site; equivalent to a const pointer to ib_site_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* See Site for discussion of sites.
*
* @tparam T Value type for site.
*
* @sa Site
* @sa ironbeepp
* @sa ib_site_t
* @nosubgrouping
**/
class ConstSite :
public CommonSemantics<ConstSite>
{
public:
//! C Type.
typedef const ib_site_t* ib_type;
/**
* Construct singular ConstSite.
*
* All behavior of a singular ConstSite is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSite();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct Site from ib_site_t.
explicit
ConstSite(ib_type ib_site);
///@}
//! ID as UUID.
const boost::uuids::uuid& id() const;
//! ID as string.
const char* id_as_s() const;
//! Associated memory pool.
MemoryPool memory_pool() const;
//! Name.
const char* name() const;
//! Context.
Context context() const;
private:
ib_type m_ib;
};
/**
* Site; equivalent to a pointer to ib_site_t.
*
* Site can be treated as ConstSite. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSite
* @sa ironbeepp
* @sa ib_site_t
* @nosubgrouping
**/
class Site :
public ConstSite
{
public:
//! C Type.
typedef ib_site_t* ib_type;
/**
* Remove the constness of a ConstSite.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] site ConstSite to remove const from.
* @returns Site pointing to same underlying site as @a site.
**/
static Site remove_const(ConstSite site);
/**
* Construct singular Site.
*
* All behavior of a singular Site is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
Site();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct Site from ib_site_t.
explicit
Site(ib_type ib_site);
///@}
private:
ib_type m_ib;
};
/**
* Output operator for Site.
*
* Outputs Site[@e value] to @a o where @e value is replaced with
* the name of the site.
*
* @param[in] o Ostream to output to.
* @param[in] site Site to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSite& site);
} // IronBee
#endif
<commit_msg>ironbee++/site: Minor documentation cleanup.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee++ --- Site
*
* This file defines (Const)Site, (Const)SiteHost, (Const)SiteService, and
* (Const)SiteLocation, wrapper of ib_site_t, ib_site_host_t,
* ib_site_service_t, and ib_site_location_t, respectively.
*
* Provided functionality is currently minimal. It may be expanded once the
* C site code matures.
*
* @remark Developers should be familiar with @ref ironbeepp to understand
* aspects of this code, e.g., the public/non-virtual inheritance
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#ifndef __IBPP__SITE__
#define __IBPP__SITE__
#include <ironbeepp/abi_compatibility.hpp>
#include <ironbeepp/common_semantics.hpp>
#include <ironbeepp/engine.hpp>
#include <ironbeepp/memory_pool.hpp>
#include <boost/uuid/uuid.hpp>
#include <ostream>
// IronBee C
typedef struct ib_site_t ib_site_t;
typedef struct ib_site_host_t ib_site_host_t;
typedef struct ib_site_service_t ib_site_service_t;
typedef struct ib_site_location_t ib_site_location_t;
namespace IronBee {
class ConstSite;
/**
* Const SiteHost; equivalent to a const pointer to ib_site_host_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* @sa SiteHost
* @sa ironbeepp
* @sa ib_site_host_t
* @nosubgrouping
**/
class ConstSiteHost :
public CommonSemantics<ConstSiteHost>
{
public:
//! C Type.
typedef const ib_site_host_t* ib_type;
/**
* Construct singular ConstSiteHost.
*
* All behavior of a singular ConstSiteHost is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSiteHost();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_host_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteHost from ib_site_host_t.
explicit
ConstSiteHost(ib_type ib_site_host);
///@}
//! Site accessor.
ConstSite site() const;
//! Hostname accessor.
const char* hostname() const;
//! Suffix accessor.
const char* suffix() const;
private:
ib_type m_ib;
};
/**
* SiteHost; equivalent to a pointer to ib_site_host_t.
*
* SiteHost can be treated as ConstSiteHost. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSiteHost
* @sa ironbeepp
* @sa ib_site_host_t
* @nosubgrouping
**/
class SiteHost :
public ConstSiteHost
{
public:
//! C Type.
typedef ib_site_host_t* ib_type;
/**
* Remove the constness of a ConstSiteHost.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] site_host ConstSiteHost to remove const from.
* @returns SiteHost pointing to same underlying sitehost as @a site_host.
**/
static SiteHost remove_const(ConstSiteHost site_host);
/**
* Construct singular SiteHost.
*
* All behavior of a singular SiteHost is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
SiteHost();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_host_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteHost from ib_site_host_t.
explicit
SiteHost(ib_type ib_site_host);
///@}
private:
ib_type m_ib;
};
/**
* Output operator for SiteHost.
*
* Output IronBee::SiteHost[@e value] where @e value is the hostname.
*
* @param[in] o Ostream to output to.
* @param[in] site_host SiteHost to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSiteHost& site_host);
/**
* Const SiteService; equivalent to a const pointer to ib_site_service_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* @sa SiteService
* @sa ironbeepp
* @sa ib_site_service_t
* @nosubgrouping
**/
class ConstSiteService :
public CommonSemantics<ConstSiteService>
{
public:
//! C Type.
typedef const ib_site_service_t* ib_type;
/**
* Construct singular ConstSiteService.
*
* All behavior of a singular ConstSiteService is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSiteService();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_service_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteService from ib_site_service_t.
explicit
ConstSiteService(ib_type ib_site_service);
///@}
//! Site accessor.
ConstSite site() const;
//! IP address accessor.
const char* ip_as_s() const;
//! Port accessor.
int port() const;
private:
ib_type m_ib;
};
/**
* SiteService; equivalent to a pointer to ib_site_service_t.
*
* SiteService can be treated as ConstSiteService. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSiteService
* @sa ironbeepp
* @sa ib_site_service_t
* @nosubgrouping
**/
class SiteService :
public ConstSiteService
{
public:
//! C Type.
typedef ib_site_service_t* ib_type;
/**
* Remove the constness of a ConstSiteService.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] site_service ConstSiteService to remove const from.
* @returns SiteService pointing to same underlying site service as @a site_service.
**/
static SiteService remove_const(ConstSiteService site_service);
/**
* Construct singular SiteService.
*
* All behavior of a singular SiteService is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
SiteService();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_service_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteService from ib_site_service_t.
explicit
SiteService(ib_type ib_site_service);
///@}
private:
ib_type m_ib;
};
/**
* Const SiteLocation; equivalent to a const pointer to ib_site_location_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* @tparam T Value type for location.
*
* @sa SiteLocation
* @sa ironbeepp
* @sa ib_site_location_t
* @nosubgrouping
**/
class ConstSiteLocation :
public CommonSemantics<ConstSiteLocation>
{
public:
//! C Type.
typedef const ib_site_location_t* ib_type;
/**
* Construct singular ConstSiteLocation.
*
* All behavior of a singular ConstSiteLocation is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSiteLocation();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_location_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteLocation from ib_site_location_t.
explicit
ConstSiteLocation(ib_type ib_location);
///@}
//! Site accessor.
ConstSite site() const;
//! Path accessor.
const char* path() const;
//! Context accessor.
Context context() const;
private:
ib_type m_ib;
};
/**
* SiteLocation; equivalent to a pointer to ib_site_location_t.
*
* SiteLocation can be treated as ConstSiteLocation. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSiteLocation
* @sa ironbeepp
* @sa ib_site_location_t
* @nosubgrouping
**/
class SiteLocation :
public ConstSiteLocation
{
public:
//! C Type.
typedef ib_site_location_t* ib_type;
/**
* Remove the constness of a ConstSiteLocation.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] location ConstSiteLocation to remove const from.
* @returns SiteLocation pointing to same underlying location as @a location.
**/
static SiteLocation remove_const(ConstSiteLocation location);
/**
* Construct singular SiteLocation.
*
* All behavior of a singular SiteLocation is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
SiteLocation();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_location_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct SiteLocation from ib_site_location_t.
explicit
SiteLocation(ib_type ib_location);
///@}
private:
ib_type m_ib;
};
/**
* Output operator for SiteLocation.
*
* Outputs SiteLocation[@e value] to @a o where @e value is replaced with
* the path of the location.
*
* @param[in] o Ostream to output to.
* @param[in] location SiteLocation to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSiteLocation& location);
/**
* Output operator for SiteService.
*
* Output IronBee::SiteService[@e value] where @e value is hostname.
*
* @param[in] o Ostream to output to.
* @param[in] site_service SiteService to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSiteService& site_service);
/**
* Const Site; equivalent to a const pointer to ib_site_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* See Site for discussion of sites.
*
* @tparam T Value type for site.
*
* @sa Site
* @sa ironbeepp
* @sa ib_site_t
* @nosubgrouping
**/
class ConstSite :
public CommonSemantics<ConstSite>
{
public:
//! C Type.
typedef const ib_site_t* ib_type;
/**
* Construct singular ConstSite.
*
* All behavior of a singular ConstSite is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstSite();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_site_t accessor.
// Intentionally inlined.
ib_type ib() const
{
return m_ib;
}
//! Construct Site from ib_site_t.
explicit
ConstSite(ib_type ib_site);
///@}
//! ID as UUID.
const boost::uuids::uuid& id() const;
//! ID as string.
const char* id_as_s() const;
//! Associated memory pool.
MemoryPool memory_pool() const;
//! Name.
const char* name() const;
//! Context.
Context context() const;
private:
ib_type m_ib;
};
/**
* Site; equivalent to a pointer to ib_site_t.
*
* Site can be treated as ConstSite. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* Provides no functionality besides non-const ib() access.
*
* @sa ConstSite
* @sa ironbeepp
* @sa ib_site_t
* @nosubgrouping
**/
class Site :
public ConstSite
{
public:
//! C Type.
typedef ib_site_t* ib_type;
/**
* Remove the constness of a ConstSite.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] site ConstSite to remove const from.
* @returns Site pointing to same underlying site as @a site.
**/
static Site remove_const(ConstSite site);
/**
* Construct singular Site.
*
* All behavior of a singular Site is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
Site();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! ib_site_t accessor.
ib_type ib() const
{
return m_ib;
}
//! Construct Site from ib_site_t.
explicit
Site(ib_type ib_site);
///@}
private:
ib_type m_ib;
};
/**
* Output operator for Site.
*
* Outputs Site[@e value] to @a o where @e value is replaced with
* the name of the site.
*
* @param[in] o Ostream to output to.
* @param[in] site Site to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstSite& site);
} // IronBee
#endif
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef registrardb_hh
#define registrardb_hh
#include <map>
#include <list>
#include <set>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <limits>
#include <mutex>
#include <iosfwd>
#include <sofia-sip/sip.h>
#include <sofia-sip/url.h>
#include "log/logmanager.hh"
#include "agent.hh"
#include <string>
#include <list>
#define AOR_KEY_SIZE 128
struct ExtendedContactCommon {
std::string mContactId;
std::string mCallId;
std::string mLineValueCopy;
std::list<std::string> mPath;
ExtendedContactCommon(const char *contactId, const std::list<std::string> &path, const char* callId, const char *lineValue) {
if (callId) mCallId = callId;
mPath = path;
if (lineValue) mLineValueCopy = lineValue;
mContactId = contactId;
}
ExtendedContactCommon(const std::string &route) : mContactId(), mCallId(),mLineValueCopy(),mPath({route}) {};
};
struct ExtendedContact {
class Record;
friend class Record;
std::string mContactId;
std::string mCallId;
std::string mLineValueCopy;
std::list<std::string> mPath;
std::string mSipUri;
float mQ;
time_t mExpireAt;
time_t mUpdatedTime;
uint32_t mCSeq;
bool mAlias;
inline const char *callId() { return mCallId.c_str(); }
inline const char *line() { return mLineValueCopy.c_str(); }
inline const char *contactId() { return mContactId.c_str(); }
inline const char *route() { return (mPath.empty() ? NULL : mPath.cbegin()->c_str()); }
static int resolve_expire(const char *contact_expire, int global_expire) {
if (contact_expire) {
return atoi(contact_expire);
} else {
if(global_expire >= 0) {
return global_expire;
} else {
return -1;
}
}
}
ExtendedContact(const ExtendedContactCommon &common,
sip_contact_t *sip_contact, int global_expire, uint32_t cseq, time_t updateTime, bool alias) :
mContactId(common.mContactId), mCallId(common.mCallId), mLineValueCopy(common.mLineValueCopy), mPath(common.mPath),
mSipUri(),
mQ(0), mUpdatedTime(updateTime), mCSeq(cseq), mAlias(alias) {
{
su_home_t home;
su_home_init(&home);
mSipUri = ExtendedContact::format_url(&home, sip_contact->m_url);
su_home_destroy(&home);
}
if (sip_contact->m_q) {
mQ = atof(sip_contact->m_q);
}
int expire = resolve_expire(sip_contact->m_expires, global_expire);
if (expire == -1) SLOGA << "no global expire nor local contact expire found";
mExpireAt = updateTime + expire;
}
ExtendedContact(const ExtendedContactCommon &common,
const char *sipuri, long expireAt, float q, uint32_t cseq, time_t updateTime, bool alias) :
mContactId(common.mContactId), mCallId(common.mCallId), mLineValueCopy(common.mLineValueCopy), mPath(common.mPath),
mSipUri(sipuri),
mQ(q), mExpireAt(expireAt), mUpdatedTime(updateTime), mCSeq(cseq), mAlias(alias){
}
ExtendedContact(const url_t *url, std::string route) :
mContactId(), mCallId(), mLineValueCopy(), mPath({route}),
mSipUri(),
mQ(0), mExpireAt(LONG_MAX), mUpdatedTime(0), mCSeq(0), mAlias(false){
su_home_t home;
su_home_init(&home);
mSipUri = ExtendedContact::format_url(&home, url);
su_home_destroy(&home);
}
static char* format_url(su_home_t *home, const url_t *url) {
const char * port = (url->url_port) ? url->url_port : "5060";
if (url->url_params) {
if (url->url_user) {
return su_sprintf(home, "<sip:%s@%s:%s;%s>", url->url_user, url->url_host, port, url->url_params);
} else {
return su_sprintf(home, "<sip:%s:%s;%s>", url->url_host, port, url->url_params);
}
} else {
if (url->url_user) {
return su_sprintf(home, "<sip:%s@%s:%s>", url->url_user, url->url_host, port);
} else {
return su_sprintf(home, "<sip:%s:%s>", url->url_host, port);
}
}
}
std::ostream &print(std::ostream & stream, time_t now, time_t offset = 0) const;
};
/*
std::ostream &operator<<(std::ostream & stream, const ExtendedContact &ec) {
return stream;
}
*/
class Record {
friend class RecursiveRegistrarDbListener;
friend class RegistrarDb;
private:
static void init();
void insertOrUpdateBinding(const std::shared_ptr<ExtendedContact> &ec);
std::list<std::shared_ptr<ExtendedContact>> mContacts;
std::string mKey;
public:
static std::list<std::string> sLineFieldNames;
static int sMaxContacts;
protected:
static char sStaticRecordVersion[100];
public:
Record(std::string key);
static std::string extractUniqueId(const sip_contact_t *contact);
static std::string extractUniqueId(const url_t *url);
static sip_contact_t *extendedContactToSofia(su_home_t *home, const ExtendedContact &ec, time_t now);
const sip_contact_t * getContacts(su_home_t *home, time_t now);
bool isInvalidRegister(const char *call_id, uint32_t cseq);
void clean(const sip_contact_t *sip, const char *call_id, uint32_t cseq, time_t time);
void clean(time_t time);
void update(const sip_contact_t *contacts, const sip_path_t *path, int globalExpire, const char *call_id, uint32_t cseq, time_t now, bool alias);
void update(const ExtendedContactCommon &ecc, const char* sipuri, long int expireAt, float q, uint32_t cseq, time_t updated_time, bool alias);
void print(std::ostream &stream) const;
bool isEmpty() { return mContacts.empty(); };
const std::string &getKey() const {
return mKey;
}
void setKey(const char *key) {
mKey=key;
}
int count() {
return mContacts.size();
}
const std::list<std::shared_ptr<ExtendedContact>> &getExtendedContacts() const {
return mContacts;
}
static int getMaxContacts() {
if (sMaxContacts == -1)
init();
return sMaxContacts;
}
time_t latestExpire() const;
time_t latestExpire(const std::string &route) const;
static void setStaticRecordsVersion(int version) {
static int maxlen=sizeof(sStaticRecordVersion);
memset(sStaticRecordVersion, 0, maxlen);
if (version != 0) {
snprintf(sStaticRecordVersion, maxlen, "static-record-v%d", version);
}
}
static std::list<std::string> route_to_stl(su_home_t *home, const sip_route_s *route);
~Record();
};
template< typename TraitsT >
inline std::basic_ostream< char, TraitsT >& operator<< (
std::basic_ostream< char, TraitsT >& strm, const Record &record)
{
record.print(strm);
return strm;
}
class RegistrarDbListener: public StatFinishListener {
public:
~RegistrarDbListener() {
}
virtual void onRecordFound(Record *r) = 0;
virtual void onError() = 0;
virtual void onInvalid() {
/*let the registration timeout;*/
}
};
/**
* A singleton class which holds records contact addresses associated with a from.
* Both local and remote storage implementations exist.
* It is used by the Registrar module.
**/
class RegistrarDb {
friend class ModuleRegistrar;
public:
struct BindParameters {
/**
* Parameter wrapper class that doesn't copy anything.
*/ struct SipParams {
const url_t* from;
const sip_contact_t *contact;
const char * call_id;
const uint32_t cs_seq;
const sip_path_t *path;
SipParams(const url_t* from, const sip_contact_t *contact,
const char *id, uint32_t seq, const sip_path_t *path)
: from(from), contact(contact), call_id(id), cs_seq(seq), path(path) {
}
};
const SipParams sip;
const int global_expire;
const bool alias;
BindParameters(SipParams sip, int expire, bool alias)
: sip(sip), global_expire(expire), alias(alias) {
}
};
static RegistrarDb *get(Agent *ag);
void bind(const BindParameters &mainParams, const std::shared_ptr<RegistrarDbListener> &listener) {
doBind(mainParams, listener);
}
void bind(const sip_t *sip, int globalExpire, bool alias, const std::shared_ptr<RegistrarDbListener> &listener) {
BindParameters mainParams(
BindParameters::SipParams(
sip->sip_from->a_url,
sip->sip_contact,
sip->sip_call_id->i_id,
sip->sip_cseq->cs_seq, sip->sip_path),
globalExpire, alias);
doBind(mainParams, listener);
}
void clear(const sip_t *sip, const std::shared_ptr<RegistrarDbListener> &listener);
void fetch(const url_t *url, const std::shared_ptr<RegistrarDbListener> &listener, bool recursive = false);
void updateRemoteExpireTime(const std::string &key, time_t expireat);
unsigned long countLocalActiveRecords() {
return mLocalRegExpire->countActives();
}
void useGlobalDomain(bool useGlobalDomain);
protected:
class LocalRegExpire {
std::map<std::string, time_t> mRegMap;
std::mutex mMutex;
std::string mPreferedRoute;
public:
void remove(const std::string key) {
mRegMap.erase(key);
}
void update(const Record &record);
size_t countActives();
void removeExpiredBefore(time_t before);
LocalRegExpire(std::string preferedRoute);
void clearAll() {
std::lock_guard<std::mutex> lock(mMutex);
mRegMap.clear();
}
};
virtual void doBind(const BindParameters ¶ms, const std::shared_ptr<RegistrarDbListener> &listener)=0;
virtual void doClear(const sip_t *sip, const std::shared_ptr<RegistrarDbListener> &listener)=0;
virtual void doFetch(const url_t *url, const std::shared_ptr<RegistrarDbListener> &listener)=0;
int count_sip_contacts(const sip_contact_t *contact);
bool errorOnTooMuchContactInBind(const sip_contact_t *sip_contact, const char *key, const std::shared_ptr<RegistrarDbListener> &listener);
void defineKeyFromUrl(char *key, int len, const url_t *url);
RegistrarDb(const std::string &preferedRoute);
virtual ~RegistrarDb();
std::map<std::string, Record*> mRecords;
LocalRegExpire *mLocalRegExpire;
bool mUseGlobalDomain;
static RegistrarDb *sUnique;
};
#endif
<commit_msg>Preserve sips scheme during registration.<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef registrardb_hh
#define registrardb_hh
#include <map>
#include <list>
#include <set>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <limits>
#include <mutex>
#include <iosfwd>
#include <sofia-sip/sip.h>
#include <sofia-sip/url.h>
#include "log/logmanager.hh"
#include "agent.hh"
#include <string>
#include <list>
#define AOR_KEY_SIZE 128
struct ExtendedContactCommon {
std::string mContactId;
std::string mCallId;
std::string mLineValueCopy;
std::list<std::string> mPath;
ExtendedContactCommon(const char *contactId, const std::list<std::string> &path, const char* callId, const char *lineValue) {
if (callId) mCallId = callId;
mPath = path;
if (lineValue) mLineValueCopy = lineValue;
mContactId = contactId;
}
ExtendedContactCommon(const std::string &route) : mContactId(), mCallId(),mLineValueCopy(),mPath({route}) {};
};
struct ExtendedContact {
class Record;
friend class Record;
std::string mContactId;
std::string mCallId;
std::string mLineValueCopy;
std::list<std::string> mPath;
std::string mSipUri;
float mQ;
time_t mExpireAt;
time_t mUpdatedTime;
uint32_t mCSeq;
bool mAlias;
inline const char *callId() { return mCallId.c_str(); }
inline const char *line() { return mLineValueCopy.c_str(); }
inline const char *contactId() { return mContactId.c_str(); }
inline const char *route() { return (mPath.empty() ? NULL : mPath.cbegin()->c_str()); }
static int resolve_expire(const char *contact_expire, int global_expire) {
if (contact_expire) {
return atoi(contact_expire);
} else {
if(global_expire >= 0) {
return global_expire;
} else {
return -1;
}
}
}
ExtendedContact(const ExtendedContactCommon &common,
sip_contact_t *sip_contact, int global_expire, uint32_t cseq, time_t updateTime, bool alias) :
mContactId(common.mContactId), mCallId(common.mCallId), mLineValueCopy(common.mLineValueCopy), mPath(common.mPath),
mSipUri(),
mQ(0), mUpdatedTime(updateTime), mCSeq(cseq), mAlias(alias) {
{
su_home_t home;
su_home_init(&home);
mSipUri = url_as_string(&home, sip_contact->m_url);
su_home_destroy(&home);
}
if (sip_contact->m_q) {
mQ = atof(sip_contact->m_q);
}
int expire = resolve_expire(sip_contact->m_expires, global_expire);
if (expire == -1) SLOGA << "no global expire nor local contact expire found";
mExpireAt = updateTime + expire;
}
ExtendedContact(const ExtendedContactCommon &common,
const char *sipuri, long expireAt, float q, uint32_t cseq, time_t updateTime, bool alias) :
mContactId(common.mContactId), mCallId(common.mCallId), mLineValueCopy(common.mLineValueCopy), mPath(common.mPath),
mSipUri(sipuri),
mQ(q), mExpireAt(expireAt), mUpdatedTime(updateTime), mCSeq(cseq), mAlias(alias){
}
ExtendedContact(const url_t *url, std::string route) :
mContactId(), mCallId(), mLineValueCopy(), mPath({route}),
mSipUri(),
mQ(0), mExpireAt(LONG_MAX), mUpdatedTime(0), mCSeq(0), mAlias(false){
su_home_t home;
su_home_init(&home);
mSipUri = url_as_string(&home, url);
su_home_destroy(&home);
}
std::ostream &print(std::ostream & stream, time_t now, time_t offset = 0) const;
};
/*
std::ostream &operator<<(std::ostream & stream, const ExtendedContact &ec) {
return stream;
}
*/
class Record {
friend class RecursiveRegistrarDbListener;
friend class RegistrarDb;
private:
static void init();
void insertOrUpdateBinding(const std::shared_ptr<ExtendedContact> &ec);
std::list<std::shared_ptr<ExtendedContact>> mContacts;
std::string mKey;
public:
static std::list<std::string> sLineFieldNames;
static int sMaxContacts;
protected:
static char sStaticRecordVersion[100];
public:
Record(std::string key);
static std::string extractUniqueId(const sip_contact_t *contact);
static std::string extractUniqueId(const url_t *url);
static sip_contact_t *extendedContactToSofia(su_home_t *home, const ExtendedContact &ec, time_t now);
const sip_contact_t * getContacts(su_home_t *home, time_t now);
bool isInvalidRegister(const char *call_id, uint32_t cseq);
void clean(const sip_contact_t *sip, const char *call_id, uint32_t cseq, time_t time);
void clean(time_t time);
void update(const sip_contact_t *contacts, const sip_path_t *path, int globalExpire, const char *call_id, uint32_t cseq, time_t now, bool alias);
void update(const ExtendedContactCommon &ecc, const char* sipuri, long int expireAt, float q, uint32_t cseq, time_t updated_time, bool alias);
void print(std::ostream &stream) const;
bool isEmpty() { return mContacts.empty(); };
const std::string &getKey() const {
return mKey;
}
void setKey(const char *key) {
mKey=key;
}
int count() {
return mContacts.size();
}
const std::list<std::shared_ptr<ExtendedContact>> &getExtendedContacts() const {
return mContacts;
}
static int getMaxContacts() {
if (sMaxContacts == -1)
init();
return sMaxContacts;
}
time_t latestExpire() const;
time_t latestExpire(const std::string &route) const;
static void setStaticRecordsVersion(int version) {
static int maxlen=sizeof(sStaticRecordVersion);
memset(sStaticRecordVersion, 0, maxlen);
if (version != 0) {
snprintf(sStaticRecordVersion, maxlen, "static-record-v%d", version);
}
}
static std::list<std::string> route_to_stl(su_home_t *home, const sip_route_s *route);
~Record();
};
template< typename TraitsT >
inline std::basic_ostream< char, TraitsT >& operator<< (
std::basic_ostream< char, TraitsT >& strm, const Record &record)
{
record.print(strm);
return strm;
}
class RegistrarDbListener: public StatFinishListener {
public:
~RegistrarDbListener() {
}
virtual void onRecordFound(Record *r) = 0;
virtual void onError() = 0;
virtual void onInvalid() {
/*let the registration timeout;*/
}
};
/**
* A singleton class which holds records contact addresses associated with a from.
* Both local and remote storage implementations exist.
* It is used by the Registrar module.
**/
class RegistrarDb {
friend class ModuleRegistrar;
public:
struct BindParameters {
/**
* Parameter wrapper class that doesn't copy anything.
*/ struct SipParams {
const url_t* from;
const sip_contact_t *contact;
const char * call_id;
const uint32_t cs_seq;
const sip_path_t *path;
SipParams(const url_t* from, const sip_contact_t *contact,
const char *id, uint32_t seq, const sip_path_t *path)
: from(from), contact(contact), call_id(id), cs_seq(seq), path(path) {
}
};
const SipParams sip;
const int global_expire;
const bool alias;
BindParameters(SipParams sip, int expire, bool alias)
: sip(sip), global_expire(expire), alias(alias) {
}
};
static RegistrarDb *get(Agent *ag);
void bind(const BindParameters &mainParams, const std::shared_ptr<RegistrarDbListener> &listener) {
doBind(mainParams, listener);
}
void bind(const sip_t *sip, int globalExpire, bool alias, const std::shared_ptr<RegistrarDbListener> &listener) {
BindParameters mainParams(
BindParameters::SipParams(
sip->sip_from->a_url,
sip->sip_contact,
sip->sip_call_id->i_id,
sip->sip_cseq->cs_seq, sip->sip_path),
globalExpire, alias);
doBind(mainParams, listener);
}
void clear(const sip_t *sip, const std::shared_ptr<RegistrarDbListener> &listener);
void fetch(const url_t *url, const std::shared_ptr<RegistrarDbListener> &listener, bool recursive = false);
void updateRemoteExpireTime(const std::string &key, time_t expireat);
unsigned long countLocalActiveRecords() {
return mLocalRegExpire->countActives();
}
void useGlobalDomain(bool useGlobalDomain);
protected:
class LocalRegExpire {
std::map<std::string, time_t> mRegMap;
std::mutex mMutex;
std::string mPreferedRoute;
public:
void remove(const std::string key) {
mRegMap.erase(key);
}
void update(const Record &record);
size_t countActives();
void removeExpiredBefore(time_t before);
LocalRegExpire(std::string preferedRoute);
void clearAll() {
std::lock_guard<std::mutex> lock(mMutex);
mRegMap.clear();
}
};
virtual void doBind(const BindParameters ¶ms, const std::shared_ptr<RegistrarDbListener> &listener)=0;
virtual void doClear(const sip_t *sip, const std::shared_ptr<RegistrarDbListener> &listener)=0;
virtual void doFetch(const url_t *url, const std::shared_ptr<RegistrarDbListener> &listener)=0;
int count_sip_contacts(const sip_contact_t *contact);
bool errorOnTooMuchContactInBind(const sip_contact_t *sip_contact, const char *key, const std::shared_ptr<RegistrarDbListener> &listener);
void defineKeyFromUrl(char *key, int len, const url_t *url);
RegistrarDb(const std::string &preferedRoute);
virtual ~RegistrarDb();
std::map<std::string, Record*> mRecords;
LocalRegExpire *mLocalRegExpire;
bool mUseGlobalDomain;
static RegistrarDb *sUnique;
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Unit tests for alert system
//
#include "alert.h"
#include "chain.h"
#include "chainparams.h"
#include "clientversion.h"
#include "data/alertTests.raw.h"
#include "chainparams.h"
#include "main.h"
#include "serialize.h"
#include "streams.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h"
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#if 0
//
// alertTests contains 7 alerts, generated with this code:
// (SignAndSave code not shown, alert signing key is secret)
//
{
CAlert alert;
alert.nRelayUntil = 60;
alert.nExpiration = 24 * 60 * 60;
alert.nID = 1;
alert.nCancel = 0; // cancels previous messages up to this ID number
alert.nMinVer = 0; // These versions are protocol versions
alert.nMaxVer = 999001;
alert.nPriority = 1;
alert.strComment = "Alert comment";
alert.strStatusBar = "Alert 1";
SignAndSave(alert, "test/alertTests");
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0";
SignAndSave(alert, "test/alertTests");
alert.setSubVer.insert(std::string("/Satoshi:0.2.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0";
SignAndSave(alert, "test/alertTests");
alert.setSubVer.clear();
++alert.nID;
alert.nCancel = 1;
alert.nPriority = 100;
alert.strStatusBar = "Alert 2, cancels 1";
SignAndSave(alert, "test/alertTests");
alert.nExpiration += 60;
++alert.nID;
SignAndSave(alert, "test/alertTests");
++alert.nID;
alert.nMinVer = 11;
alert.nMaxVer = 22;
SignAndSave(alert, "test/alertTests");
++alert.nID;
alert.strStatusBar = "Alert 2 for Satoshi 0.1.0";
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
SignAndSave(alert, "test/alertTests");
++alert.nID;
alert.nMinVer = 0;
alert.nMaxVer = 999999;
alert.strStatusBar = "Evil Alert'; /bin/ls; echo '";
alert.setSubVer.clear();
SignAndSave(alert, "test/alertTests");
}
#endif
struct ReadAlerts : public TestingSetup
{
ReadAlerts()
{
std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests));
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
try {
while (!stream.eof())
{
CAlert alert;
stream >> alert;
alerts.push_back(alert);
}
}
catch (const std::exception&) { }
}
~ReadAlerts() { }
static std::vector<std::string> read_lines(boost::filesystem::path filepath)
{
std::vector<std::string> result;
std::ifstream f(filepath.string().c_str());
std::string line;
while (std::getline(f,line))
result.push_back(line);
return result;
}
std::vector<CAlert> alerts;
};
BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts)
BOOST_AUTO_TEST_CASE(AlertApplies)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
BOOST_FOREACH(const CAlert& alert, alerts)
{
BOOST_CHECK(alert.CheckSignature(alertKey));
}
BOOST_CHECK(alerts.size() >= 3);
// Matches:
BOOST_CHECK(alerts[0].AppliesTo(1, ""));
BOOST_CHECK(alerts[0].AppliesTo(999001, ""));
BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
BOOST_CHECK(!alerts[0].AppliesTo(-1, ""));
BOOST_CHECK(!alerts[0].AppliesTo(999002, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
SetMockTime(0);
}
BOOST_AUTO_TEST_CASE(AlertNotify)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
boost::filesystem::path temp = GetTempPath() / "alertnotify.txt";
boost::filesystem::remove(temp);
mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string();
BOOST_FOREACH(CAlert alert, alerts)
alert.ProcessAlert(alertKey, false);
std::vector<std::string> r = read_lines(temp);
BOOST_CHECK_EQUAL(r.size(), 4u);
// Windows built-in echo semantics are different than posixy shells. Quotes and
// whitespace are printed literally.
#ifndef WIN32
BOOST_CHECK_EQUAL(r[0], "Alert 1");
BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed
#else
BOOST_CHECK_EQUAL(r[0], "'Alert 1' ");
BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' ");
#endif
boost::filesystem::remove(temp);
SetMockTime(0);
}
static bool falseFunc() { return false; }
BOOST_AUTO_TEST_CASE(PartitionAlert)
{
// Test PartitionCheck
CCriticalSection csDummy;
CChain chainDummy;
CBlockIndex indexDummy[100];
CChainParams& params = Params(CBaseChainParams::MAIN);
int64_t nPowTargetSpacing = params.GetConsensus().nPowTargetSpacing;
// Generate fake blockchain timestamps relative to
// an arbitrary time:
int64_t now = 1427379054;
SetMockTime(now);
for (int i = 0; i < 100; i++)
{
indexDummy[i].phashBlock = NULL;
if (i == 0) indexDummy[i].pprev = NULL;
else indexDummy[i].pprev = &indexDummy[i-1];
indexDummy[i].nHeight = i;
indexDummy[i].nTime = now - (100-i)*nPowTargetSpacing;
// Other members don't matter, the partition check code doesn't
// use them
}
chainDummy.SetTip(&indexDummy[99]);
// Test 1: chain with blocks every nPowTargetSpacing seconds,
// as normal, no worries:
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(strMiscWarning.empty());
// Test 2: go 3.5 hours without a block, expect a warning:
now += 3*60*60+30*60;
SetMockTime(now);
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(!strMiscWarning.empty());
BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning);
strMiscWarning = "";
// Test 3: test the "partition alerts only go off once per day"
// code:
now += 60*10;
SetMockTime(now);
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(strMiscWarning.empty());
// Test 4: get 2.5 times as many blocks as expected:
now += 60*60*24; // Pretend it is a day later
SetMockTime(now);
int64_t quickSpacing = nPowTargetSpacing*2/5;
for (int i = 0; i < 100; i++) // Tweak chain timestamps:
indexDummy[i].nTime = now - (100-i)*quickSpacing;
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(!strMiscWarning.empty());
BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning);
strMiscWarning = "";
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove duplicate chainparams.h include from alert_tests<commit_after>// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Unit tests for alert system
//
#include "alert.h"
#include "chain.h"
#include "chainparams.h"
#include "clientversion.h"
#include "data/alertTests.raw.h"
#include "main.h"
#include "serialize.h"
#include "streams.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h"
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#if 0
//
// alertTests contains 7 alerts, generated with this code:
// (SignAndSave code not shown, alert signing key is secret)
//
{
CAlert alert;
alert.nRelayUntil = 60;
alert.nExpiration = 24 * 60 * 60;
alert.nID = 1;
alert.nCancel = 0; // cancels previous messages up to this ID number
alert.nMinVer = 0; // These versions are protocol versions
alert.nMaxVer = 999001;
alert.nPriority = 1;
alert.strComment = "Alert comment";
alert.strStatusBar = "Alert 1";
SignAndSave(alert, "test/alertTests");
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0";
SignAndSave(alert, "test/alertTests");
alert.setSubVer.insert(std::string("/Satoshi:0.2.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0";
SignAndSave(alert, "test/alertTests");
alert.setSubVer.clear();
++alert.nID;
alert.nCancel = 1;
alert.nPriority = 100;
alert.strStatusBar = "Alert 2, cancels 1";
SignAndSave(alert, "test/alertTests");
alert.nExpiration += 60;
++alert.nID;
SignAndSave(alert, "test/alertTests");
++alert.nID;
alert.nMinVer = 11;
alert.nMaxVer = 22;
SignAndSave(alert, "test/alertTests");
++alert.nID;
alert.strStatusBar = "Alert 2 for Satoshi 0.1.0";
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
SignAndSave(alert, "test/alertTests");
++alert.nID;
alert.nMinVer = 0;
alert.nMaxVer = 999999;
alert.strStatusBar = "Evil Alert'; /bin/ls; echo '";
alert.setSubVer.clear();
SignAndSave(alert, "test/alertTests");
}
#endif
struct ReadAlerts : public TestingSetup
{
ReadAlerts()
{
std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests));
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
try {
while (!stream.eof())
{
CAlert alert;
stream >> alert;
alerts.push_back(alert);
}
}
catch (const std::exception&) { }
}
~ReadAlerts() { }
static std::vector<std::string> read_lines(boost::filesystem::path filepath)
{
std::vector<std::string> result;
std::ifstream f(filepath.string().c_str());
std::string line;
while (std::getline(f,line))
result.push_back(line);
return result;
}
std::vector<CAlert> alerts;
};
BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts)
BOOST_AUTO_TEST_CASE(AlertApplies)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
BOOST_FOREACH(const CAlert& alert, alerts)
{
BOOST_CHECK(alert.CheckSignature(alertKey));
}
BOOST_CHECK(alerts.size() >= 3);
// Matches:
BOOST_CHECK(alerts[0].AppliesTo(1, ""));
BOOST_CHECK(alerts[0].AppliesTo(999001, ""));
BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
BOOST_CHECK(!alerts[0].AppliesTo(-1, ""));
BOOST_CHECK(!alerts[0].AppliesTo(999002, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
SetMockTime(0);
}
BOOST_AUTO_TEST_CASE(AlertNotify)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
boost::filesystem::path temp = GetTempPath() / "alertnotify.txt";
boost::filesystem::remove(temp);
mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string();
BOOST_FOREACH(CAlert alert, alerts)
alert.ProcessAlert(alertKey, false);
std::vector<std::string> r = read_lines(temp);
BOOST_CHECK_EQUAL(r.size(), 4u);
// Windows built-in echo semantics are different than posixy shells. Quotes and
// whitespace are printed literally.
#ifndef WIN32
BOOST_CHECK_EQUAL(r[0], "Alert 1");
BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed
#else
BOOST_CHECK_EQUAL(r[0], "'Alert 1' ");
BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' ");
#endif
boost::filesystem::remove(temp);
SetMockTime(0);
}
static bool falseFunc() { return false; }
BOOST_AUTO_TEST_CASE(PartitionAlert)
{
// Test PartitionCheck
CCriticalSection csDummy;
CChain chainDummy;
CBlockIndex indexDummy[100];
CChainParams& params = Params(CBaseChainParams::MAIN);
int64_t nPowTargetSpacing = params.GetConsensus().nPowTargetSpacing;
// Generate fake blockchain timestamps relative to
// an arbitrary time:
int64_t now = 1427379054;
SetMockTime(now);
for (int i = 0; i < 100; i++)
{
indexDummy[i].phashBlock = NULL;
if (i == 0) indexDummy[i].pprev = NULL;
else indexDummy[i].pprev = &indexDummy[i-1];
indexDummy[i].nHeight = i;
indexDummy[i].nTime = now - (100-i)*nPowTargetSpacing;
// Other members don't matter, the partition check code doesn't
// use them
}
chainDummy.SetTip(&indexDummy[99]);
// Test 1: chain with blocks every nPowTargetSpacing seconds,
// as normal, no worries:
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(strMiscWarning.empty());
// Test 2: go 3.5 hours without a block, expect a warning:
now += 3*60*60+30*60;
SetMockTime(now);
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(!strMiscWarning.empty());
BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning);
strMiscWarning = "";
// Test 3: test the "partition alerts only go off once per day"
// code:
now += 60*10;
SetMockTime(now);
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(strMiscWarning.empty());
// Test 4: get 2.5 times as many blocks as expected:
now += 60*60*24; // Pretend it is a day later
SetMockTime(now);
int64_t quickSpacing = nPowTargetSpacing*2/5;
for (int i = 0; i < 100; i++) // Tweak chain timestamps:
indexDummy[i].nTime = now - (100-i)*quickSpacing;
PartitionCheck(falseFunc, csDummy, chainDummy, nPowTargetSpacing);
BOOST_CHECK(!strMiscWarning.empty());
BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning);
strMiscWarning = "";
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <blackhole/log.hpp>
#include "global.hpp"
#include "mocks/logger.hpp"
using namespace blackhole;
TEST(Macro, OpensInvalidLogRecordAndNotPush) {
log::record_t record;
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EXPECT_CALL(log, push(_))
.Times(0);
BH_LOG(log, level::debug, "message");
}
struct ExtractMessageAttributeAction {
std::string& actual;
void operator ()(log::record_t record) const {
actual = record.extract<std::string>("message");
}
};
TEST(Macro, OpensValidRecordAndPush) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value");
EXPECT_EQ("value", actual);
}
TEST(Macro, FormatMessageWithPrintfStyle) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah");
EXPECT_EQ("value [100500]: blah - okay", actual);
}
struct ExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
timeval timestamp;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
actual.timestamp = record.extract<timeval>("timestamp");
}
};
TEST(Macro, FormatMessageWithAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
TEST(Macro, FormatMessageWithPrintfStyleWithAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("value [100500]: blah - okay", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
namespace blackhole {
namespace format {
namespace message {
template<>
struct insitu<keyword::tag::severity_t<level>> {
static inline std::ostream& execute(std::ostream& stream, level lvl) {
static std::string DESCRIPTIONS[] = {
"DEBUG",
"INFO ",
"WARN ",
"ERROR"
};
std::size_t lvl_ = static_cast<std::size_t>(lvl);
if (lvl_ < sizeof(DESCRIPTIONS) / sizeof(DESCRIPTIONS[0])) {
stream << DESCRIPTIONS[lvl_];
} else {
stream << lvl_;
}
return stream;
}
};
} // namespace message
} // namespace format
} // namespace blackhole
TEST(Macro, SpecificKeywordMessageFormatting) {
log::record_t record;
record.attributes = {
keyword::severity<level>() = level::debug
};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value: %s", keyword::severity<level>());
EXPECT_EQ("value: DEBUG", actual);
}
struct EmplaceCheckExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
}
};
TEST(Macro, EmplaceAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EmplaceCheckExtractAttributesAction::pack_t actual;
EmplaceCheckExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
"value", 42,
"reason", "42"
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
}
namespace testing {
struct streamable_value_t {
std::string message;
int value;
friend std::ostream& operator<<(std::ostream& stream, const streamable_value_t& value) {
stream << "['" << value.message << "', " << value.value << "]";
return stream;
}
};
} // namespace testing
struct ExtractStreamableValueAttributesAction {
struct pack_t {
std::string message;
std::string value;
};
pack_t& actual;
void operator()(const log::record_t& record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<std::string>("value");
}
};
TEST(Macro, UsingStreamOperatorIfNoImplicitConversionAvailable) {
static_assert(traits::supports::stream_push<streamable_value_t>::value,
"`streamable_value_t` must support stream push operator<<");
streamable_value_t value = { "42", 42 };
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")("value", value);
EXPECT_EQ("message", actual.message);
EXPECT_EQ("['42', 42]", actual.value);
}
TEST(Macro, InitializerListAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(attribute::list{
{"value", "42"}
});
EXPECT_EQ("message", actual.message);
EXPECT_EQ("42", actual.value);
}
<commit_msg>[GCC 4.4] Fuck you, GCC 4.4.<commit_after>#include <blackhole/log.hpp>
#include "global.hpp"
#include "mocks/logger.hpp"
using namespace blackhole;
TEST(Macro, OpensInvalidLogRecordAndNotPush) {
log::record_t record;
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EXPECT_CALL(log, push(_))
.Times(0);
BH_LOG(log, level::debug, "message");
}
struct ExtractMessageAttributeAction {
std::string& actual;
void operator ()(log::record_t record) const {
actual = record.extract<std::string>("message");
}
};
TEST(Macro, OpensValidRecordAndPush) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value");
EXPECT_EQ("value", actual);
}
TEST(Macro, FormatMessageWithPrintfStyle) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah");
EXPECT_EQ("value [100500]: blah - okay", actual);
}
struct ExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
timeval timestamp;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
actual.timestamp = record.extract<timeval>("timestamp");
}
};
TEST(Macro, FormatMessageWithAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
TEST(Macro, FormatMessageWithPrintfStyleWithAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("value [100500]: blah - okay", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
namespace blackhole {
namespace format {
namespace message {
template<>
struct insitu<keyword::tag::severity_t<level>> {
static inline std::ostream& execute(std::ostream& stream, level lvl) {
static std::string DESCRIPTIONS[] = {
"DEBUG",
"INFO ",
"WARN ",
"ERROR"
};
std::size_t lvl_ = static_cast<std::size_t>(lvl);
if (lvl_ < sizeof(DESCRIPTIONS) / sizeof(DESCRIPTIONS[0])) {
stream << DESCRIPTIONS[lvl_];
} else {
stream << lvl_;
}
return stream;
}
};
} // namespace message
} // namespace format
} // namespace blackhole
TEST(Macro, SpecificKeywordMessageFormatting) {
log::record_t record;
record.attributes = {
keyword::severity<level>() = level::debug
};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value: %s", keyword::severity<level>());
EXPECT_EQ("value: DEBUG", actual);
}
struct EmplaceCheckExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
}
};
TEST(Macro, EmplaceAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EmplaceCheckExtractAttributesAction::pack_t actual;
EmplaceCheckExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
"value", 42,
"reason", "42"
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
}
namespace testing {
struct streamable_value_t {
std::string message;
int value;
friend std::ostream& operator<<(std::ostream& stream, const streamable_value_t& value) {
stream << "['" << value.message << "', " << value.value << "]";
return stream;
}
};
} // namespace testing
struct ExtractStreamableValueAttributesAction {
struct pack_t {
std::string message;
std::string value;
};
pack_t& actual;
void operator()(const log::record_t& record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<std::string>("value");
}
};
TEST(Macro, UsingStreamOperatorIfNoImplicitConversionAvailable) {
static_assert(traits::supports::stream_push<streamable_value_t>::value,
"`streamable_value_t` must support stream push operator<<");
streamable_value_t value = { "42", 42 };
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")("value", value);
EXPECT_EQ("message", actual.message);
EXPECT_EQ("['42', 42]", actual.value);
}
TEST(Macro, InitializerListAttributes) {
log::record_t record;
record.attributes["attr1"] = {"value1"};
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(attribute::list({
{"value", "42"}
}));
EXPECT_EQ("message", actual.message);
EXPECT_EQ("42", actual.value);
}
<|endoftext|> |
<commit_before>#include "robot_impl.h"
#include <algorithm>
#include <sstream>
#include <Poco/Net/NetException.h>
#include <cstring>
#include <iostream>
// `using std::string_literals::operator""s` produces a GCC warning that cannot
// be disabled, so we have to use `using namespace ...`.
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65923#c0
using namespace std::string_literals; // NOLINT
namespace franka {
constexpr std::chrono::seconds Robot::Impl::kDefaultTimeout;
Robot::Impl::Impl(const std::string& franka_address,
uint16_t franka_port,
std::chrono::milliseconds timeout)
: motion_generator_running_{false} {
Poco::Timespan poco_timeout(1000l * timeout.count());
try {
tcp_socket_.connect({franka_address, franka_port}, poco_timeout);
tcp_socket_.setBlocking(true);
tcp_socket_.setSendTimeout(poco_timeout);
tcp_socket_.setReceiveTimeout(poco_timeout);
udp_socket_.setReceiveTimeout(poco_timeout);
udp_socket_.bind({"0.0.0.0", 0});
research_interface::ConnectRequest connect_request(
udp_socket_.address().port());
tcp_socket_.sendBytes(&connect_request, sizeof(connect_request));
research_interface::ConnectReply connect_reply =
tcpReceiveObject<research_interface::ConnectReply>();
switch (connect_reply.status) {
case research_interface::ConnectReply::Status::
kIncompatibleLibraryVersion: {
std::stringstream message;
message << "libfranka: incompatible library version. " << std::endl
<< "Server version: " << connect_reply.version << std::endl
<< "Library version: " << research_interface::kVersion;
throw IncompatibleVersionException(message.str());
}
case research_interface::ConnectReply::Status::kSuccess:
ri_version_ = connect_reply.version;
break;
default:
throw ProtocolException("libfranka: protocol error");
}
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: FRANKA connection error: "s + e.what());
} catch (Poco::TimeoutException const& e) {
throw NetworkException("libfranka: FRANKA connection timeout");
} catch (Poco::Exception const& e) {
throw NetworkException("libfranka: "s + e.what());
}
}
Robot::Impl::~Impl() noexcept {
try {
tcp_socket_.shutdown();
tcp_socket_.close();
udp_socket_.close();
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: FRANKA socket error: "s + e.what());
} catch (Poco::Exception const& e) {
throw NetworkException("libfranka: "s + e.what());
}
}
void Robot::Impl::setRobotState(
const research_interface::RobotState& robot_state) {
std::copy(robot_state.q_start.cbegin(), robot_state.q_start.cend(),
robot_state_.q_start.begin());
std::copy(robot_state.O_T_EE_start.cbegin(), robot_state.O_T_EE_start.cend(),
robot_state_.O_T_EE_start.begin());
std::copy(robot_state.elbow_start.cbegin(), robot_state.elbow_start.cend(),
robot_state_.elbow_start.begin());
std::copy(robot_state.tau_J.cbegin(), robot_state.tau_J.cend(),
robot_state_.tau_J.begin());
std::copy(robot_state.dtau_J.cbegin(), robot_state.dtau_J.cend(),
robot_state_.dtau_J.begin());
std::copy(robot_state.q.cbegin(), robot_state.q.cend(),
robot_state_.q.begin());
std::copy(robot_state.dq.cbegin(), robot_state.dq.cend(),
robot_state_.dq.begin());
std::copy(robot_state.q_d.cbegin(), robot_state.q_d.cend(),
robot_state_.q_d.begin());
std::copy(robot_state.joint_contact.cbegin(),
robot_state.joint_contact.cend(),
robot_state_.joint_contact.begin());
std::copy(robot_state.cartesian_contact.cbegin(),
robot_state.cartesian_contact.cend(),
robot_state_.cartesian_contact.begin());
std::copy(robot_state.joint_collision.cbegin(),
robot_state.joint_collision.cend(),
robot_state_.joint_collision.begin());
std::copy(robot_state.cartesian_collision.cbegin(),
robot_state.cartesian_collision.cend(),
robot_state_.cartesian_collision.begin());
std::copy(robot_state.tau_ext_hat_filtered.cbegin(),
robot_state.tau_ext_hat_filtered.cend(),
robot_state_.tau_ext_hat_filtered.begin());
std::copy(robot_state.O_F_ext_hat_K.cbegin(),
robot_state.O_F_ext_hat_K.cend(),
robot_state_.O_F_ext_hat_K.begin());
std::copy(robot_state.K_F_ext_hat_K.cbegin(),
robot_state.K_F_ext_hat_K.cend(),
robot_state_.K_F_ext_hat_K.begin());
}
bool Robot::Impl::update() {
try {
if (!handleReplies()) {
return false; // server sent EOF
}
std::array<uint8_t, sizeof(research_interface::RobotState)> buffer;
Poco::Net::SocketAddress server_address;
int bytes_received =
udp_socket_.receiveFrom(buffer.data(), buffer.size(), server_address);
if (bytes_received == buffer.size()) {
research_interface::RobotState robot_state(
*reinterpret_cast<research_interface::RobotState*>(buffer.data()));
setRobotState(robot_state);
if (motion_generator_running_) {
if (robot_command_.motion.motion_generation_finished) {
motion_generator_running_ = false;
}
robot_command_.message_id = robot_state.message_id;
robot_command_.motion.timestamp += kCommandTimeStep;
int bytes_sent = udp_socket_.sendTo(
&robot_command_, sizeof(robot_command_), server_address);
if (bytes_sent != sizeof(robot_command_)) {
throw NetworkException("libfranka: UDP send error");
}
}
return true;
}
throw ProtocolException("libfranka: incorrect object size");
} catch (Poco::TimeoutException const& e) {
throw NetworkException("libfranka: robot state read timeout");
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: robot state read: "s + e.what());
}
}
const RobotState& Robot::Impl::robotState() const noexcept {
return robot_state_;
}
Robot::ServerVersion Robot::Impl::serverVersion() const noexcept {
return ri_version_;
}
research_interface::MotionGeneratorCommand&
Robot::Impl::motionCommand() noexcept {
return robot_command_.motion;
}
bool Robot::Impl::handleReplies() {
using namespace std::placeholders;
if (tcp_socket_.poll(0, Poco::Net::Socket::SELECT_READ)) {
size_t offset = read_buffer_.size();
read_buffer_.resize(offset + tcp_socket_.available());
int rv = tcp_socket_.receiveBytes(&read_buffer_[offset],
tcp_socket_.available());
if (rv == 0) {
return false;
}
if (read_buffer_.size() < sizeof(research_interface::Function)) {
return true;
}
research_interface::Function function =
*reinterpret_cast<research_interface::Function*>(read_buffer_.data());
auto it =
std::find(expected_replies_.begin(), expected_replies_.end(), function);
if (it == std::end(expected_replies_)) {
throw ProtocolException("libfranka: unexpected reply!");
}
switch (function) {
case research_interface::Function::kStartMotionGenerator:
handleReply<research_interface::StartMotionGeneratorReply>(
std::bind(&Robot::Impl::handleStartMotionGeneratorReply, this, _1),
it);
break;
case research_interface::Function::kStopMotionGenerator:
handleReply<research_interface::StopMotionGeneratorReply>(
std::bind(&Robot::Impl::handleStopMotionGeneratorReply, this, _1),
it);
break;
default:
throw ProtocolException("libfranka: unsupported reply!");
}
}
return true;
}
template <typename T>
void Robot::Impl::handleReply(
std::function<void(T)> handle,
std::list<research_interface::Function>::iterator it) {
if (read_buffer_.size() < sizeof(T)) {
return;
}
T reply = *reinterpret_cast<T*>(read_buffer_.data());
size_t remaining_bytes = read_buffer_.size() - sizeof(reply);
std::memmove(read_buffer_.data(), &read_buffer_[sizeof(reply)],
remaining_bytes);
read_buffer_.resize(remaining_bytes);
expected_replies_.erase(it);
handle(reply);
}
template <class T>
T Robot::Impl::tcpReceiveObject() {
int bytes_read = 0;
try {
std::array<uint8_t, sizeof(T)> buffer;
constexpr int kBytesTotal = sizeof(T);
while (bytes_read < kBytesTotal) {
int bytes_left = kBytesTotal - bytes_read;
int rv = tcp_socket_.receiveBytes(&buffer.at(bytes_read), bytes_left);
if (rv == 0) {
throw NetworkException("libfranka: FRANKA connection closed");
}
bytes_read += rv;
}
return T(*reinterpret_cast<const T*>(buffer.data()));
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: FRANKA connection error: "s + e.what());
} catch (Poco::TimeoutException const& e) {
if (bytes_read != 0) {
throw ProtocolException("libfranka: incorrect object size");
} else {
throw NetworkException("libfranka: FRANKA connection timeout");
}
}
}
void Robot::Impl::startMotionGenerator(
research_interface::StartMotionGeneratorRequest::Type
motion_generator_type) {
if (motion_generator_running_) {
throw MotionGeneratorException(
"libfranka: attempted to start multiple motion generators!");
}
motion_generator_running_ = true;
std::memset(&robot_command_, 0, sizeof(robot_command_));
research_interface::StartMotionGeneratorRequest request(
motion_generator_type);
tcp_socket_.sendBytes(&request, sizeof(request));
research_interface::StartMotionGeneratorReply motion_generator_reply =
tcpReceiveObject<research_interface::StartMotionGeneratorReply>();
switch (motion_generator_reply.status) {
case research_interface::StartMotionGeneratorReply::Status::kSuccess:
break;
case research_interface::StartMotionGeneratorReply::Status::kNotConnected:
throw ProtocolException(
"libfranka: attempted to start motion generator, but not connected!");
case research_interface::StartMotionGeneratorReply::Status::kInvalidType:
default:
throw ProtocolException("libfranka: unexpected motion generator reply!");
}
expected_replies_.push_back(
research_interface::Function::kStartMotionGenerator);
}
void Robot::Impl::stopMotionGenerator() {
robot_command_.motion.motion_generation_finished = true;
research_interface::StopMotionGeneratorRequest request;
tcp_socket_.sendBytes(&request, sizeof(request));
expected_replies_.push_back(
research_interface::Function::kStopMotionGenerator);
}
void Robot::Impl::handleStartMotionGeneratorReply(
const research_interface::StartMotionGeneratorReply&
start_motion_generator_request) {
motion_generator_running_ = false;
switch (start_motion_generator_request.status) {
case research_interface::StartMotionGeneratorReply::Status::kFinished:
case research_interface::StartMotionGeneratorReply::Status::kAborted:
break;
case research_interface::StartMotionGeneratorReply::Status::kRejected:
throw MotionGeneratorException(
"libfranka: start motion generator command rejected!");
default:
throw ProtocolException("libfranka: unexpected motion generator reply!");
}
}
void Robot::Impl::handleStopMotionGeneratorReply(
const research_interface::StopMotionGeneratorReply&
stop_motion_generator_reply) {
if (stop_motion_generator_reply.status !=
research_interface::StopMotionGeneratorReply::Status::kSuccess) {
throw ProtocolException("libfranka: unexpected motion generator reply!");
}
}
} // namespace franka
<commit_msg>Robot::Impl: Don't throw exceptions in destructor.<commit_after>#include "robot_impl.h"
#include <algorithm>
#include <sstream>
#include <Poco/Net/NetException.h>
#include <cstring>
#include <iostream>
// `using std::string_literals::operator""s` produces a GCC warning that cannot
// be disabled, so we have to use `using namespace ...`.
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65923#c0
using namespace std::string_literals; // NOLINT
namespace franka {
constexpr std::chrono::seconds Robot::Impl::kDefaultTimeout;
Robot::Impl::Impl(const std::string& franka_address,
uint16_t franka_port,
std::chrono::milliseconds timeout)
: motion_generator_running_{false} {
Poco::Timespan poco_timeout(1000l * timeout.count());
try {
tcp_socket_.connect({franka_address, franka_port}, poco_timeout);
tcp_socket_.setBlocking(true);
tcp_socket_.setSendTimeout(poco_timeout);
tcp_socket_.setReceiveTimeout(poco_timeout);
udp_socket_.setReceiveTimeout(poco_timeout);
udp_socket_.bind({"0.0.0.0", 0});
research_interface::ConnectRequest connect_request(
udp_socket_.address().port());
tcp_socket_.sendBytes(&connect_request, sizeof(connect_request));
research_interface::ConnectReply connect_reply =
tcpReceiveObject<research_interface::ConnectReply>();
switch (connect_reply.status) {
case research_interface::ConnectReply::Status::
kIncompatibleLibraryVersion: {
std::stringstream message;
message << "libfranka: incompatible library version. " << std::endl
<< "Server version: " << connect_reply.version << std::endl
<< "Library version: " << research_interface::kVersion;
throw IncompatibleVersionException(message.str());
}
case research_interface::ConnectReply::Status::kSuccess:
ri_version_ = connect_reply.version;
break;
default:
throw ProtocolException("libfranka: protocol error");
}
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: FRANKA connection error: "s + e.what());
} catch (Poco::TimeoutException const& e) {
throw NetworkException("libfranka: FRANKA connection timeout");
} catch (Poco::Exception const& e) {
throw NetworkException("libfranka: "s + e.what());
}
}
Robot::Impl::~Impl() noexcept {
try {
tcp_socket_.shutdown();
} catch (...) {
}
}
void Robot::Impl::setRobotState(
const research_interface::RobotState& robot_state) {
std::copy(robot_state.q_start.cbegin(), robot_state.q_start.cend(),
robot_state_.q_start.begin());
std::copy(robot_state.O_T_EE_start.cbegin(), robot_state.O_T_EE_start.cend(),
robot_state_.O_T_EE_start.begin());
std::copy(robot_state.elbow_start.cbegin(), robot_state.elbow_start.cend(),
robot_state_.elbow_start.begin());
std::copy(robot_state.tau_J.cbegin(), robot_state.tau_J.cend(),
robot_state_.tau_J.begin());
std::copy(robot_state.dtau_J.cbegin(), robot_state.dtau_J.cend(),
robot_state_.dtau_J.begin());
std::copy(robot_state.q.cbegin(), robot_state.q.cend(),
robot_state_.q.begin());
std::copy(robot_state.dq.cbegin(), robot_state.dq.cend(),
robot_state_.dq.begin());
std::copy(robot_state.q_d.cbegin(), robot_state.q_d.cend(),
robot_state_.q_d.begin());
std::copy(robot_state.joint_contact.cbegin(),
robot_state.joint_contact.cend(),
robot_state_.joint_contact.begin());
std::copy(robot_state.cartesian_contact.cbegin(),
robot_state.cartesian_contact.cend(),
robot_state_.cartesian_contact.begin());
std::copy(robot_state.joint_collision.cbegin(),
robot_state.joint_collision.cend(),
robot_state_.joint_collision.begin());
std::copy(robot_state.cartesian_collision.cbegin(),
robot_state.cartesian_collision.cend(),
robot_state_.cartesian_collision.begin());
std::copy(robot_state.tau_ext_hat_filtered.cbegin(),
robot_state.tau_ext_hat_filtered.cend(),
robot_state_.tau_ext_hat_filtered.begin());
std::copy(robot_state.O_F_ext_hat_K.cbegin(),
robot_state.O_F_ext_hat_K.cend(),
robot_state_.O_F_ext_hat_K.begin());
std::copy(robot_state.K_F_ext_hat_K.cbegin(),
robot_state.K_F_ext_hat_K.cend(),
robot_state_.K_F_ext_hat_K.begin());
}
bool Robot::Impl::update() {
try {
if (!handleReplies()) {
return false; // server sent EOF
}
std::array<uint8_t, sizeof(research_interface::RobotState)> buffer;
Poco::Net::SocketAddress server_address;
int bytes_received =
udp_socket_.receiveFrom(buffer.data(), buffer.size(), server_address);
if (bytes_received == buffer.size()) {
research_interface::RobotState robot_state(
*reinterpret_cast<research_interface::RobotState*>(buffer.data()));
setRobotState(robot_state);
if (motion_generator_running_) {
if (robot_command_.motion.motion_generation_finished) {
motion_generator_running_ = false;
}
robot_command_.message_id = robot_state.message_id;
robot_command_.motion.timestamp += kCommandTimeStep;
int bytes_sent = udp_socket_.sendTo(
&robot_command_, sizeof(robot_command_), server_address);
if (bytes_sent != sizeof(robot_command_)) {
throw NetworkException("libfranka: UDP send error");
}
}
return true;
}
throw ProtocolException("libfranka: incorrect object size");
} catch (Poco::TimeoutException const& e) {
throw NetworkException("libfranka: robot state read timeout");
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: robot state read: "s + e.what());
}
}
const RobotState& Robot::Impl::robotState() const noexcept {
return robot_state_;
}
Robot::ServerVersion Robot::Impl::serverVersion() const noexcept {
return ri_version_;
}
research_interface::MotionGeneratorCommand&
Robot::Impl::motionCommand() noexcept {
return robot_command_.motion;
}
bool Robot::Impl::handleReplies() {
using namespace std::placeholders;
if (tcp_socket_.poll(0, Poco::Net::Socket::SELECT_READ)) {
size_t offset = read_buffer_.size();
read_buffer_.resize(offset + tcp_socket_.available());
int rv = tcp_socket_.receiveBytes(&read_buffer_[offset],
tcp_socket_.available());
if (rv == 0) {
return false;
}
if (read_buffer_.size() < sizeof(research_interface::Function)) {
return true;
}
research_interface::Function function =
*reinterpret_cast<research_interface::Function*>(read_buffer_.data());
auto it =
std::find(expected_replies_.begin(), expected_replies_.end(), function);
if (it == std::end(expected_replies_)) {
throw ProtocolException("libfranka: unexpected reply!");
}
switch (function) {
case research_interface::Function::kStartMotionGenerator:
handleReply<research_interface::StartMotionGeneratorReply>(
std::bind(&Robot::Impl::handleStartMotionGeneratorReply, this, _1),
it);
break;
case research_interface::Function::kStopMotionGenerator:
handleReply<research_interface::StopMotionGeneratorReply>(
std::bind(&Robot::Impl::handleStopMotionGeneratorReply, this, _1),
it);
break;
default:
throw ProtocolException("libfranka: unsupported reply!");
}
}
return true;
}
template <typename T>
void Robot::Impl::handleReply(
std::function<void(T)> handle,
std::list<research_interface::Function>::iterator it) {
if (read_buffer_.size() < sizeof(T)) {
return;
}
T reply = *reinterpret_cast<T*>(read_buffer_.data());
size_t remaining_bytes = read_buffer_.size() - sizeof(reply);
std::memmove(read_buffer_.data(), &read_buffer_[sizeof(reply)],
remaining_bytes);
read_buffer_.resize(remaining_bytes);
expected_replies_.erase(it);
handle(reply);
}
template <class T>
T Robot::Impl::tcpReceiveObject() {
int bytes_read = 0;
try {
std::array<uint8_t, sizeof(T)> buffer;
constexpr int kBytesTotal = sizeof(T);
while (bytes_read < kBytesTotal) {
int bytes_left = kBytesTotal - bytes_read;
int rv = tcp_socket_.receiveBytes(&buffer.at(bytes_read), bytes_left);
if (rv == 0) {
throw NetworkException("libfranka: FRANKA connection closed");
}
bytes_read += rv;
}
return T(*reinterpret_cast<const T*>(buffer.data()));
} catch (Poco::Net::NetException const& e) {
throw NetworkException("libfranka: FRANKA connection error: "s + e.what());
} catch (Poco::TimeoutException const& e) {
if (bytes_read != 0) {
throw ProtocolException("libfranka: incorrect object size");
} else {
throw NetworkException("libfranka: FRANKA connection timeout");
}
}
}
void Robot::Impl::startMotionGenerator(
research_interface::StartMotionGeneratorRequest::Type
motion_generator_type) {
if (motion_generator_running_) {
throw MotionGeneratorException(
"libfranka: attempted to start multiple motion generators!");
}
motion_generator_running_ = true;
std::memset(&robot_command_, 0, sizeof(robot_command_));
research_interface::StartMotionGeneratorRequest request(
motion_generator_type);
tcp_socket_.sendBytes(&request, sizeof(request));
research_interface::StartMotionGeneratorReply motion_generator_reply =
tcpReceiveObject<research_interface::StartMotionGeneratorReply>();
switch (motion_generator_reply.status) {
case research_interface::StartMotionGeneratorReply::Status::kSuccess:
break;
case research_interface::StartMotionGeneratorReply::Status::kNotConnected:
throw ProtocolException(
"libfranka: attempted to start motion generator, but not connected!");
case research_interface::StartMotionGeneratorReply::Status::kInvalidType:
default:
throw ProtocolException("libfranka: unexpected motion generator reply!");
}
expected_replies_.push_back(
research_interface::Function::kStartMotionGenerator);
}
void Robot::Impl::stopMotionGenerator() {
robot_command_.motion.motion_generation_finished = true;
research_interface::StopMotionGeneratorRequest request;
tcp_socket_.sendBytes(&request, sizeof(request));
expected_replies_.push_back(
research_interface::Function::kStopMotionGenerator);
}
void Robot::Impl::handleStartMotionGeneratorReply(
const research_interface::StartMotionGeneratorReply&
start_motion_generator_request) {
motion_generator_running_ = false;
switch (start_motion_generator_request.status) {
case research_interface::StartMotionGeneratorReply::Status::kFinished:
case research_interface::StartMotionGeneratorReply::Status::kAborted:
break;
case research_interface::StartMotionGeneratorReply::Status::kRejected:
throw MotionGeneratorException(
"libfranka: start motion generator command rejected!");
default:
throw ProtocolException("libfranka: unexpected motion generator reply!");
}
}
void Robot::Impl::handleStopMotionGeneratorReply(
const research_interface::StopMotionGeneratorReply&
stop_motion_generator_reply) {
if (stop_motion_generator_reply.status !=
research_interface::StopMotionGeneratorReply::Status::kSuccess) {
throw ProtocolException("libfranka: unexpected motion generator reply!");
}
}
} // namespace franka
<|endoftext|> |
<commit_before>/*
* Copyright (C) LinBox
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
#include <linbox/matrix/random-matrix.h>
#include <linbox/solutions/solve.h>
using namespace LinBox;
namespace {
template <class Matrix>
struct TypeToString;
template <class MatrixArgs>
struct TypeToString<DenseMatrix<MatrixArgs>> {
static constexpr const char* value = "DenseMatrix";
};
template <class... MatrixArgs>
struct TypeToString<SparseMatrix<MatrixArgs...>> {
static constexpr const char* value = "SparseMatrix";
};
template <class Matrix>
inline const char* type_to_string(const Matrix& A)
{
return TypeToString<Matrix>::value;
}
template <class SolveMethod, class ResultVector, class Matrix, class Vector>
void print_error(const ResultVector& x, const Matrix& A, const Vector& b, int m, int n, int bitSize, int seed, bool verbose,
std::string reason)
{
if (verbose) {
A.write(std::cerr << "A: ", Tag::FileFormat::Maple) << std::endl;
std::cerr << "b: " << b << std::endl;
std::cerr << "x: " << x << std::endl;
}
std::cerr << "/!\\ " << SolveMethod::name() << " on " << type_to_string(A) << " over ";
A.field().write(std::cerr);
std::cerr << " of size " << A.rowdim() << "x" << A.coldim() << " FAILS (" << reason << ")" << std::endl;
}
}
template <class SolveMethod, class Matrix, class Domain, class ResultDomain>
bool test_solve(Domain& D, ResultDomain& RD, Communicator* pCommunicator, int m, int n, int bitSize, int seed, bool verbose)
{
using Vector = DenseVector<Domain>;
using ResultVector = DenseVector<ResultDomain>;
Matrix A(D, m, n);
Vector b(D, m);
ResultVector x(RD, n);
// @note RandomDenseMatrix can also fill a SparseMatrix, it has just a sparsity of 0.
typename Domain::RandIter randIter(D, bitSize, seed);
LinBox::RandomDenseMatrix<typename Domain::RandIter, Domain> RDM(D, randIter);
b.random();
// @note Within our test m == n implies invertible,
// but for the rectangular case, we pass whatever.
if (m == n) {
RDM.randomFullRank(A);
}
else {
RDM.random(A);
}
if (verbose) {
std::cout << "--- Testing " << SolveMethod::name() << " on " << type_to_string(A) << " over ";
D.write(std::cout) << " of size " << m << "x" << n << std::endl;
}
SolveMethod method;
method.pCommunicator = pCommunicator;
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
print_error<SolveMethod>(x, A, b, m, n, bitSize, seed, verbose, "throws error");
return false;
}
// @fixme CHECK RESULT IS CORRECT
// if (x[0] != 1 || x[1] != 52) {
// print_error<SolveMethod>(x, A, b, m, n, bitSize, seed, verbose, "Ax != b");
// return false;
// }
return true;
}
//
// Rational solve
//
template <class SolveMethod, class Matrix>
bool test_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
using RationalDomain = Givaro::QField<Givaro::Rational>;
IntegerDomain D;
RationalDomain RD;
// @fixme Add a test for blackboxes
bool ok = true;
ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, n, bitSize, seed, verbose);
ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_all_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
bool ok = true;
ok &= test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
ok &= test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_dense_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
return test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
}
template <class SolveMethod>
bool test_sparse_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
return test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
}
//
// Modular solve
//
template <class SolveMethod, class Matrix>
bool test_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
ModularDomain D(q);
// @fixme Add a test for blackboxes
bool ok = true;
ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, n, bitSize, seed, verbose);
ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_all_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
bool ok = true;
ok &= test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
ok &= test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_dense_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
return test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
}
template <class SolveMethod>
bool test_sparse_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
return test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
}
int main(int argc, char** argv)
{
Integer q = 101;
bool verbose = false;
bool loop = false;
int seed = -1;
int bitSize = 100;
int m = 32;
int n = 24;
static Argument args[] = {{'q', "-q", "Field characteristic.", TYPE_INTEGER, &q},
{'v', "-v", "Enable verbose mode.", TYPE_BOOL, &verbose},
{'l', "-l", "Infinite loop of tests.", TYPE_BOOL, &loop},
{'s', "-s", "Seed for randomness.", TYPE_INT, &seed},
{'b', "-b", "Bit size for rational solve tests.", TYPE_INT, &bitSize},
{'m', "-m", "Row dimension of matrices.", TYPE_INT, &m},
{'n', "-n", "Column dimension of matrices.", TYPE_INT, &n},
END_OF_ARGUMENTS};
if (seed < 0) {
seed = time(nullptr);
}
parseArguments(argc, argv, args);
if (verbose) {
commentator().setReportStream(std::cout);
}
bool ok = true;
Communicator communicator(0, nullptr);
do {
ok &= test_all_rational_solve<Method::Auto>(communicator, m, n, bitSize, seed, verbose);
ok &= test_all_rational_solve<Method::CraAuto>(communicator, m, n, bitSize, seed, verbose);
ok &= test_all_rational_solve<Method::Dixon>(communicator, m, n, bitSize, seed, verbose);
// @note NumericSymbolic methods are only implemented on DenseMatrix
// @fixme Singular case fails
// ok &= test_dense_rational_solve<Method::NumericSymbolicOverlap>(communicator, m, n, bitSize, seed, verbose);
// @fixme Fails
// ok &= test_dense_rational_solve<Method::NumericSymbolicNorm>(communicator, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::DenseElimination>(q, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::SparseElimination>(q, m, n, bitSize, seed, verbose);
// @fixme Dense does not compile
// ok &= test_dense_modular_solve<Method::Wiedemann>(q, m, n, bitSize, seed, verbose);
ok &= test_sparse_modular_solve<Method::Wiedemann>(q, m, n, bitSize, seed, verbose);
// @fixme Dense is segfaulting
// ok &= test_dense_modular_solve<Method::Lanczos>(q, m, n, bitSize, seed, verbose);
// @fixme Singular case fails
// ok &= test_sparse_modular_solve<Method::Lanczos>(q, m, n, bitSize, seed, verbose);
// @fixme Dense does not compile
// ok &= test_dense_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, seed, verbose);
// @fixme Sparse is segfaulting
// ok &= test_sparse_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, seed, verbose);
// @deprecated These do not compile anymore
// ok &= test_all_modular_solve<Method::BlockWiedemann>(q, m, n, bitSize, seed, verbose);
// ok &= test_all_modular_solve<Method::Coppersmith>(q, m, n, bitSize, seed, verbose);
if (!ok) {
std::cerr << "Failed with seed: " << seed << std::endl;
}
seed += 1;
} while (loop);
return 0;
}
<commit_msg>test-solve-full Completed<commit_after>/*
* Copyright (C) LinBox
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
#include <linbox/matrix/random-matrix.h>
#include <linbox/solutions/solve.h>
using namespace LinBox;
namespace {
template <class Matrix>
struct TypeToString;
template <class MatrixArgs>
struct TypeToString<DenseMatrix<MatrixArgs>> {
static constexpr const char* value = "DenseMatrix";
};
template <class... MatrixArgs>
struct TypeToString<SparseMatrix<MatrixArgs...>> {
static constexpr const char* value = "SparseMatrix";
};
template <class Matrix>
inline const char* type_to_string(const Matrix& A)
{
return TypeToString<Matrix>::value;
}
template <class SolveMethod, class ResultVector, class Matrix, class Vector>
void print_error(const ResultVector& x, const Matrix& A, const Vector& b, bool verbose, std::string reason)
{
if (verbose) {
A.write(std::cerr << "A: ", Tag::FileFormat::Maple) << std::endl;
std::cerr << "b: " << b << std::endl;
std::cerr << "x: " << x << std::endl;
}
std::cerr << "/!\\ " << SolveMethod::name() << " on " << type_to_string(A) << " over ";
A.field().write(std::cerr);
std::cerr << " of size " << A.rowdim() << "x" << A.coldim() << " FAILS (" << reason << ")" << std::endl;
}
}
template <class SolveMethod, class Matrix, class Domain, class ResultDomain>
bool test_solve(Domain& D, ResultDomain& RD, Communicator* pCommunicator, int m, int n, int bitSize, int seed, bool verbose)
{
using Vector = DenseVector<Domain>;
using ResultVector = DenseVector<ResultDomain>;
//
// Generating data
//
Matrix A(D, m, n);
Vector b(D, m);
ResultVector x(RD, n);
// @note RandomDenseMatrix can also fill a SparseMatrix, it has just a sparsity of 0.
typename Domain::RandIter randIter(D, bitSize, seed);
LinBox::RandomDenseMatrix<typename Domain::RandIter, Domain> RDM(D, randIter);
b.random();
// @note Within our test m == n implies invertible,
// but for the rectangular case, we pass whatever.
if (m == n) {
RDM.randomFullRank(A);
}
else {
RDM.random(A);
}
if (verbose) {
std::cout << "--- Testing " << SolveMethod::name() << " on " << type_to_string(A) << " over ";
D.write(std::cout) << " of size " << m << "x" << n << std::endl;
}
//
// Copying data for final check
//
using ResultMatrix = typename Matrix::template rebind<ResultDomain>::other;
ResultMatrix RA(A, RD);
ResultVector Rb(RD, b);
//
// Solving
//
SolveMethod method;
method.pCommunicator = pCommunicator;
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
print_error<SolveMethod>(x, A, b, verbose, "throws error");
return false;
}
//
// Checking result is correct
//
ResultVector RAx(RD, RA.coldim());
RA.apply(RAx, x);
VectorDomain<ResultDomain> VD(RD);
if (!VD.areEqual(RAx, Rb)) {
print_error<SolveMethod>(x, A, b, verbose, "Ax != b");
return false;
}
return true;
}
//
// Rational solve
//
template <class SolveMethod, class Matrix>
bool test_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
using RationalDomain = Givaro::QField<Givaro::Rational>;
IntegerDomain D;
RationalDomain RD;
bool ok = true;
ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, m, bitSize, seed, verbose);
ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_all_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
bool ok = true;
ok &= test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
ok &= test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_dense_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
return test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
}
template <class SolveMethod>
bool test_sparse_rational_solve(Communicator& communicator, int m, int n, int bitSize, int seed, bool verbose)
{
using IntegerDomain = Givaro::ZRing<Integer>;
return test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, seed, verbose);
}
//
// Modular solve
//
template <class SolveMethod, class Matrix>
bool test_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
ModularDomain D(q);
bool ok = true;
ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, m, bitSize, seed, verbose);
ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_all_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
bool ok = true;
ok &= test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
ok &= test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
return ok;
}
template <class SolveMethod>
bool test_dense_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
return test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
}
template <class SolveMethod>
bool test_sparse_modular_solve(Integer& q, int m, int n, int bitSize, int seed, bool verbose)
{
using ModularDomain = Givaro::Modular<double>;
return test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, seed, verbose);
}
int main(int argc, char** argv)
{
Integer q = 101;
bool verbose = false;
bool loop = false;
int seed = -1;
int bitSize = 100;
int m = 32;
int n = 24;
static Argument args[] = {{'q', "-q", "Field characteristic.", TYPE_INTEGER, &q},
{'v', "-v", "Enable verbose mode.", TYPE_BOOL, &verbose},
{'l', "-l", "Infinite loop of tests.", TYPE_BOOL, &loop},
{'s', "-s", "Seed for randomness.", TYPE_INT, &seed},
{'b', "-b", "Bit size for rational solve tests.", TYPE_INT, &bitSize},
{'m', "-m", "Row dimension of matrices.", TYPE_INT, &m},
{'n', "-n", "Column dimension of matrices.", TYPE_INT, &n},
END_OF_ARGUMENTS};
if (seed < 0) {
seed = time(nullptr);
}
parseArguments(argc, argv, args);
if (verbose) {
commentator().setReportStream(std::cout);
}
bool ok = true;
Communicator communicator(0, nullptr);
do {
ok &= test_all_rational_solve<Method::Auto>(communicator, m, n, bitSize, seed, verbose);
ok &= test_all_rational_solve<Method::CraAuto>(communicator, m, n, bitSize, seed, verbose);
ok &= test_all_rational_solve<Method::Dixon>(communicator, m, n, bitSize, seed, verbose);
// @note NumericSymbolic methods are only implemented on DenseMatrix
// @fixme Singular case fails
// ok &= test_dense_rational_solve<Method::NumericSymbolicOverlap>(communicator, m, n, bitSize, seed, verbose);
// @fixme Fails
// ok &= test_sparse_rational_solve<Method::NumericSymbolicNorm>(communicator, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::DenseElimination>(q, m, n, bitSize, seed, verbose);
ok &= test_all_modular_solve<Method::SparseElimination>(q, m, n, bitSize, seed, verbose);
// @fixme Dense does not compile
// ok &= test_dense_modular_solve<Method::Wiedemann>(q, m, n, bitSize, seed, verbose);
ok &= test_sparse_modular_solve<Method::Wiedemann>(q, m, n, bitSize, seed, verbose);
// @fixme Dense is segfaulting
// ok &= test_dense_modular_solve<Method::Lanczos>(q, m, n, bitSize, seed, verbose);
// @fixme Singular case fails
// ok &= test_sparse_modular_solve<Method::Lanczos>(q, m, n, bitSize, seed, verbose);
// @fixme Dense does not compile
// ok &= test_dense_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, seed, verbose);
// @fixme Sparse is segfaulting
// ok &= test_sparse_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, seed, verbose);
// @deprecated These do not compile anymore
// ok &= test_all_modular_solve<Method::BlockWiedemann>(q, m, n, bitSize, seed, verbose);
// ok &= test_all_modular_solve<Method::Coppersmith>(q, m, n, bitSize, seed, verbose);
if (!ok) {
std::cerr << "Failed with seed: " << seed << std::endl;
}
seed += 1;
} while (ok && loop);
return 0;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vvasielv@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/PrettyPrinter.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace cling {
Transaction::Transaction() {
Initialize();
}
Transaction::Transaction(const CompilationOptions& Opts) {
Initialize();
m_Opts = Opts; // intentional copy.
}
void Transaction::Initialize() {
m_NestedTransactions.reset(0);
m_Parent = 0;
m_State = kCollecting;
m_IssuedDiags = kNone;
m_Opts = CompilationOptions();
m_Module = 0;
m_WrapperFD = 0;
m_Next = 0;
}
Transaction::~Transaction() {
if (hasNestedTransactions())
for (size_t i = 0; i < m_NestedTransactions->size(); ++i) {
assert((*m_NestedTransactions)[i]->getState() == kCommitted
&& "All nested transactions must be committed!");
delete (*m_NestedTransactions)[i];
}
}
void Transaction::addNestedTransaction(Transaction* nested) {
// Create lazily the list
if (!m_NestedTransactions)
m_NestedTransactions.reset(new NestedTransactions());
nested->setParent(this);
// Leave a marker in the parent transaction, where the nested transaction
// started.
DelayCallInfo marker(clang::DeclGroupRef(), Transaction::kCCINone);
m_DeclQueue.push_back(marker);
m_NestedTransactions->push_back(nested);
}
void Transaction::removeNestedTransaction(Transaction* nested) {
assert(hasNestedTransactions() && "Does not contain nested transactions");
int nestedPos = -1;
for (size_t i = 0; i < m_NestedTransactions->size(); ++i)
if ((*m_NestedTransactions)[i] == nested) {
nestedPos = i;
break;
}
assert(nestedPos > -1 && "Not found!?");
m_NestedTransactions->erase(m_NestedTransactions->begin() + nestedPos);
// We need to remove the marker too.
int markerPos = -1;
for (size_t i = 0; i < size(); ++i) {
if ((*this)[i].m_DGR.isNull() && (*this)[i].m_Call == kCCINone) {
++markerPos;
if (nestedPos == markerPos) {
erase(i);
break;
}
}
}
if (!m_NestedTransactions->size())
m_NestedTransactions.reset(0);
}
void Transaction::reset() {
assert(empty() && "The transaction must be empty.");
if (Transaction* parent = getParent())
parent->removeNestedTransaction(this);
m_Parent = 0;
m_State = kCollecting;
m_IssuedDiags = kNone;
m_Opts = CompilationOptions();
m_NestedTransactions.reset(0); // FIXME: leaks the nested transactions.
m_Module = 0;
m_WrapperFD = 0;
m_Next = 0;
}
void Transaction::append(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
#ifdef TEMPORARILY_DISABLED
assert(getState() == kCollecting
&& "Cannot append declarations in current state.");
#endif
forceAppend(DCI);
}
void Transaction::forceAppend(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert((getState() == kCollecting || getState() == kCompleted)
&& "Must not be");
#ifdef TEMPORARILY_DISABLED
#ifndef NDEBUG
// Check for duplicates
for (size_t i = 0, e = m_DeclQueue.size(); i < e; ++i) {
DelayCallInfo &oldDCI (m_DeclQueue[i]);
// It is possible to have duplicate calls to HandleVTable with the same
// declaration, because each time Sema believes a vtable is used it emits
// that callback.
// For reference (clang::CodeGen::CodeGenModule::EmitVTable).
if (oldDCI.m_Call != kCCIHandleVTable)
assert(oldDCI != DCI && "Duplicates?!");
}
#endif
#endif
bool checkForWrapper = !m_WrapperFD;
assert(checkForWrapper = true && "Check for wrappers with asserts");
// register the wrapper if any.
if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl()))
if (utils::Analyze::IsWrapper(FD)) {
assert(!m_WrapperFD && "Two wrappers in one transaction?");
m_WrapperFD = FD;
}
}
m_DeclQueue.push_back(DCI);
}
void Transaction::append(clang::DeclGroupRef DGR) {
append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl));
}
void Transaction::append(Decl* D) {
append(DeclGroupRef(D));
}
void Transaction::forceAppend(Decl* D) {
forceAppend(DelayCallInfo(DeclGroupRef(D), kCCIHandleTopLevelDecl));
}
void Transaction::erase(size_t pos) {
assert(!empty() && "Erasing from an empty transaction.");
m_DeclQueue.erase(decls_begin() + pos);
}
void Transaction::dump() const {
if (!size())
return;
ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext();
PrintingPolicy Policy = C.getPrintingPolicy();
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::dumpPretty() const {
if (!size())
return;
ASTContext* C = 0;
if (m_WrapperFD)
C = &(m_WrapperFD->getASTContext());
if (!getFirstDecl().isNull())
C = &(getFirstDecl().getSingleDecl()->getASTContext());
PrintingPolicy Policy(C->getLangOpts());
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy,
unsigned Indent, bool PrintInstantiation) const {
int nestedT = 0;
for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull()) {
assert(hasNestedTransactions() && "DGR is null even if no nesting?");
// print the nested decl
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" Nested Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
(*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent,
PrintInstantiation);
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" End Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
}
for (DeclGroupRef::const_iterator J = I->m_DGR.begin(),
L = I->m_DGR.end(); J != L; ++J)
if (*J)
(*J)->print(Out, Policy, Indent, PrintInstantiation);
else
Out << "<<NULL DECL>>";
}
}
void Transaction::printStructure(size_t nindent) const {
static const char* const stateNames[kNumStates] = {
"Collecting",
"kCompleted",
"RolledBack",
"RolledBackWithErrors",
"Committed"
};
std::string indent(nindent, ' ');
llvm::errs() << indent << "Transaction @" << this << ": \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
(*I)->printStructure(nindent + 3);
}
llvm::errs() << indent << " state: " << stateNames[getState()] << ", "
<< size() << " decl groups, ";
if (hasNestedTransactions())
llvm::errs() << m_NestedTransactions->size();
else
llvm::errs() << "0";
llvm::errs() << " nested transactions\n"
<< indent << " wrapper: " << m_WrapperFD
<< ", parent: " << m_Parent
<< ", next: " << m_Next << "\n";
}
void cling::Transaction::printStructureBrief(size_t nindent /*=0*/) const {
std::string indent(nindent, ' ');
llvm::errs() << indent << "<T @" << this << " empty=" << empty() <<"> \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
llvm::errs() << indent << "`";
(*I)->printStructureBrief(nindent + 3);
}
}
} // end namespace cling
<commit_msg>Improve debug printout.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vvasielv@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/PrettyPrinter.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace cling {
Transaction::Transaction() {
Initialize();
}
Transaction::Transaction(const CompilationOptions& Opts) {
Initialize();
m_Opts = Opts; // intentional copy.
}
void Transaction::Initialize() {
m_NestedTransactions.reset(0);
m_Parent = 0;
m_State = kCollecting;
m_IssuedDiags = kNone;
m_Opts = CompilationOptions();
m_Module = 0;
m_WrapperFD = 0;
m_Next = 0;
}
Transaction::~Transaction() {
if (hasNestedTransactions())
for (size_t i = 0; i < m_NestedTransactions->size(); ++i) {
assert((*m_NestedTransactions)[i]->getState() == kCommitted
&& "All nested transactions must be committed!");
delete (*m_NestedTransactions)[i];
}
}
void Transaction::addNestedTransaction(Transaction* nested) {
// Create lazily the list
if (!m_NestedTransactions)
m_NestedTransactions.reset(new NestedTransactions());
nested->setParent(this);
// Leave a marker in the parent transaction, where the nested transaction
// started.
DelayCallInfo marker(clang::DeclGroupRef(), Transaction::kCCINone);
m_DeclQueue.push_back(marker);
m_NestedTransactions->push_back(nested);
}
void Transaction::removeNestedTransaction(Transaction* nested) {
assert(hasNestedTransactions() && "Does not contain nested transactions");
int nestedPos = -1;
for (size_t i = 0; i < m_NestedTransactions->size(); ++i)
if ((*m_NestedTransactions)[i] == nested) {
nestedPos = i;
break;
}
assert(nestedPos > -1 && "Not found!?");
m_NestedTransactions->erase(m_NestedTransactions->begin() + nestedPos);
// We need to remove the marker too.
int markerPos = -1;
for (size_t i = 0; i < size(); ++i) {
if ((*this)[i].m_DGR.isNull() && (*this)[i].m_Call == kCCINone) {
++markerPos;
if (nestedPos == markerPos) {
erase(i);
break;
}
}
}
if (!m_NestedTransactions->size())
m_NestedTransactions.reset(0);
}
void Transaction::reset() {
assert(empty() && "The transaction must be empty.");
if (Transaction* parent = getParent())
parent->removeNestedTransaction(this);
m_Parent = 0;
m_State = kCollecting;
m_IssuedDiags = kNone;
m_Opts = CompilationOptions();
m_NestedTransactions.reset(0); // FIXME: leaks the nested transactions.
m_Module = 0;
m_WrapperFD = 0;
m_Next = 0;
}
void Transaction::append(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
#ifdef TEMPORARILY_DISABLED
assert(getState() == kCollecting
&& "Cannot append declarations in current state.");
#endif
forceAppend(DCI);
}
void Transaction::forceAppend(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert((getState() == kCollecting || getState() == kCompleted)
&& "Must not be");
#ifdef TEMPORARILY_DISABLED
#ifndef NDEBUG
// Check for duplicates
for (size_t i = 0, e = m_DeclQueue.size(); i < e; ++i) {
DelayCallInfo &oldDCI (m_DeclQueue[i]);
// It is possible to have duplicate calls to HandleVTable with the same
// declaration, because each time Sema believes a vtable is used it emits
// that callback.
// For reference (clang::CodeGen::CodeGenModule::EmitVTable).
if (oldDCI.m_Call != kCCIHandleVTable)
assert(oldDCI != DCI && "Duplicates?!");
}
#endif
#endif
bool checkForWrapper = !m_WrapperFD;
assert(checkForWrapper = true && "Check for wrappers with asserts");
// register the wrapper if any.
if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl()))
if (utils::Analyze::IsWrapper(FD)) {
assert(!m_WrapperFD && "Two wrappers in one transaction?");
m_WrapperFD = FD;
}
}
m_DeclQueue.push_back(DCI);
}
void Transaction::append(clang::DeclGroupRef DGR) {
append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl));
}
void Transaction::append(Decl* D) {
append(DeclGroupRef(D));
}
void Transaction::forceAppend(Decl* D) {
forceAppend(DelayCallInfo(DeclGroupRef(D), kCCIHandleTopLevelDecl));
}
void Transaction::erase(size_t pos) {
assert(!empty() && "Erasing from an empty transaction.");
m_DeclQueue.erase(decls_begin() + pos);
}
void Transaction::dump() const {
if (!size())
return;
ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext();
PrintingPolicy Policy = C.getPrintingPolicy();
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::dumpPretty() const {
if (!size())
return;
ASTContext* C = 0;
if (m_WrapperFD)
C = &(m_WrapperFD->getASTContext());
if (!getFirstDecl().isNull())
C = &(getFirstDecl().getSingleDecl()->getASTContext());
PrintingPolicy Policy(C->getLangOpts());
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy,
unsigned Indent, bool PrintInstantiation) const {
int nestedT = 0;
for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull()) {
assert(hasNestedTransactions() && "DGR is null even if no nesting?");
// print the nested decl
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" Nested Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
(*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent,
PrintInstantiation);
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" End Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
}
for (DeclGroupRef::const_iterator J = I->m_DGR.begin(),
L = I->m_DGR.end(); J != L; ++J)
if (*J)
(*J)->print(Out, Policy, Indent, PrintInstantiation);
else
Out << "<<NULL DECL>>";
}
}
void Transaction::printStructure(size_t nindent) const {
static const char* const stateNames[kNumStates] = {
"Collecting",
"kCompleted",
"RolledBack",
"RolledBackWithErrors",
"Committed"
};
std::string indent(nindent, ' ');
llvm::errs() << indent << "Transaction @" << this << ": \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
(*I)->printStructure(nindent + 3);
}
llvm::errs() << indent << " state: " << stateNames[getState()] << ", "
<< size() << " decl groups, ";
if (hasNestedTransactions())
llvm::errs() << m_NestedTransactions->size();
else
llvm::errs() << "0";
llvm::errs() << " nested transactions\n"
<< indent << " wrapper: " << m_WrapperFD
<< ", parent: " << m_Parent
<< ", next: " << m_Next << "\n";
}
void cling::Transaction::printStructureBrief(size_t nindent /*=0*/) const {
std::string indent(nindent, ' ');
llvm::errs() << indent << "<T @" << this << " isEmpty=" << empty();
llvm::errs() << " isCommitted=" << (getState() == kCommitted);
llvm::errs() <<"> \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
llvm::errs() << indent << "`";
(*I)->printStructureBrief(nindent + 3);
}
}
} // end namespace cling
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
#include "compiler.h"
#include "assembler.h"
#include "class_linker.h"
#include "dex_cache.h"
#include "jni_compiler.h"
extern bool oatCompileMethod(art::Method*, art::InstructionSet);
namespace art {
// TODO need to specify target
const ClassLoader* Compiler::Compile(std::vector<const DexFile*> class_path) {
const ClassLoader* class_loader = PathClassLoader::Alloc(class_path);
Resolve(class_loader);
for (size_t i = 0; i != class_path.size(); ++i) {
const DexFile* dex_file = class_path[i];
CHECK(dex_file != NULL);
CompileDexFile(class_loader, *dex_file);
}
return class_loader;
}
void Compiler::Resolve(const ClassLoader* class_loader) {
const std::vector<const DexFile*>& class_path = class_loader->GetClassPath();
for (size_t i = 0; i != class_path.size(); ++i) {
const DexFile* dex_file = class_path[i];
CHECK(dex_file != NULL);
ResolveDexFile(class_loader, *dex_file);
}
}
void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
// Strings are easy, they always are simply resolved to literals in the same file
DexCache* dex_cache = class_linker->FindDexCache(dex_file);
for (size_t i = 0; i < dex_cache->NumStrings(); i++) {
class_linker->ResolveString(dex_file, i, dex_cache);
}
// Class derived values are more complicated, they require the linker and loader
for (size_t i = 0; i < dex_cache->NumTypes(); i++) {
class_linker->ResolveType(dex_file, i, dex_cache, class_loader);
}
for (size_t i = 0; i < dex_cache->NumMethods(); i++) {
// unknown if direct or virtual, try both
Method* method = class_linker->ResolveMethod(dex_file, i, dex_cache, class_loader, false);
if (method == NULL) {
class_linker->ResolveMethod(dex_file, i, dex_cache, class_loader, true);
}
}
for (size_t i = 0; i < dex_cache->NumFields(); i++) {
// unknown if instance or static, try both
Field* field = class_linker->ResolveField(dex_file, i, dex_cache, class_loader, false);
if (field == NULL) {
class_linker->ResolveMethod(dex_file, i, dex_cache, class_loader, true);
}
}
}
void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
for (size_t i = 0; i < dex_file.NumClassDefs(); i++) {
const DexFile::ClassDef& class_def = dex_file.GetClassDef(i);
const char* descriptor = dex_file.GetClassDescriptor(class_def);
Class* klass = class_linker->FindClass(descriptor, class_loader);
CHECK(klass != NULL);
CompileClass(klass);
}
}
void Compiler::CompileClass(Class* klass) {
for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
CompileMethod(klass->GetDirectMethod(i));
}
for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
CompileMethod(klass->GetVirtualMethod(i));
}
}
void Compiler::CompileMethod(Method* method) {
if (method->IsNative()) {
// TODO note code will be unmapped when JniCompiler goes out of scope
Assembler jni_asm;
JniCompiler jni_compiler;
jni_compiler.Compile(&jni_asm, method);
} else if (method->IsAbstract()) {
// TODO: This might be also noted in the ClassLinker.
// Probably makes more sense to do here?
UNIMPLEMENTED(FATAL) << "compile stub to throw AbstractMethodError";
} else {
oatCompileMethod(method, kThumb2);
}
// CHECK(method->HasCode()); // TODO: enable this check ASAP
}
} // namespace art
<commit_msg>Fix a typo in field resolution.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
#include "compiler.h"
#include "assembler.h"
#include "class_linker.h"
#include "dex_cache.h"
#include "jni_compiler.h"
extern bool oatCompileMethod(art::Method*, art::InstructionSet);
namespace art {
// TODO need to specify target
const ClassLoader* Compiler::Compile(std::vector<const DexFile*> class_path) {
const ClassLoader* class_loader = PathClassLoader::Alloc(class_path);
Resolve(class_loader);
for (size_t i = 0; i != class_path.size(); ++i) {
const DexFile* dex_file = class_path[i];
CHECK(dex_file != NULL);
CompileDexFile(class_loader, *dex_file);
}
return class_loader;
}
void Compiler::Resolve(const ClassLoader* class_loader) {
const std::vector<const DexFile*>& class_path = class_loader->GetClassPath();
for (size_t i = 0; i != class_path.size(); ++i) {
const DexFile* dex_file = class_path[i];
CHECK(dex_file != NULL);
ResolveDexFile(class_loader, *dex_file);
}
}
void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
// Strings are easy, they always are simply resolved to literals in the same file
DexCache* dex_cache = class_linker->FindDexCache(dex_file);
for (size_t i = 0; i < dex_cache->NumStrings(); i++) {
class_linker->ResolveString(dex_file, i, dex_cache);
}
// Class derived values are more complicated, they require the linker and loader
for (size_t i = 0; i < dex_cache->NumTypes(); i++) {
class_linker->ResolveType(dex_file, i, dex_cache, class_loader);
}
for (size_t i = 0; i < dex_cache->NumMethods(); i++) {
// unknown if direct or virtual, try both
Method* method = class_linker->ResolveMethod(dex_file, i, dex_cache, class_loader, false);
if (method == NULL) {
class_linker->ResolveMethod(dex_file, i, dex_cache, class_loader, true);
}
}
for (size_t i = 0; i < dex_cache->NumFields(); i++) {
// unknown if instance or static, try both
Field* field = class_linker->ResolveField(dex_file, i, dex_cache, class_loader, false);
if (field == NULL) {
class_linker->ResolveField(dex_file, i, dex_cache, class_loader, true);
}
}
}
void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
for (size_t i = 0; i < dex_file.NumClassDefs(); i++) {
const DexFile::ClassDef& class_def = dex_file.GetClassDef(i);
const char* descriptor = dex_file.GetClassDescriptor(class_def);
Class* klass = class_linker->FindClass(descriptor, class_loader);
CHECK(klass != NULL);
CompileClass(klass);
}
}
void Compiler::CompileClass(Class* klass) {
for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
CompileMethod(klass->GetDirectMethod(i));
}
for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
CompileMethod(klass->GetVirtualMethod(i));
}
}
void Compiler::CompileMethod(Method* method) {
if (method->IsNative()) {
// TODO note code will be unmapped when JniCompiler goes out of scope
Assembler jni_asm;
JniCompiler jni_compiler;
jni_compiler.Compile(&jni_asm, method);
} else if (method->IsAbstract()) {
// TODO: This might be also noted in the ClassLinker.
// Probably makes more sense to do here?
UNIMPLEMENTED(FATAL) << "compile stub to throw AbstractMethodError";
} else {
oatCompileMethod(method, kThumb2);
}
// CHECK(method->HasCode()); // TODO: enable this check ASAP
}
} // namespace art
<|endoftext|> |
<commit_before>//
// X Window System Implementation of EggAche Graphics Library
// By BOT Man, 2016
//
#include <exception>
#include <thread>
#include <X11/Xlib.h>
#include "EggAche_Impl.h"
namespace EggAche_Impl
{
class WindowImpl_XWindow : public WindowImpl
{
public:
WindowImpl_XWindow (size_t width, size_t height,
const char *cap_string);
~WindowImpl_XWindow () override;
void Draw (const GUIContext *context, size_t x, size_t y) override;
std::pair<size_t, size_t> GetSize () override;
bool IsClosed () const override;
void OnClick (std::function<void (int, int)> fn) override;
void OnPress (std::function<void (char)> fn) override;
void OnResized (std::function<void (int, int)> fn) override;
void OnRefresh (std::function<void ()> fn) override;
static void EventHandler ();
protected:
int _cxCanvas, _cyCanvas;
int _cxClient, _cyClient;
Window _window;
bool _isClosed;
std::function<void (int, int)> onClick;
std::function<void (char)> onPress;
std::function<void (int, int)> onResized;
std::function<void ()> onRefresh;
WindowImpl_XWindow (const WindowImpl_XWindow &) = delete; // Not allow to copy
void operator= (const WindowImpl_XWindow &) = delete; // Not allow to copy
};
class GUIContext_XWindow : public GUIContext
{
public:
GUIContext_XWindow (size_t width, size_t height);
~GUIContext_XWindow () override;
bool SetPen (unsigned int width,
unsigned int r = 0,
unsigned int g = 0,
unsigned int b = 0) override;
bool SetBrush (bool isTransparent,
unsigned int r,
unsigned int g,
unsigned int b) override;
bool SetFont (unsigned int size = 18,
const char *family = "Consolas",
unsigned int r = 0,
unsigned int g = 0,
unsigned int b = 0) override;
bool DrawLine (int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawRect (int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawElps (int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawRdRt (int xBeg, int yBeg,
int xEnd, int yEnd, int wElps, int hElps) override;
bool DrawArc (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawChord (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawPie (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawTxt (int xBeg, int yBeg, const char *szText) override;
bool DrawImg (const char *fileName,
int x, int y,
int width = -1, int height = -1,
int r = -1,
int g = -1,
int b = -1) override;
bool SaveAsBmp (const char *fileName) override;
void Clear () override;
void PaintOnContext (GUIContext *,
size_t x, size_t y) const override;
protected:
size_t _w, _h;
GUIContext_XWindow (const GUIContext_XWindow &) = delete; // Not allow to copy
void operator= (const GUIContext_XWindow &) = delete; // Not allow to copy
};
}
namespace EggAche_Impl
{
// Factory
WindowImpl *GUIFactory_XWindow::NewWindow (size_t width, size_t height,
const char *cap_string)
{
return new WindowImpl_XWindow (width, height, cap_string);
}
GUIContext *GUIFactory_XWindow::NewGUIContext (size_t width, size_t height)
{
return new GUIContext_XWindow (width, height);
}
// Window
class WindowManager
{
private:
static Display *display;
protected:
WindowManager () {}
public:
static size_t refCount;
static Display *Instance ()
{
std::thread eventHandler (WindowImpl_XWindow::EventHandler);
eventHandler.detach ();
if (display == nullptr)
{
/* open connection with the server */
display = XOpenDisplay (NULL);
if (display == NULL)
throw std::runtime_error ("Failed at XOpenDisplay");
}
return display;
}
static void Delete ()
{
/* close connection to server */
XCloseDisplay (display);
}
};
Display *WindowManager::display = nullptr;
size_t WindowManager::refCount = 0;
void WindowImpl_XWindow::EventHandler ()
{
auto display = WindowManager::Instance ();
auto screen = DefaultScreen (display);
XEvent event;
while (!wnd->_isClosed)
{
XNextEvent (display, &event);
switch (event.type)
{
case ButtonPress:
case KeyPress:
case ResizeRequest:
case Expose:
XFillRectangle (display, wnd->_window, DefaultGC (display, screen), 20, 20, 10, 10);
XDrawString (display, wnd->_window, DefaultGC (display, screen), 50, 50,
"Hello, World!", strlen ("Hello, World!"));
break;
case DestroyNotify:
wnd->_isClosed = true;
break;
default:
break;
}
}
}
WindowImpl_XWindow::WindowImpl_XWindow (size_t width, size_t height,
const char *cap_string)
: _cxCanvas (width), _cyCanvas (height), _cxClient (width), _cyClient (height),
_isClosed (false)
{
auto display = WindowManager::Instance ();
auto screen = DefaultScreen (display);
auto initX = 10, initY = 10, initBorder = 1;
this->_window = XCreateSimpleWindow (display, RootWindow (display, screen),
initX, initY, width, height, initBorder,
BlackPixel (display, screen),
WhitePixel (display, screen));
/* select kind of events we are interested in */
XSelectInput (display, this->_window,
ExposureMask | KeyPressMask | ButtonPressMask |
ResizeRedirectMask | SubstructureNotifyMask);
/* map (show) the window */
XMapWindow (display, this->_window);
WindowManager::refCount++;
}
WindowImpl_XWindow::~WindowImpl_XWindow ()
{
auto display = WindowManager::Instance ();
XEvent event;
event.type = DestroyNotify;
event.window = this->_window;
XSendEvent (display, this->_window, false,
SubstructureNotifyMask, &event);
WindowManager::refCount--;
}
// Context
// MsgBox
/*
void MsgBox_Impl (const char * szTxt, const char * szCap)
{
}*/
}
int main (int argc, char *argv[])
{
using namespace EggAche_Impl;
WindowImpl_XWindow wnd (200, 200);
getchar ();
return 0;
}
<commit_msg>Add Outline<commit_after>//
// X Window System Implementation of EggAche Graphics Library
// By BOT Man, 2016
//
#include <exception>
#include <thread>
#include <X11/Xlib.h>
#include "EggAche_Impl.h"
namespace EggAche_Impl
{
class WindowImpl_XWindow : public WindowImpl
{
public:
WindowImpl_XWindow (size_t width, size_t height,
const char *cap_string);
~WindowImpl_XWindow () override;
void Draw (const GUIContext *context, size_t x, size_t y) override;
std::pair<size_t, size_t> GetSize () override;
bool IsClosed () const override;
void OnClick (std::function<void (int, int)> fn) override;
void OnPress (std::function<void (char)> fn) override;
void OnResized (std::function<void (int, int)> fn) override;
void OnRefresh (std::function<void ()> fn) override;
static void EventHandler ();
protected:
int _cxCanvas, _cyCanvas;
int _cxClient, _cyClient;
Window _window;
bool _isClosed;
std::function<void (int, int)> onClick;
std::function<void (char)> onPress;
std::function<void (int, int)> onResized;
std::function<void ()> onRefresh;
WindowImpl_XWindow (const WindowImpl_XWindow &) = delete; // Not allow to copy
void operator= (const WindowImpl_XWindow &) = delete; // Not allow to copy
};
class GUIContext_XWindow : public GUIContext
{
public:
GUIContext_XWindow (size_t width, size_t height);
~GUIContext_XWindow () override;
bool SetPen (unsigned int width,
unsigned int r = 0,
unsigned int g = 0,
unsigned int b = 0) override;
bool SetBrush (bool isTransparent,
unsigned int r,
unsigned int g,
unsigned int b) override;
bool SetFont (unsigned int size = 18,
const char *family = "Consolas",
unsigned int r = 0,
unsigned int g = 0,
unsigned int b = 0) override;
bool DrawLine (int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawRect (int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawElps (int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawRdRt (int xBeg, int yBeg,
int xEnd, int yEnd, int wElps, int hElps) override;
bool DrawArc (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawChord (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawPie (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd) override;
bool DrawTxt (int xBeg, int yBeg, const char *szText) override;
bool DrawImg (const char *fileName,
int x, int y,
int width = -1, int height = -1,
int r = -1,
int g = -1,
int b = -1) override;
bool SaveAsBmp (const char *fileName) override;
void Clear () override;
void PaintOnContext (GUIContext *,
size_t x, size_t y) const override;
protected:
size_t _w, _h;
GUIContext_XWindow (const GUIContext_XWindow &) = delete; // Not allow to copy
void operator= (const GUIContext_XWindow &) = delete; // Not allow to copy
};
}
namespace EggAche_Impl
{
// Factory
WindowImpl *GUIFactory_XWindow::NewWindow (size_t width, size_t height,
const char *cap_string)
{
return new WindowImpl_XWindow (width, height, cap_string);
}
GUIContext *GUIFactory_XWindow::NewGUIContext (size_t width, size_t height)
{
return new GUIContext_XWindow (width, height);
}
// Window
class WindowManager
{
private:
static Display *display;
protected:
WindowManager () {}
public:
static size_t refCount;
static Display *Instance ()
{
if (display == nullptr)
{
std::thread eventHandler (WindowImpl_XWindow::EventHandler);
eventHandler.detach ();
/* open connection with the server */
display = XOpenDisplay (NULL);
if (display == NULL)
throw std::runtime_error ("Failed at XOpenDisplay");
}
return display;
}
static void Delete ()
{
/* close connection to server */
XCloseDisplay (display);
}
};
Display *WindowManager::display = nullptr;
size_t WindowManager::refCount = 0;
void WindowImpl_XWindow::EventHandler ()
{
auto display = WindowManager::Instance ();
auto screen = DefaultScreen (display);
XEvent event;
while (WindowManager::refCount)
{
XNextEvent (display, &event);
switch (event.type)
{
case ButtonPress:
case KeyPress:
case ResizeRequest:
case Expose:
XFillRectangle (display, event.xexpose.window, DefaultGC (display, screen), 20, 20, 10, 10);
XDrawString (display, event.xexpose.window, DefaultGC (display, screen), 50, 50, "Hello, World!", 14);
break;
case DestroyNotify:
break;
default:
break;
}
}
WindowManager::Delete ();
}
WindowImpl_XWindow::WindowImpl_XWindow (size_t width, size_t height,
const char *cap_string)
: _cxCanvas (width), _cyCanvas (height), _cxClient (width), _cyClient (height),
_isClosed (false)
{
auto display = WindowManager::Instance ();
auto screen = DefaultScreen (display);
auto initX = 10, initY = 10, initBorder = 1;
this->_window = XCreateSimpleWindow (display, RootWindow (display, screen),
initX, initY, width, height, initBorder,
BlackPixel (display, screen),
WhitePixel (display, screen));
/* select kind of events we are interested in */
XSelectInput (display, this->_window,
ExposureMask | KeyPressMask | ButtonPressMask |
ResizeRedirectMask | SubstructureNotifyMask);
/* map (show) the window */
XMapWindow (display, this->_window);
WindowManager::refCount++;
}
WindowImpl_XWindow::~WindowImpl_XWindow ()
{
auto display = WindowManager::Instance ();
XEvent event;
event.type = DestroyNotify;
event.xdestroywindow.window = this->_window;
XSendEvent (display, this->_window, false,
SubstructureNotifyMask, &event);
WindowManager::refCount--;
}
void WindowImpl_XWindow::Draw (const GUIContext *context,
size_t x, size_t y)
{
// Todo
}
std::pair<size_t, size_t> WindowImpl_XWindow::GetSize ()
{
return std::make_pair (this->_cxClient, this->_cyClient);
}
bool WindowImpl_XWindow::IsClosed () const
{
// Todo
return false;
}
void WindowImpl_XWindow::OnClick (std::function<void (int, int)> fn)
{
onClick = std::move (fn);
}
void WindowImpl_XWindow::OnPress (std::function<void (char)> fn)
{
onPress = std::move (fn);
}
void WindowImpl_XWindow::OnResized (std::function<void (int, int)> fn)
{
onResized = std::move (fn);
}
void WindowImpl_XWindow::OnRefresh (std::function<void ()> fn)
{
onRefresh = std::move (fn);
}
// Context
GUIContext_XWindow::GUIContext_XWindow (size_t width, size_t height)
: _w (width), _h (height)
{
// Todo
}
GUIContext_XWindow::~GUIContext_XWindow ()
{
// Todo
}
bool GUIContext_XWindow::SetPen (unsigned int width,
unsigned int r,
unsigned int g,
unsigned int b)
{
// Todo
return false;
}
bool GUIContext_XWindow::SetBrush (bool isTransparent,
unsigned int r,
unsigned int g,
unsigned int b)
{
// Todo
return false;
}
bool GUIContext_XWindow::SetFont (unsigned int size,
const char *family,
unsigned int r,
unsigned int g,
unsigned int b)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawLine (int xBeg, int yBeg, int xEnd, int yEnd)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawRect (int xBeg, int yBeg, int xEnd, int yEnd)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawElps (int xBeg, int yBeg, int xEnd, int yEnd)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawRdRt (int xBeg, int yBeg, int xEnd, int yEnd,
int wElps, int hElps)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawArc (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawChord (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawPie (int xLeft, int yTop, int xRight, int yBottom,
int xBeg, int yBeg, int xEnd, int yEnd)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawTxt (int xBeg, int yBeg, const char * szText)
{
// Todo
return false;
}
bool GUIContext_XWindow::DrawImg (const char *fileName, int x, int y,
int width, int height, int r, int g, int b)
{
// Todo
return false;
}
bool GUIContext_XWindow::SaveAsBmp (const char *fileName)
{
// Todo
return false;
}
void GUIContext_XWindow::Clear ()
{
// Todo
}
void GUIContext_XWindow::PaintOnContext (GUIContext *parentContext,
size_t x, size_t y) const
{
// Todo
}
// MsgBox
void MsgBox_Impl (const char * szTxt, const char * szCap)
{
// Todo
}
}
// Test Funcion
// g++ XWindow_Impl.cpp -o test -std=c++11 -lX11
int main (int argc, char *argv[])
{
using namespace EggAche_Impl;
WindowImpl_XWindow wnd (200, 200, "Hello EggAche");
getchar ();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef LIBTEN_HTTP_CLIENT_HH
#define LIBTEN_HTTP_CLIENT_HH
#include "ten/http/http_message.hh"
#include "ten/shared_pool.hh"
#include "ten/buffer.hh"
#include "ten/net.hh"
#include "ten/uri.hh"
namespace ten {
//! thrown on http network errors
class http_error : public errorx {
public:
http_error(const std::string &msg) : errorx(msg) {}
};
//! basic http client
class http_client {
private:
std::shared_ptr<netsock> _s;
buffer _buf;
std::string _host;
uint16_t _port;
void ensure_connection() {
if (_s && _s->valid()) return;
_s.reset(new netsock(AF_INET, SOCK_STREAM));
if (_s->dial(_host.c_str(), _port) != 0) {
throw http_error("dial");
}
}
public:
size_t max_content_length;
http_client(const std::string &host_, uint16_t port_=80)
: _buf(4*1024), _host(host_), _port(port_), max_content_length(~(size_t)0)
{
parse_host_port(_host, _port);
}
std::string host() const { return _host; }
uint16_t port() const { return _port; }
http_response perform(const std::string &method, const std::string &path, const std::string &data="") {
uri u;
u.scheme = "http";
u.host = _host;
u.port = _port;
u.path = path;
u.normalize();
http_request r(method, u.compose_path());
// HTTP/1.1 requires host header
r.set("Host", u.host);
r.body = data;
return perform(r);
}
http_response perform(http_request &r) {
if (r.body.size()) {
r.set("Content-Length", r.body.size());
}
try {
ensure_connection();
std::string hdata = r.data();
ssize_t nw = _s->send(hdata.c_str(), hdata.size());
if (r.body.size()) {
nw = _s->send(r.body.c_str(), r.body.size());
}
http_parser parser;
http_response resp;
resp.parser_init(&parser);
_buf.clear();
while (!resp.complete) {
_buf.reserve(4*1024);
ssize_t nr = _s->recv(_buf.back(), _buf.available());
if (nr <= 0) { throw http_error("recv"); }
_buf.commit(nr);
size_t len = _buf.size();
resp.parse(&parser, _buf.front(), len);
_buf.remove(len);
if (resp.body.size() >= max_content_length) {
_s.reset(); // close this socket, we won't read anymore
return resp;
}
}
// should not be any data left over in _buf
CHECK(_buf.size() == 0);
if ((resp.http_version == "HTTP/1.0" && resp.get("Connection") != "Keep-Alive") ||
resp.get("Connection") == "close")
{
_s.reset();
}
return resp;
} catch (errorx &e) {
_s.reset();
throw;
}
}
http_response get(const std::string &path) {
return perform("GET", path);
}
http_response post(const std::string &path, const std::string &data) {
return perform("POST", path, data);
}
};
class http_pool : public shared_pool<http_client> {
public:
http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn)
: shared_pool<http_client>("http://" + host_,
std::bind(&http_pool::new_resource, this),
max_conn
),
_host(host_), _port(port_) {}
protected:
std::string _host;
uint16_t _port;
std::shared_ptr<http_client> new_resource() {
VLOG(3) << "new http_client resource " << _host << ":" << _port;
return std::make_shared<http_client>(_host, _port);
}
};
} // end namespace ten
#endif // LIBTEN_HTTP_CLIENT_HH
<commit_msg>fix client for HEAD requests<commit_after>#ifndef LIBTEN_HTTP_CLIENT_HH
#define LIBTEN_HTTP_CLIENT_HH
#include "ten/http/http_message.hh"
#include "ten/shared_pool.hh"
#include "ten/buffer.hh"
#include "ten/net.hh"
#include "ten/uri.hh"
namespace ten {
//! thrown on http network errors
class http_error : public errorx {
public:
http_error(const std::string &msg) : errorx(msg) {}
};
//! basic http client
class http_client {
private:
std::shared_ptr<netsock> _s;
buffer _buf;
std::string _host;
uint16_t _port;
void ensure_connection() {
if (_s && _s->valid()) return;
_s.reset(new netsock(AF_INET, SOCK_STREAM));
if (_s->dial(_host.c_str(), _port) != 0) {
throw http_error("dial");
}
}
public:
size_t max_content_length;
http_client(const std::string &host_, uint16_t port_=80)
: _buf(4*1024), _host(host_), _port(port_), max_content_length(~(size_t)0)
{
parse_host_port(_host, _port);
}
std::string host() const { return _host; }
uint16_t port() const { return _port; }
http_response perform(const std::string &method, const std::string &path, const std::string &data="") {
uri u;
u.scheme = "http";
u.host = _host;
u.port = _port;
u.path = path;
u.normalize();
http_request r(method, u.compose_path());
// HTTP/1.1 requires host header
r.set("Host", u.host);
r.body = data;
return perform(r);
}
http_response perform(http_request &r) {
if (r.body.size()) {
r.set("Content-Length", r.body.size());
}
try {
ensure_connection();
std::string hdata = r.data();
ssize_t nw = _s->send(hdata.c_str(), hdata.size());
if (r.body.size()) {
nw = _s->send(r.body.c_str(), r.body.size());
}
http_parser parser;
http_response resp(&r);
resp.parser_init(&parser);
_buf.clear();
while (!resp.complete) {
_buf.reserve(4*1024);
ssize_t nr = _s->recv(_buf.back(), _buf.available());
if (nr <= 0) { throw http_error("recv"); }
_buf.commit(nr);
size_t len = _buf.size();
resp.parse(&parser, _buf.front(), len);
_buf.remove(len);
if (resp.body.size() >= max_content_length) {
_s.reset(); // close this socket, we won't read anymore
return resp;
}
}
// should not be any data left over in _buf
CHECK(_buf.size() == 0);
if ((resp.http_version == "HTTP/1.0" && resp.get("Connection") != "Keep-Alive") ||
resp.get("Connection") == "close")
{
_s.reset();
}
return resp;
} catch (errorx &e) {
_s.reset();
throw;
}
}
http_response get(const std::string &path) {
return perform("GET", path);
}
http_response post(const std::string &path, const std::string &data) {
return perform("POST", path, data);
}
};
class http_pool : public shared_pool<http_client> {
public:
http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn)
: shared_pool<http_client>("http://" + host_,
std::bind(&http_pool::new_resource, this),
max_conn
),
_host(host_), _port(port_) {}
protected:
std::string _host;
uint16_t _port;
std::shared_ptr<http_client> new_resource() {
VLOG(3) << "new http_client resource " << _host << ":" << _port;
return std::make_shared<http_client>(_host, _port);
}
};
} // end namespace ten
#endif // LIBTEN_HTTP_CLIENT_HH
<|endoftext|> |
<commit_before>/**
* Copyright 2013 Truphone
*/
#include "ListCommand.h"
#include <QString>
#include <QList>
#include <QObject>
#include <bb/cascades/ListView>
#include <bb/cascades/DataModel>
#include "Connection.h"
#include "Utils.h"
using bb::cascades::ListView;
using bb::cascades::DataModel;
namespace truphone
{
namespace test
{
namespace cascades
{
const QString ListCommand::CMD_NAME = "list";
ListCommand::ListCommand(Connection * const socket,
QObject* parent)
: Command(parent),
client(socket),
scenePane(bb::cascades::Application::instance()->scene())
{
}
ListCommand::~ListCommand()
{
}
bool ListCommand::executeCommand(QStringList * const arguments)
{
bool ret = false;
if (arguments->size() > 1)
{
const QString listViewName = arguments->first();
arguments->removeFirst();
ListView * const listView = scenePane->findChild<ListView*>(listViewName);
if (listView)
{
const QString command = arguments->first();
arguments->removeFirst();
//
// check the count/size of the list
//
if (command == "count" && !arguments->isEmpty())
{
bool ok = false;
const int expected = arguments->first().toInt(&ok);
if (ok)
{
arguments->removeFirst();
const int actual =
listView->dataModel()->childCount(listView->rootIndexPath());
ret = (actual == expected);
if (!ret)
{
this->client->write("ERROR: List size is {");
this->client->write(QString::number(actual).toUtf8().constData());
this->client->write("} was expecting {");
this->client->write(QString::number(expected).toUtf8().constData());
this->client->write("}\r\n");
}
}
else
{
this->client->write("ERROR: Expected list size wasn't an integer\r\n");
}
}
//
// check an element by index
//
else if (command == "index")
{
const QVariant element = findElementByIndex(listView, arguments->first());
qDebug() << "got" << element.toString();
if (!element.isNull() && element.isValid())
{
const QString elementType = QString(element.typeName());
if (elementType == "QString")
{
qDebug() << "Result" << element.toString();
}
else if (elementType == "QVariantMap")
{
QVariantMap elementMap(element.toMap());
Q_FOREACH(QString key, elementMap.keys())
{
qDebug() << "Key" << key << "=" << elementMap.value(key).toString();
}
}
else
{
this->client->write("ERROR: Unsupported list element type\r\n");
}
}
else
{
this->client->write("ERROR: Couldn't find the index in the list\r\n");
}
}
//
// check an element by named index
//
else if (command == "name")
{
const QString tmp = arguments->join(" ").trimmed();
const QString namedIndex = tmp.left(tmp.lastIndexOf("."));
const QVariant element = findElementByName(listView, namedIndex);
if (!element.isNull() && element.isValid())
{
const QString elementType = QString(element.typeName());
if (elementType == "QString")
{
qDebug() << "Result" << element.toString();
}
else if (elementType == "QVariantMap")
{
QVariantMap elementMap(element.toMap());
Q_FOREACH(QString key, elementMap.keys())
{
qDebug() << "Key" << key << "=" << elementMap.value(key).toString();
}
}
else
{
this->client->write("ERROR: Unsupported list element type\r\n");
}
}
else
{
this->client->write("ERROR: Couldn't find the index in the list\r\n");
}
}
else
{
this->client->write("ERROR: Unknown list command\r\n");
}
}
else
{
this->client->write("ERROR: Couldn't find the listview\r\n");
}
}
else
{
this->client->write("ERROR: Not enough arguments, sleep <timeInMs>\r\n");
}
return ret;
}
QVariant ListCommand::findElementByIndex(
ListView * const list,
const QString& index)
{
QVariant result;
Buffer delim(".");
Buffer indexString (index.toUtf8().constData());
DataModel * const model = list->dataModel();
QStringList indexes = Utils::tokenise(&delim, &indexString, false);
bool failed = false;
QVariantList indexList;
Q_FOREACH(QString sIndex, indexes)
{
bool ok = false;
qDebug() << "findElementByIndex" << sIndex;
const int iIndex = sIndex.toInt(&ok);
if (ok)
{
qDebug() << "findElementByIndex converted to" << iIndex;
indexList.push_back(iIndex);
}
else
{
failed = true;
break;
}
}
if (!failed)
{
qDebug() << "findElementByIndex index is" << indexList;
result = model->data(indexList);
}
return result;
}
QVariant ListCommand::findElementByName(
bb::cascades::ListView * const list,
const QString& index)
{
QVariant result;
Buffer delim(".");
Buffer indexString (index.toUtf8().constData());
DataModel * const model = list->dataModel();
QStringList indexes = Utils::tokenise(&delim, &indexString, false);
bool failed = false;
QVariantList indexList;
while(!indexes.isEmpty())
{
const QString elementName = indexes.first();
bool found = false;
for (int i = 0 ; i < model->childCount(indexList) ; i++)
{
QVariantList tmp(indexList);
tmp.push_back(i);
const QVariant v = model->data(tmp);
const QString value = v.toString();
const QString type = v.typeName();
if (value == elementName)
{
qDebug() << "findElementByName " << value << "<" << type << ")" << "=" << elementName;
qDebug() << "findElementByName converted to" << i;
indexList.push_back(i);
found = true;
break;
}
}
if (!found)
{
failed = true;
break;
}
indexes.removeFirst();
}
if (!failed)
{
qDebug() << "findElementByName index is" << indexList;
result = model->data(indexList);
}
return result;
}
void ListCommand::showHelp()
{
this->client->write("> list <list> count <expectedSize>\r\n");
}
} // namespace cascades
} // namespace test
} // namespace truphone
<commit_msg>Navigation by index or name working.<commit_after>/**
* Copyright 2013 Truphone
*/
#include "ListCommand.h"
#include <QString>
#include <QList>
#include <QObject>
#include <bb/cascades/ListView>
#include <bb/cascades/DataModel>
#include "Connection.h"
#include "Utils.h"
using bb::cascades::ListView;
using bb::cascades::DataModel;
namespace truphone
{
namespace test
{
namespace cascades
{
const QString ListCommand::CMD_NAME = "list";
ListCommand::ListCommand(Connection * const socket,
QObject* parent)
: Command(parent),
client(socket),
scenePane(bb::cascades::Application::instance()->scene())
{
}
ListCommand::~ListCommand()
{
}
bool ListCommand::executeCommand(QStringList * const arguments)
{
bool ret = false;
if (arguments->size() > 1)
{
const QString listViewName = arguments->first();
arguments->removeFirst();
ListView * const listView = scenePane->findChild<ListView*>(listViewName);
if (listView)
{
const QString command = arguments->first();
arguments->removeFirst();
//
// check the count/size of the list
//
if (command == "count" && !arguments->isEmpty())
{
bool ok = false;
const int expected = arguments->first().toInt(&ok);
if (ok)
{
arguments->removeFirst();
const int actual =
listView->dataModel()->childCount(listView->rootIndexPath());
ret = (actual == expected);
if (!ret)
{
this->client->write("ERROR: List size is {");
this->client->write(QString::number(actual).toUtf8().constData());
this->client->write("} was expecting {");
this->client->write(QString::number(expected).toUtf8().constData());
this->client->write("}\r\n");
}
}
else
{
this->client->write("ERROR: Expected list size wasn't an integer\r\n");
}
}
//
// check an element by index
//
else if (command == "index")
{
const QVariant element = findElementByIndex(listView, arguments->first());
qDebug() << "got" << element.toString();
if (!element.isNull() && element.isValid())
{
const QString elementType = QString(element.typeName());
if (elementType == "QString")
{
qDebug() << "Result" << element.toString();
}
else if (elementType == "QVariantMap")
{
QVariantMap elementMap(element.toMap());
Q_FOREACH(QString key, elementMap.keys())
{
qDebug() << "Key" << key << "=" << elementMap.value(key).toString();
}
}
else
{
this->client->write("ERROR: Unsupported list element type\r\n");
}
}
else
{
this->client->write("ERROR: Couldn't find the index in the list\r\n");
}
}
//
// check an element by named index
//
else if (command == "name")
{
const QString tmp = arguments->join(" ").trimmed();
const QString namedIndex = tmp.left(tmp.lastIndexOf("."));
const QVariant element = findElementByName(listView, namedIndex);
if (!element.isNull() && element.isValid())
{
const QString elementType = QString(element.typeName());
if (elementType == "QString")
{
qDebug() << "Result" << element.toString();
}
else if (elementType == "QVariantMap")
{
QVariantMap elementMap(element.toMap());
Q_FOREACH(QString key, elementMap.keys())
{
qDebug() << "Key" << key << "=" << elementMap.value(key).toString();
}
}
else
{
this->client->write("ERROR: Unsupported list element type\r\n");
}
}
else
{
this->client->write("ERROR: Couldn't find the index in the list\r\n");
}
}
else
{
this->client->write("ERROR: Unknown list command\r\n");
}
}
else
{
this->client->write("ERROR: Couldn't find the listview\r\n");
}
}
else
{
this->client->write("ERROR: Not enough arguments, sleep <timeInMs>\r\n");
}
return ret;
}
QVariant ListCommand::findElementByIndex(
ListView * const list,
const QString& index)
{
QVariant result;
Buffer delim(".");
Buffer indexString (index.toUtf8().constData());
DataModel * const model = list->dataModel();
QStringList indexes = Utils::tokenise(&delim, &indexString, false);
bool failed = false;
QVariantList indexList;
Q_FOREACH(QString sIndex, indexes)
{
bool ok = false;
qDebug() << "findElementByIndex" << sIndex;
const int iIndex = sIndex.toInt(&ok);
if (ok)
{
qDebug() << "findElementByIndex converted to" << iIndex;
indexList.push_back(iIndex);
}
else
{
failed = true;
break;
}
}
if (!failed)
{
qDebug() << "findElementByIndex index is" << indexList;
result = model->data(indexList);
}
return result;
}
QVariant ListCommand::findElementByName(
bb::cascades::ListView * const list,
const QString& index)
{
QVariant result;
Buffer delim(".");
Buffer indexString (index.toUtf8().constData());
DataModel * const model = list->dataModel();
QStringList indexes = Utils::tokenise(&delim, &indexString, false);
bool failed = false;
QVariantList indexList;
while(!indexes.isEmpty())
{
const QString elementName = indexes.first();
bool found = false;
for (int i = 0 ; i < model->childCount(indexList) ; i++)
{
QVariantList tmp(indexList);
tmp.push_back(i);
const QVariant v = model->data(tmp);
const QString type = v.typeName();
// just compare the value
if (type == "QString")
{
const QString value = v.toString();
if (value == elementName)
{
qDebug() << "findElementByName " << value << "<" << type << ")" << "=" << elementName;
qDebug() << "findElementByName converted to" << i;
indexList.push_back(i);
found = true;
break;
}
}
// look up the name/value pair
else if (type == "QVariantMap")
{
QStringList keyValuePair = elementName.split("=");
if (keyValuePair.size() == 2)
{
const QString key = keyValuePair.first().trimmed();
keyValuePair.removeFirst();
const QString value = keyValuePair.first().trimmed();
if (!key.isNull() && !key.isEmpty()
&& !value.isNull() && !value.isEmpty())
{
QVariantMap elementMap(v.toMap());
const QString actual = elementMap[key].toString();
if (actual == value)
{
qDebug() << "findElementByName found map" << key << value;
qDebug() << "findElementByName converted to" << i;
indexList.push_back(i);
found = true;
break;
}
}
}
}
}
if (!found)
{
failed = true;
break;
}
indexes.removeFirst();
}
if (!failed)
{
qDebug() << "findElementByName index is" << indexList;
result = model->data(indexList);
}
return result;
}
void ListCommand::showHelp()
{
this->client->write("> list <list> count <expectedSize>\r\n");
}
} // namespace cascades
} // namespace test
} // namespace truphone
<|endoftext|> |
<commit_before>#include "imageviewer.h"
#include "ui_imageviewer.h"
ImageViewer::ImageViewer(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ImageViewer)
{
ui->setupUi(this);
QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg");
ui->imageLabel->setPixmap(QPixmap::fromImage(image));
}
ImageViewer::~ImageViewer()
{
delete ui;
}
<commit_msg>Set imageLabel and scrollArea properties<commit_after>#include "imageviewer.h"
#include "ui_imageviewer.h"
ImageViewer::ImageViewer(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ImageViewer)
{
ui->setupUi(this);
ui->imageLabel->setBackgroundRole(QPalette::Base);
ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
ui->imageLabel->setScaledContents(true);
ui->scrollArea->setBackgroundRole(QPalette::Dark);
QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg");
ui->imageLabel->setPixmap(QPixmap::fromImage(image));
setWindowTitle(tr("Image Viewer"));
}
ImageViewer::~ImageViewer()
{
delete ui;
}
<|endoftext|> |
<commit_before>#ifndef LIBTEN_HTTP_SERVER_HH
#define LIBTEN_HTTP_SERVER_HH
#include <fnmatch.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <chrono>
#include <functional>
#include <netinet/tcp.h>
#include "ten/buffer.hh"
#include "ten/logging.hh"
#include "ten/task.hh"
#include "ten/net.hh"
#include "ten/http/http_message.hh"
#include "ten/uri.hh"
namespace ten {
//! http request/response pair; keeps reference to request and socket
// (the term "exchange" appears in the standard)
struct http_exchange {
http_request &req;
netsock &sock;
http_response resp {404};
bool resp_sent {false};
std::chrono::high_resolution_clock::time_point start;
http_exchange(http_request &req_, netsock &sock_)
: req(req_),
sock(sock_),
start(std::chrono::steady_clock::now())
{}
~http_exchange() {
if (!resp_sent) {
// ensure a response is sent
send_response();
}
if (will_close()) {
sock.close();
}
}
bool will_close() {
if ((resp.version <= http_1_0 && boost::iequals(resp.get("Connection"), "Keep-Alive")) ||
!boost::iequals(resp.get("Connection"), "close"))
{
return true;
}
return false;
}
//! compose a uri from the request uri
uri get_uri(std::string host="") const {
if (host.empty()) {
host = req.get("Host");
// TODO: transform to preserve passed in host
if (boost::starts_with(req.uri, "http://")) {
return req.uri;
}
}
if (host.empty()) {
// just make up a host
host = "localhost";
}
uri tmp;
tmp.host = host;
tmp.scheme = "http";
tmp.path = req.uri;
return tmp.compose();
}
//! send response to this request
ssize_t send_response() {
if (resp_sent) return 0;
resp_sent = true;
// TODO: Content-Length might be good to add to normal responses,
// but only if Transfer-Encoding isn't chunked?
if (resp.status_code >= 400 && resp.status_code <= 599
&& resp.get("Content-Length").empty()
&& req.method != "HEAD")
{
resp.set("Content-Length", resp.body.size());
}
// HTTP/1.1 requires Date, so lets add it
if (resp.get("Date").empty()) {
char buf[128];
struct tm tm;
time_t now = std::chrono::system_clock::to_time_t(procnow());
strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&now, &tm));
resp.set("Date", buf);
}
if (resp.get("Connection").empty()) {
// obey clients wishes if we have none of our own
std::string conn = req.get("Connection");
if (!conn.empty())
resp.set("Connection", conn);
else if (req.version == http_1_0)
resp.set("Connection", "close");
}
auto data = resp.data();
if (!resp.body.empty() && req.method != "HEAD") {
data += resp.body;
}
ssize_t nw = sock.send(data.data(), data.size());
return nw;
}
//! the ip of the host making the request
//! might use the X-Forwarded-For header
std::string agent_ip(bool use_xff=false) const {
if (use_xff) {
std::string xffs = req.get("X-Forwarded-For");
const char *xff = xffs.c_str();
if (xff) {
// pick the first addr
int i;
for (i=0; *xff && i<256 && !isdigit((unsigned char)*xff); i++, xff++) {}
if (*xff && i < 256) {
// now, find the end
const char *e = xff;
for (i = 0; *e && i<256 && (isdigit((unsigned char)*e) || *e == '.'); i++, e++) {}
if (i < 256 && e >= xff + 7 ) {
return std::string(xff, e - xff);
}
}
}
}
address addr;
if (sock.getpeername(addr)) {
char buf[INET6_ADDRSTRLEN];
if (addr.ntop(buf, sizeof(buf))) {
return buf;
}
}
return "";
}
};
//! basic http server
class http_server : public netsock_server {
public:
typedef std::function<void (http_exchange &)> callback_type;
std::function<void ()> connect_watch;
std::function<void ()> disconnect_watch;
protected:
struct route {
std::string pattern;
callback_type callback;
int fnmatch_flags;
route(const std::string &pattern_,
const callback_type &callback_,
int fnmatch_flags_=0)
: pattern(pattern_), callback(callback_), fnmatch_flags(fnmatch_flags_) {}
};
std::vector<route> _routes;
callback_type _log_func;
public:
http_server(size_t stacksize_=default_stacksize, unsigned timeout_ms_=0)
: netsock_server("http", stacksize_, timeout_ms_)
{
}
//! add a callback for a uri with an fnmatch pattern
void add_route(const std::string &pattern,
const callback_type &callback,
int fnmatch_flags = 0)
{
_routes.emplace_back(pattern, callback, fnmatch_flags);
}
//! set logging function, called after every exchange
void set_log_callback(const callback_type &f) {
_log_func = f;
}
private:
virtual void setup_listen_socket(netsock &s) {
netsock_server::setup_listen_socket(s);
s.setsockopt(IPPROTO_TCP, TCP_DEFER_ACCEPT, 30);
}
void on_connection(netsock &s) {
// TODO: tuneable buffer sizes
buffer buf(4*1024);
http_parser parser;
if (connect_watch) {
connect_watch();
}
bool nodelay_set = false;
http_request req;
for (;;) {
req.parser_init(&parser);
bool got_headers = false;
for (;;) {
buf.reserve(4*1024);
ssize_t nr = -1;
if (buf.size() == 0) {
nr = s.recv(buf.back(), buf.available(), _timeout_ms);
if (nr < 0) goto done;
buf.commit(nr);
}
size_t nparse = buf.size();
req.parse(&parser, buf.front(), nparse);
buf.remove(nparse);
if (req.complete) {
DVLOG(4) << req.data();
// handle http exchange (request -> response)
http_exchange ex(req, s);
if (!nodelay_set && !ex.will_close()) {
// this is a persistent connection, so low-latency sending is worth the overh
s.s.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1);
nodelay_set = true;
}
handle_exchange(ex);
break;
}
if (nr == 0) goto done;
if (!got_headers && !req.method.empty()) {
got_headers = true;
if (req.get("Expect") == "100-continue") {
http_response cont_resp(100);
std::string data = cont_resp.data();
ssize_t nw = s.send(data.data(), data.size());
(void)nw;
}
}
}
}
done:
if (disconnect_watch) {
disconnect_watch();
}
}
void handle_exchange(http_exchange &ex) {
const auto path = ex.req.path();
DVLOG(5) << "path: " << path;
// not super efficient, but good enough
// note: empty string pattern matches everything
for (const auto &i : _routes) {
DVLOG(5) << "matching pattern: " << i.pattern;
if (i.pattern.empty() || fnmatch(i.pattern.c_str(), path.c_str(), i.fnmatch_flags) == 0) {
try {
i.callback(ex);
} catch (std::exception &e) {
DVLOG(2) << "unhandled exception in route [" << i.pattern << "]: " << e.what();
ex.resp = http_response(500, http_headers{"Connection", "close"});
std::string msg = e.what();
if (!msg.empty() && *msg.rbegin() != '\n')
msg += '\n';
ex.resp.set_body(msg);
ex.send_response();
}
break;
}
}
if (_log_func) {
_log_func(ex);
}
}
};
} // end namespace ten
#endif // LIBTEN_HTTP_SERVER_HH
<commit_msg>fix logic error in http_exchange::will_close<commit_after>#ifndef LIBTEN_HTTP_SERVER_HH
#define LIBTEN_HTTP_SERVER_HH
#include <fnmatch.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <chrono>
#include <functional>
#include <netinet/tcp.h>
#include "ten/buffer.hh"
#include "ten/logging.hh"
#include "ten/task.hh"
#include "ten/net.hh"
#include "ten/http/http_message.hh"
#include "ten/uri.hh"
namespace ten {
//! http request/response pair; keeps reference to request and socket
// (the term "exchange" appears in the standard)
struct http_exchange {
http_request &req;
netsock &sock;
http_response resp {404};
bool resp_sent {false};
std::chrono::high_resolution_clock::time_point start;
http_exchange(http_request &req_, netsock &sock_)
: req(req_),
sock(sock_),
start(std::chrono::steady_clock::now())
{}
http_exchange(const http_exchange &) = delete;
http_exchange &operator=(const http_exchange &) = delete;
~http_exchange() {
if (!resp_sent) {
// ensure a response is sent
send_response();
}
if (will_close()) {
sock.close();
}
}
bool will_close() {
if ((resp.version <= http_1_0 && boost::iequals(resp.get("Connection"), "Keep-Alive")) ||
!boost::iequals(resp.get("Connection"), "close"))
{
return false;
}
return true;
}
//! compose a uri from the request uri
uri get_uri(std::string host="") const {
if (host.empty()) {
host = req.get("Host");
// TODO: transform to preserve passed in host
if (boost::starts_with(req.uri, "http://")) {
return req.uri;
}
}
if (host.empty()) {
// just make up a host
host = "localhost";
}
uri tmp;
tmp.host = host;
tmp.scheme = "http";
tmp.path = req.uri;
return tmp.compose();
}
//! send response to this request
ssize_t send_response() {
if (resp_sent) return 0;
resp_sent = true;
// TODO: Content-Length might be good to add to normal responses,
// but only if Transfer-Encoding isn't chunked?
if (resp.status_code >= 400 && resp.status_code <= 599
&& resp.get("Content-Length").empty()
&& req.method != "HEAD")
{
resp.set("Content-Length", resp.body.size());
}
// HTTP/1.1 requires Date, so lets add it
if (resp.get("Date").empty()) {
char buf[128];
struct tm tm;
time_t now = std::chrono::system_clock::to_time_t(procnow());
strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&now, &tm));
resp.set("Date", buf);
}
if (resp.get("Connection").empty()) {
// obey clients wishes if we have none of our own
std::string conn = req.get("Connection");
if (!conn.empty())
resp.set("Connection", conn);
else if (req.version == http_1_0)
resp.set("Connection", "close");
}
auto data = resp.data();
if (!resp.body.empty() && req.method != "HEAD") {
data += resp.body;
}
ssize_t nw = sock.send(data.data(), data.size());
return nw;
}
//! the ip of the host making the request
//! might use the X-Forwarded-For header
std::string agent_ip(bool use_xff=false) const {
if (use_xff) {
std::string xffs = req.get("X-Forwarded-For");
const char *xff = xffs.c_str();
if (xff) {
// pick the first addr
int i;
for (i=0; *xff && i<256 && !isdigit((unsigned char)*xff); i++, xff++) {}
if (*xff && i < 256) {
// now, find the end
const char *e = xff;
for (i = 0; *e && i<256 && (isdigit((unsigned char)*e) || *e == '.'); i++, e++) {}
if (i < 256 && e >= xff + 7 ) {
return std::string(xff, e - xff);
}
}
}
}
address addr;
if (sock.getpeername(addr)) {
char buf[INET6_ADDRSTRLEN];
if (addr.ntop(buf, sizeof(buf))) {
return buf;
}
}
return "";
}
};
//! basic http server
class http_server : public netsock_server {
public:
typedef std::function<void (http_exchange &)> callback_type;
std::function<void ()> connect_watch;
std::function<void ()> disconnect_watch;
protected:
struct route {
std::string pattern;
callback_type callback;
int fnmatch_flags;
route(const std::string &pattern_,
const callback_type &callback_,
int fnmatch_flags_=0)
: pattern(pattern_), callback(callback_), fnmatch_flags(fnmatch_flags_) {}
};
std::vector<route> _routes;
callback_type _log_func;
public:
http_server(size_t stacksize_=default_stacksize, unsigned timeout_ms_=0)
: netsock_server("http", stacksize_, timeout_ms_)
{
}
//! add a callback for a uri with an fnmatch pattern
void add_route(const std::string &pattern,
const callback_type &callback,
int fnmatch_flags = 0)
{
_routes.emplace_back(pattern, callback, fnmatch_flags);
}
//! set logging function, called after every exchange
void set_log_callback(const callback_type &f) {
_log_func = f;
}
private:
virtual void setup_listen_socket(netsock &s) {
netsock_server::setup_listen_socket(s);
s.setsockopt(IPPROTO_TCP, TCP_DEFER_ACCEPT, 30);
}
void on_connection(netsock &s) {
// TODO: tuneable buffer sizes
buffer buf(4*1024);
http_parser parser;
if (connect_watch) {
connect_watch();
}
bool nodelay_set = false;
http_request req;
for (;;) {
req.parser_init(&parser);
bool got_headers = false;
for (;;) {
buf.reserve(4*1024);
ssize_t nr = -1;
if (buf.size() == 0) {
nr = s.recv(buf.back(), buf.available(), _timeout_ms);
if (nr < 0) goto done;
buf.commit(nr);
}
size_t nparse = buf.size();
req.parse(&parser, buf.front(), nparse);
buf.remove(nparse);
if (req.complete) {
DVLOG(4) << req.data();
// handle http exchange (request -> response)
http_exchange ex(req, s);
if (!nodelay_set && !ex.will_close()) {
// this is a persistent connection, so low-latency sending is worth the overh
s.s.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1);
nodelay_set = true;
}
handle_exchange(ex);
break;
}
if (nr == 0) goto done;
if (!got_headers && !req.method.empty()) {
got_headers = true;
if (req.get("Expect") == "100-continue") {
http_response cont_resp(100);
std::string data = cont_resp.data();
ssize_t nw = s.send(data.data(), data.size());
(void)nw;
}
}
}
}
done:
if (disconnect_watch) {
disconnect_watch();
}
}
void handle_exchange(http_exchange &ex) {
const auto path = ex.req.path();
DVLOG(5) << "path: " << path;
// not super efficient, but good enough
// note: empty string pattern matches everything
for (const auto &i : _routes) {
DVLOG(5) << "matching pattern: " << i.pattern;
if (i.pattern.empty() || fnmatch(i.pattern.c_str(), path.c_str(), i.fnmatch_flags) == 0) {
try {
i.callback(ex);
} catch (std::exception &e) {
DVLOG(2) << "unhandled exception in route [" << i.pattern << "]: " << e.what();
ex.resp = http_response(500, http_headers{"Connection", "close"});
std::string msg = e.what();
if (!msg.empty() && *msg.rbegin() != '\n')
msg += '\n';
ex.resp.set_body(msg);
ex.send_response();
}
break;
}
}
if (_log_func) {
_log_func(ex);
}
}
};
} // end namespace ten
#endif // LIBTEN_HTTP_SERVER_HH
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: types.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 14:26:37 $
*
* 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 INCLUDED_SHARABLE_BASETYPES_HXX
#define INCLUDED_SHARABLE_BASETYPES_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
//-----------------------------------------------------------------------------
namespace rtl { class OUString; }
//-----------------------------------------------------------------------------
namespace configmgr
{
namespace sharable
{
//-----------------------------------------------------------------------------
// some base types
typedef sal_uInt16 Offset; // Offset relative to 'this' in array of nodes
// some derived types
typedef rtl_uString * Name;
typedef rtl_uString * String;
typedef struct TreeFragment * List; // singly linked intrusive, used for set elements
typedef sal_uInt8 * Vector; // points to counted sequence of some type
//-----------------------------------------------------------------------------
inline String allocString(::rtl::OUString const & _sString)
{
rtl_uString_acquire(_sString.pData);
return _sString.pData;
}
inline void freeString(String _aString)
{ rtl_uString_release(_aString); }
inline ::rtl::OUString readString(String _aString)
{ return rtl::OUString(_aString); }
//-----------------------------------------------------------------------------
inline Name allocName(::rtl::OUString const & _aName)
{ return allocString(_aName); }
inline void freeName(Name _aName)
{ freeString(_aName); }
inline ::rtl::OUString readName(Name _aName)
{ return readString(_aName); }
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // INCLUDED_SHARABLE_BASETYPES_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.16); FILE MERGED 2008/04/01 15:06:45 thb 1.5.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:46 rt 1.5.16.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: types.hxx,v $
* $Revision: 1.6 $
*
* 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 INCLUDED_SHARABLE_BASETYPES_HXX
#define INCLUDED_SHARABLE_BASETYPES_HXX
#include <sal/types.h>
#include <rtl/ustring.hxx>
//-----------------------------------------------------------------------------
namespace rtl { class OUString; }
//-----------------------------------------------------------------------------
namespace configmgr
{
namespace sharable
{
//-----------------------------------------------------------------------------
// some base types
typedef sal_uInt16 Offset; // Offset relative to 'this' in array of nodes
// some derived types
typedef rtl_uString * Name;
typedef rtl_uString * String;
typedef struct TreeFragment * List; // singly linked intrusive, used for set elements
typedef sal_uInt8 * Vector; // points to counted sequence of some type
//-----------------------------------------------------------------------------
inline String allocString(::rtl::OUString const & _sString)
{
rtl_uString_acquire(_sString.pData);
return _sString.pData;
}
inline void freeString(String _aString)
{ rtl_uString_release(_aString); }
inline ::rtl::OUString readString(String _aString)
{ return rtl::OUString(_aString); }
//-----------------------------------------------------------------------------
inline Name allocName(::rtl::OUString const & _aName)
{ return allocString(_aName); }
inline void freeName(Name _aName)
{ freeString(_aName); }
inline ::rtl::OUString readName(Name _aName)
{ return readString(_aName); }
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // INCLUDED_SHARABLE_BASETYPES_HXX
<|endoftext|> |
<commit_before>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp/FieldId.h>
#include <thrift/lib/cpp2/gen/module_types_h.h>
#include <thrift/lib/cpp2/op/Create.h>
#include <thrift/lib/cpp2/type/Tag.h>
#include <thrift/lib/cpp2/type/Testing.h>
#include <thrift/lib/thrift/gen-cpp2/type_types.h>
#include <thrift/test/testset/Testset.h>
#include <thrift/test/testset/gen-cpp2/testset_types.h>
namespace apache::thrift::op {
namespace {
using namespace apache::thrift::type;
namespace testset = apache::thrift::test::testset;
// Wrapper with default constructor deleted.
template <typename T>
struct Wrapper {
T value;
Wrapper() = delete;
bool operator==(const Wrapper& other) const { return value == other.value; }
bool operator<(const Wrapper& other) const { return value < other.value; }
};
// Wrapper with context with default constructor deleted.
template <typename T>
struct WrapperWithContext {
T value;
int16_t fieldId = 0;
std::string* meta = nullptr;
WrapperWithContext() = delete;
bool operator==(const WrapperWithContext& other) const {
return value == other.value;
}
bool operator<(const WrapperWithContext& other) const {
return value < other.value;
}
};
struct TestTypeAdapter {
template <typename T>
static Wrapper<T> fromThrift(T value) {
return {value};
}
template <typename T>
static T toThrift(Wrapper<T> wrapper) {
return wrapper.value;
}
};
struct TestFieldAdapter {
template <typename T, typename Struct, int16_t FieldId>
static WrapperWithContext<T> fromThriftField(
T value, apache::thrift::FieldAdapterContext<Struct, FieldId>&& ctx) {
return {value, ctx.kFieldId, &ctx.object.meta};
}
template <typename T>
static T toThrift(WrapperWithContext<T> wrapper) {
return wrapper.value;
}
template <typename T, typename Context>
static void construct(WrapperWithContext<T>& field, Context&& ctx) {
field.fieldId = Context::kFieldId;
field.meta = &ctx.object.meta;
}
};
struct TestThriftType {
std::string meta;
};
template <typename Tag>
void testCreateWithTag() {
using tag = Tag;
using field_tag = field_t<FieldId{0}, tag>;
using adapted_tag = adapted<TestTypeAdapter, tag>;
using type_adapted_field_tag = field_t<FieldId{0}, adapted_tag>;
using field_adapted_field_tag =
field_t<FieldId{0}, adapted<TestFieldAdapter, tag>>;
TestThriftType object;
auto type_created = create<tag>();
auto adapted_created = create<adapted_tag>();
auto field_created = create<field_tag>(object);
auto type_adapted_field_created = create<type_adapted_field_tag>(object);
auto field_adapted_field_created = create<field_adapted_field_tag>(object);
test::same_type<decltype(type_created), native_type<tag>>;
test::same_type<decltype(adapted_created), Wrapper<native_type<tag>>>;
test::same_type<decltype(field_created), native_type<tag>>;
test::same_type<
decltype(type_adapted_field_created),
Wrapper<native_type<tag>>>;
test::same_type<
decltype(field_adapted_field_created),
WrapperWithContext<native_type<tag>>>;
Wrapper<native_type<tag>> type_adapted_default{native_type<tag>()};
WrapperWithContext<native_type<tag>> field_adapted_default{
native_type<tag>()};
EXPECT_EQ(type_created, native_type<tag>());
EXPECT_EQ(adapted_created, type_adapted_default);
EXPECT_EQ(field_created, native_type<tag>());
EXPECT_EQ(type_adapted_field_created, type_adapted_default);
EXPECT_EQ(field_adapted_field_created, field_adapted_default);
// Check if the context is correctly populated.
EXPECT_EQ(&object.meta, field_adapted_field_created.meta);
}
template <typename Tag>
void testCreateStructured() {
testCreateWithTag<struct_t<testset::struct_with<Tag>>>();
testCreateWithTag<
struct_t<testset::struct_with<Tag, testset::FieldModifier::Optional>>>();
testCreateWithTag<exception_t<testset::exception_with<Tag>>>();
testCreateWithTag<exception_t<
testset::exception_with<Tag, testset::FieldModifier::Optional>>>();
testCreateWithTag<union_t<testset::union_with<Tag>>>();
}
template <typename Tag>
void testCreate() {
testCreateWithTag<Tag>();
testCreateStructured<Tag>();
}
TEST(CreateTest, Integral) {
testCreate<bool_t>();
testCreate<byte_t>();
testCreate<i16_t>();
testCreate<i32_t>();
testCreate<i64_t>();
// testset does not include structured with Enum.
testCreateWithTag<enum_t<ThriftBaseType>>();
}
TEST(CreateTest, FloatingPoint) {
testCreate<float_t>();
testCreate<double_t>();
}
TEST(CreateTest, String) {
testCreate<string_t>();
testCreate<binary_t>();
}
TEST(CreateTest, Container) {
testCreate<list<string_t>>();
testCreate<set<string_t>>();
testCreate<map<string_t, string_t>>();
}
} // namespace
} // namespace apache::thrift::op
<commit_msg>Fix CreateTest<commit_after>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp/FieldId.h>
#include <thrift/lib/cpp2/gen/module_types_h.h>
#include <thrift/lib/cpp2/op/Create.h>
#include <thrift/lib/cpp2/type/Tag.h>
#include <thrift/lib/cpp2/type/Testing.h>
#include <thrift/lib/thrift/gen-cpp2/type_types.h>
#include <thrift/test/testset/Testset.h>
#include <thrift/test/testset/gen-cpp2/testset_types.h>
namespace apache::thrift::op {
namespace {
using namespace apache::thrift::type;
namespace testset = apache::thrift::test::testset;
// Wrapper with default constructor deleted.
template <typename T>
struct Wrapper {
T value;
// TODO(afuller): Support adapting the 'create' op.
// Wrapper() = delete;
bool operator==(const Wrapper& other) const { return value == other.value; }
bool operator<(const Wrapper& other) const { return value < other.value; }
};
// Wrapper with context with default constructor deleted.
template <typename T>
struct WrapperWithContext {
T value;
int16_t fieldId = 0;
std::string* meta = nullptr;
// TODO(afuller): Support adapting the 'create' op.
// WrapperWithContext() = delete;
bool operator==(const WrapperWithContext& other) const {
return value == other.value;
}
bool operator<(const WrapperWithContext& other) const {
return value < other.value;
}
};
struct TestTypeAdapter {
template <typename T>
static Wrapper<T> fromThrift(T value) {
return {value};
}
template <typename T>
static T toThrift(Wrapper<T> wrapper) {
return wrapper.value;
}
};
struct TestFieldAdapter {
template <typename T, typename Struct, int16_t FieldId>
static WrapperWithContext<T> fromThriftField(
T value, apache::thrift::FieldAdapterContext<Struct, FieldId>&& ctx) {
return {value, ctx.kFieldId, &ctx.object.meta};
}
template <typename T>
static T toThrift(WrapperWithContext<T> wrapper) {
return wrapper.value;
}
template <typename T, typename Context>
static void construct(WrapperWithContext<T>& field, Context&& ctx) {
field.fieldId = Context::kFieldId;
field.meta = &ctx.object.meta;
}
};
struct TestThriftType {
std::string meta;
};
template <typename Tag>
void testCreateWithTag() {
using tag = Tag;
using field_tag = field_t<FieldId{0}, tag>;
using adapted_tag = adapted<TestTypeAdapter, tag>;
using type_adapted_field_tag = field_t<FieldId{0}, adapted_tag>;
using field_adapted_field_tag =
field_t<FieldId{0}, adapted<TestFieldAdapter, tag>>;
TestThriftType object;
auto type_created = create<tag>();
auto adapted_created = create<adapted_tag>();
auto field_created = create<field_tag>(object);
auto type_adapted_field_created = create<type_adapted_field_tag>(object);
auto field_adapted_field_created = create<field_adapted_field_tag>(object);
test::same_type<decltype(type_created), native_type<tag>>;
test::same_type<decltype(adapted_created), Wrapper<native_type<tag>>>;
test::same_type<decltype(field_created), native_type<tag>>;
test::same_type<
decltype(type_adapted_field_created),
Wrapper<native_type<tag>>>;
test::same_type<
decltype(field_adapted_field_created),
WrapperWithContext<native_type<tag>>>;
Wrapper<native_type<tag>> type_adapted_default{native_type<tag>()};
WrapperWithContext<native_type<tag>> field_adapted_default{
native_type<tag>()};
EXPECT_EQ(type_created, native_type<tag>());
EXPECT_EQ(adapted_created, type_adapted_default);
EXPECT_EQ(field_created, native_type<tag>());
EXPECT_EQ(type_adapted_field_created, type_adapted_default);
EXPECT_EQ(field_adapted_field_created, field_adapted_default);
// Check if the context is correctly populated.
EXPECT_EQ(&object.meta, field_adapted_field_created.meta);
}
template <typename Tag>
void testCreateStructured() {
testCreateWithTag<struct_t<testset::struct_with<Tag>>>();
testCreateWithTag<
struct_t<testset::struct_with<Tag, testset::FieldModifier::Optional>>>();
testCreateWithTag<exception_t<testset::exception_with<Tag>>>();
testCreateWithTag<exception_t<
testset::exception_with<Tag, testset::FieldModifier::Optional>>>();
testCreateWithTag<union_t<testset::union_with<Tag>>>();
}
template <typename Tag>
void testCreate() {
testCreateWithTag<Tag>();
testCreateStructured<Tag>();
}
TEST(CreateTest, Integral) {
testCreate<bool_t>();
testCreate<byte_t>();
testCreate<i16_t>();
testCreate<i32_t>();
testCreate<i64_t>();
// testset does not include structured with Enum.
testCreateWithTag<enum_t<ThriftBaseType>>();
}
TEST(CreateTest, FloatingPoint) {
testCreate<float_t>();
testCreate<double_t>();
}
TEST(CreateTest, String) {
testCreate<string_t>();
testCreate<binary_t>();
}
TEST(CreateTest, Container) {
testCreate<list<string_t>>();
testCreate<set<string_t>>();
testCreate<map<string_t, string_t>>();
}
} // namespace
} // namespace apache::thrift::op
<|endoftext|> |
<commit_before>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Nate Begeman and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86 specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "X86Subtarget.h"
#include "llvm/Module.h"
#include "X86GenSubtarget.inc"
using namespace llvm;
static void GetCpuIDAndInfo(unsigned value, unsigned *EAX, unsigned *EBX,
unsigned *ECX, unsigned *EDX) {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
#if defined(__GNUC__)
asm ("pushl\t%%ebx\n\t"
"cpuid\n\t"
"movl\t%%ebx, %%esi\n\t"
"popl\t%%ebx"
: "=a" (*EAX),
"=S" (*EBX),
"=c" (*ECX),
"=d" (*EDX)
: "a" (value));
#endif
#endif
}
static const char *GetCurrentX86CPU() {
unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
unsigned Family = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; // Bits 8 - 11
unsigned Model = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; // Bits 4 - 7
GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
bool Em64T = EDX & (1 << 29);
switch (Family) {
case 3:
return "i386";
case 4:
return "i486";
case 5:
switch (Model) {
case 4: return "pentium-mmx";
default: return "pentium";
}
break;
case 6:
switch (Model) {
case 1: return "pentiumpro";
case 3:
case 5:
case 6: return "pentium2";
case 7:
case 8:
case 10:
case 11: return "pentium3";
case 9:
case 13: return "pentium-m";
case 14: return "yonah";
default: return "i686";
}
case 15: {
switch (Model) {
case 3:
case 4:
return (Em64T) ? "nocona" : "prescott";
default:
return (Em64T) ? "x86-64" : "pentium4";
}
}
default:
return "generic";
}
}
X86Subtarget::X86Subtarget(const Module &M, const std::string &FS)
: stackAlignment(8), indirectExternAndWeakGlobals(false) {
// Determine default and user specified characteristics
std::string CPU = GetCurrentX86CPU();
// Parse features string.
ParseSubtargetFeatures(FS, CPU);
// Default to ELF unless otherwise specified.
TargetType = isELF;
// FIXME: Force these off until they work. An llc-beta option should turn
// them back on.
X86SSELevel = NoMMXSSE;
X863DNowLevel = NoThreeDNow;
// Set the boolean corresponding to the current target triple, or the default
// if one cannot be determined, to true.
const std::string& TT = M.getTargetTriple();
if (TT.length() > 5) {
if (TT.find("cygwin") != std::string::npos ||
TT.find("mingw") != std::string::npos)
TargetType = isCygwin;
else if (TT.find("darwin") != std::string::npos)
TargetType = isDarwin;
else if (TT.find("win32") != std::string::npos)
TargetType = isWindows;
} else if (TT.empty()) {
#if defined(__CYGWIN__) || defined(__MINGW32__)
TargetType = isCygwin;
#elif defined(__APPLE__)
TargetType = isDarwin;
#elif defined(_WIN32)
TargetType = isWindows;
#endif
}
if (TargetType == isDarwin) {
stackAlignment = 16;
indirectExternAndWeakGlobals = true;
}
}
<commit_msg>Added a temporary option -enable-x86-sse to enable sse support. It is used by llc-beta.<commit_after>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Nate Begeman and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86 specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "X86Subtarget.h"
#include "llvm/Module.h"
#include "X86GenSubtarget.inc"
using namespace llvm;
// FIXME: temporary.
#include "llvm/Support/CommandLine.h"
namespace {
cl::opt<bool> EnableSSE("enable-x86-sse", cl::Hidden,
cl::desc("Enable sse on X86"));
}
static void GetCpuIDAndInfo(unsigned value, unsigned *EAX, unsigned *EBX,
unsigned *ECX, unsigned *EDX) {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
#if defined(__GNUC__)
asm ("pushl\t%%ebx\n\t"
"cpuid\n\t"
"movl\t%%ebx, %%esi\n\t"
"popl\t%%ebx"
: "=a" (*EAX),
"=S" (*EBX),
"=c" (*ECX),
"=d" (*EDX)
: "a" (value));
#endif
#endif
}
static const char *GetCurrentX86CPU() {
unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
unsigned Family = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; // Bits 8 - 11
unsigned Model = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; // Bits 4 - 7
GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
bool Em64T = EDX & (1 << 29);
switch (Family) {
case 3:
return "i386";
case 4:
return "i486";
case 5:
switch (Model) {
case 4: return "pentium-mmx";
default: return "pentium";
}
break;
case 6:
switch (Model) {
case 1: return "pentiumpro";
case 3:
case 5:
case 6: return "pentium2";
case 7:
case 8:
case 10:
case 11: return "pentium3";
case 9:
case 13: return "pentium-m";
case 14: return "yonah";
default: return "i686";
}
case 15: {
switch (Model) {
case 3:
case 4:
return (Em64T) ? "nocona" : "prescott";
default:
return (Em64T) ? "x86-64" : "pentium4";
}
}
default:
return "generic";
}
}
X86Subtarget::X86Subtarget(const Module &M, const std::string &FS)
: stackAlignment(8), indirectExternAndWeakGlobals(false) {
// Determine default and user specified characteristics
std::string CPU = GetCurrentX86CPU();
// Parse features string.
ParseSubtargetFeatures(FS, CPU);
// Default to ELF unless otherwise specified.
TargetType = isELF;
// FIXME: Force these off until they work. An llc-beta option should turn
// them back on.
if (!EnableSSE) {
X86SSELevel = NoMMXSSE;
X863DNowLevel = NoThreeDNow;
}
// Set the boolean corresponding to the current target triple, or the default
// if one cannot be determined, to true.
const std::string& TT = M.getTargetTriple();
if (TT.length() > 5) {
if (TT.find("cygwin") != std::string::npos ||
TT.find("mingw") != std::string::npos)
TargetType = isCygwin;
else if (TT.find("darwin") != std::string::npos)
TargetType = isDarwin;
else if (TT.find("win32") != std::string::npos)
TargetType = isWindows;
} else if (TT.empty()) {
#if defined(__CYGWIN__) || defined(__MINGW32__)
TargetType = isCygwin;
#elif defined(__APPLE__)
TargetType = isDarwin;
#elif defined(_WIN32)
TargetType = isWindows;
#endif
}
if (TargetType == isDarwin) {
stackAlignment = 16;
indirectExternAndWeakGlobals = true;
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTL_CONFIG_HPP
#define XTL_CONFIG_HPP
#define XTL_VERSION_MAJOR 0
#define XTL_VERSION_MINOR 3
#define XTL_VERSION_PATCH 1
#endif
<commit_msg>Release 0.3.2<commit_after>/***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTL_CONFIG_HPP
#define XTL_CONFIG_HPP
#define XTL_VERSION_MAJOR 0
#define XTL_VERSION_MINOR 3
#define XTL_VERSION_PATCH 2
#endif
<|endoftext|> |
<commit_before>/*
This program shows how to process BLAS LEVEL2 spr
for i = 0 .. N
for j = 0 .. N
C[i,j] = A[i,j] + alpha * X[i]*X[j]
*/
#include <tiramisu/tiramisu.h>
#define NN 100
#define alpha 3
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("spr");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant N("N", NN);
var i("i", 0, N), j("j", 0, N);
// Declare inputs : A(Matrix N*N) , X(Vector dim=N)
input A("A", {i, j}, p_uint8);
input x("B", {i}, p_uint8);
// Declare output which is result of computation
computation output("output", {i,j}, expr((uint8_t)alpha) * x(j) * x(i) + A(i, j) );
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
// Declare the buffers.
buffer b_A("b_A", {N,N}, p_uint8, a_input);
buffer b_x("b_x", {N}, p_uint8, a_input);
buffer b_output("b_output", {N,N}, p_uint8, a_output);
// Map the computations to a buffer.
A.store_in(&b_A);
x.store_in(&b_x);
output.store_in(&b_output,{i,j});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_A, &b_x, &b_output}, "build/generated_fct_developers_spr.o");
return 0;
}
<commit_msg>Update spr.cpp<commit_after>/*
This program shows how to process BLAS LEVEL2 spr
for i = 0 .. N
for j = 0 .. N
C[i,j] = A[i,j] + alpha * X[i]*X[j]
*/
#include <tiramisu/tiramisu.h>
#define NN 100
#define alpha 3
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("spr");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant N("N", NN);
var i("i", 0, N), j("j", 0, N);
// Declare inputs : A(Matrix N*N) , X(Vector dim=N)
input A("A", {i, j}, p_uint8);
input x("B", {i}, p_uint8);
// Declare output which is result of computation
computation output("output", {i,j}, expr((uint8_t)alpha) * x(j) * x(i) + A(i, j) );
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
// Declare the buffers.
buffer b_A("b_A", {N,N}, p_uint8, a_input);
buffer b_x("b_x", {N}, p_uint8, a_input);
buffer b_output("b_output", {N,N}, p_uint8, a_output);
// Map the computations to a buffer.
A.store_in(&b_A);
x.store_in(&b_x);
output.store_in(&b_output,{i,j});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_A, &b_x, &b_output}, "build/generated_fct_developers_spr.o");
return 0;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////
// File: renderer.cpp
// Description: Rendering interface to inject into TessBaseAPI
//
// (C) Copyright 2011, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include <cstring>
#include <memory> // std::unique_ptr
#include "baseapi.h"
#include "genericvector.h"
#include "renderer.h"
namespace tesseract {
/**********************************************************************
* Base Renderer interface implementation
**********************************************************************/
TessResultRenderer::TessResultRenderer(const char *outputbase,
const char* extension)
: file_extension_(extension),
title_(""), imagenum_(-1),
fout_(stdout),
next_(nullptr),
happy_(true) {
if (strcmp(outputbase, "-") && strcmp(outputbase, "stdout")) {
STRING outfile = STRING(outputbase) + STRING(".") + STRING(file_extension_);
fout_ = fopen(outfile.string(), "wb");
if (fout_ == nullptr) {
happy_ = false;
}
}
}
TessResultRenderer::~TessResultRenderer() {
if (fout_ != nullptr) {
if (fout_ != stdout)
fclose(fout_);
else
clearerr(fout_);
}
delete next_;
}
void TessResultRenderer::insert(TessResultRenderer* next) {
if (next == nullptr) return;
TessResultRenderer* remainder = next_;
next_ = next;
if (remainder) {
while (next->next_ != nullptr) {
next = next->next_;
}
next->next_ = remainder;
}
}
bool TessResultRenderer::BeginDocument(const char* title) {
if (!happy_) return false;
title_ = title;
imagenum_ = -1;
bool ok = BeginDocumentHandler();
if (next_) {
ok = next_->BeginDocument(title) && ok;
}
return ok;
}
bool TessResultRenderer::AddImage(TessBaseAPI* api) {
if (!happy_) return false;
++imagenum_;
bool ok = AddImageHandler(api);
if (next_) {
ok = next_->AddImage(api) && ok;
}
return ok;
}
bool TessResultRenderer::EndDocument() {
if (!happy_) return false;
bool ok = EndDocumentHandler();
if (next_) {
ok = next_->EndDocument() && ok;
}
return ok;
}
void TessResultRenderer::AppendString(const char* s) {
AppendData(s, strlen(s));
}
void TessResultRenderer::AppendData(const char* s, int len) {
if (!tesseract::Serialize(fout_, s, len)) happy_ = false;
}
bool TessResultRenderer::BeginDocumentHandler() {
return happy_;
}
bool TessResultRenderer::EndDocumentHandler() {
return happy_;
}
/**********************************************************************
* UTF8 Text Renderer interface implementation
**********************************************************************/
TessTextRenderer::TessTextRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "txt") {
}
bool TessTextRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> utf8(api->GetUTF8Text());
if (utf8 == nullptr) {
return false;
}
AppendString(utf8.get());
const char* pageSeparator = api->GetStringVariable("page_separator");
if (pageSeparator != nullptr && *pageSeparator != '\0') {
AppendString(pageSeparator);
}
return true;
}
/**********************************************************************
* HOcr Text Renderer interface implementation
**********************************************************************/
TessHOcrRenderer::TessHOcrRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "hocr") {
font_info_ = false;
}
TessHOcrRenderer::TessHOcrRenderer(const char *outputbase, bool font_info)
: TessResultRenderer(outputbase, "hocr") {
font_info_ = font_info;
}
bool TessHOcrRenderer::BeginDocumentHandler() {
AppendString(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" "
"lang=\"en\">\n <head>\n <title>");
AppendString(title());
AppendString(
"</title>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html;"
"charset=utf-8\" />\n"
" <meta name='ocr-system' content='tesseract " PACKAGE_VERSION
"' />\n"
" <meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par"
" ocr_line ocrx_word");
if (font_info_)
AppendString(
" ocrp_lang ocrp_dir ocrp_font ocrp_fsize ocrp_wconf");
AppendString(
"'/>\n"
"</head>\n<body>\n");
return true;
}
bool TessHOcrRenderer::EndDocumentHandler() {
AppendString(" </body>\n</html>\n");
return true;
}
bool TessHOcrRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> hocr(api->GetHOCRText(imagenum()));
if (hocr == nullptr) return false;
AppendString(hocr.get());
return true;
}
/**********************************************************************
* TSV Text Renderer interface implementation
**********************************************************************/
TessTsvRenderer::TessTsvRenderer(const char* outputbase)
: TessResultRenderer(outputbase, "tsv") {
font_info_ = false;
}
TessTsvRenderer::TessTsvRenderer(const char* outputbase, bool font_info)
: TessResultRenderer(outputbase, "tsv") {
font_info_ = font_info;
}
bool TessTsvRenderer::BeginDocumentHandler() {
// Output TSV column headings
AppendString(
"level\tpage_num\tblock_num\tpar_num\tline_num\tword_"
"num\tleft\ttop\twidth\theight\tconf\ttext\n");
return true;
}
bool TessTsvRenderer::EndDocumentHandler() { return true; }
bool TessTsvRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> tsv(api->GetTSVText(imagenum()));
if (tsv == nullptr) return false;
AppendString(tsv.get());
return true;
}
/**********************************************************************
* UNLV Text Renderer interface implementation
**********************************************************************/
TessUnlvRenderer::TessUnlvRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "unlv") {
}
bool TessUnlvRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> unlv(api->GetUNLVText());
if (unlv == nullptr) return false;
AppendString(unlv.get());
return true;
}
/**********************************************************************
* BoxText Renderer interface implementation
**********************************************************************/
TessBoxTextRenderer::TessBoxTextRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "box") {
}
bool TessBoxTextRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> text(api->GetBoxText(imagenum()));
if (text == nullptr) return false;
AppendString(text.get());
return true;
}
#ifndef DISABLED_LEGACY_ENGINE
/**********************************************************************
* Osd Text Renderer interface implementation
**********************************************************************/
TessOsdRenderer::TessOsdRenderer(const char* outputbase)
: TessResultRenderer(outputbase, "osd") {}
bool TessOsdRenderer::AddImageHandler(TessBaseAPI* api) {
char* osd = api->GetOsdText(imagenum());
if (osd == nullptr) return false;
AppendString(osd);
delete[] osd;
return true;
}
#endif // ndef DISABLED_LEGACY_ENGINE
} // namespace tesseract
<commit_msg>hocr: add ocrp_wconf to unconditional ocr-capabilities; fixes #1470<commit_after>///////////////////////////////////////////////////////////////////////
// File: renderer.cpp
// Description: Rendering interface to inject into TessBaseAPI
//
// (C) Copyright 2011, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include <cstring>
#include <memory> // std::unique_ptr
#include "baseapi.h"
#include "genericvector.h"
#include "renderer.h"
namespace tesseract {
/**********************************************************************
* Base Renderer interface implementation
**********************************************************************/
TessResultRenderer::TessResultRenderer(const char *outputbase,
const char* extension)
: file_extension_(extension),
title_(""), imagenum_(-1),
fout_(stdout),
next_(nullptr),
happy_(true) {
if (strcmp(outputbase, "-") && strcmp(outputbase, "stdout")) {
STRING outfile = STRING(outputbase) + STRING(".") + STRING(file_extension_);
fout_ = fopen(outfile.string(), "wb");
if (fout_ == nullptr) {
happy_ = false;
}
}
}
TessResultRenderer::~TessResultRenderer() {
if (fout_ != nullptr) {
if (fout_ != stdout)
fclose(fout_);
else
clearerr(fout_);
}
delete next_;
}
void TessResultRenderer::insert(TessResultRenderer* next) {
if (next == nullptr) return;
TessResultRenderer* remainder = next_;
next_ = next;
if (remainder) {
while (next->next_ != nullptr) {
next = next->next_;
}
next->next_ = remainder;
}
}
bool TessResultRenderer::BeginDocument(const char* title) {
if (!happy_) return false;
title_ = title;
imagenum_ = -1;
bool ok = BeginDocumentHandler();
if (next_) {
ok = next_->BeginDocument(title) && ok;
}
return ok;
}
bool TessResultRenderer::AddImage(TessBaseAPI* api) {
if (!happy_) return false;
++imagenum_;
bool ok = AddImageHandler(api);
if (next_) {
ok = next_->AddImage(api) && ok;
}
return ok;
}
bool TessResultRenderer::EndDocument() {
if (!happy_) return false;
bool ok = EndDocumentHandler();
if (next_) {
ok = next_->EndDocument() && ok;
}
return ok;
}
void TessResultRenderer::AppendString(const char* s) {
AppendData(s, strlen(s));
}
void TessResultRenderer::AppendData(const char* s, int len) {
if (!tesseract::Serialize(fout_, s, len)) happy_ = false;
}
bool TessResultRenderer::BeginDocumentHandler() {
return happy_;
}
bool TessResultRenderer::EndDocumentHandler() {
return happy_;
}
/**********************************************************************
* UTF8 Text Renderer interface implementation
**********************************************************************/
TessTextRenderer::TessTextRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "txt") {
}
bool TessTextRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> utf8(api->GetUTF8Text());
if (utf8 == nullptr) {
return false;
}
AppendString(utf8.get());
const char* pageSeparator = api->GetStringVariable("page_separator");
if (pageSeparator != nullptr && *pageSeparator != '\0') {
AppendString(pageSeparator);
}
return true;
}
/**********************************************************************
* HOcr Text Renderer interface implementation
**********************************************************************/
TessHOcrRenderer::TessHOcrRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "hocr") {
font_info_ = false;
}
TessHOcrRenderer::TessHOcrRenderer(const char *outputbase, bool font_info)
: TessResultRenderer(outputbase, "hocr") {
font_info_ = font_info;
}
bool TessHOcrRenderer::BeginDocumentHandler() {
AppendString(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" "
"lang=\"en\">\n <head>\n <title>");
AppendString(title());
AppendString(
"</title>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html;"
"charset=utf-8\" />\n"
" <meta name='ocr-system' content='tesseract " PACKAGE_VERSION
"' />\n"
" <meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par"
" ocr_line ocrx_word ocrp_wconf");
if (font_info_)
AppendString(
" ocrp_lang ocrp_dir ocrp_font ocrp_fsize");
AppendString(
"'/>\n"
"</head>\n<body>\n");
return true;
}
bool TessHOcrRenderer::EndDocumentHandler() {
AppendString(" </body>\n</html>\n");
return true;
}
bool TessHOcrRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> hocr(api->GetHOCRText(imagenum()));
if (hocr == nullptr) return false;
AppendString(hocr.get());
return true;
}
/**********************************************************************
* TSV Text Renderer interface implementation
**********************************************************************/
TessTsvRenderer::TessTsvRenderer(const char* outputbase)
: TessResultRenderer(outputbase, "tsv") {
font_info_ = false;
}
TessTsvRenderer::TessTsvRenderer(const char* outputbase, bool font_info)
: TessResultRenderer(outputbase, "tsv") {
font_info_ = font_info;
}
bool TessTsvRenderer::BeginDocumentHandler() {
// Output TSV column headings
AppendString(
"level\tpage_num\tblock_num\tpar_num\tline_num\tword_"
"num\tleft\ttop\twidth\theight\tconf\ttext\n");
return true;
}
bool TessTsvRenderer::EndDocumentHandler() { return true; }
bool TessTsvRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> tsv(api->GetTSVText(imagenum()));
if (tsv == nullptr) return false;
AppendString(tsv.get());
return true;
}
/**********************************************************************
* UNLV Text Renderer interface implementation
**********************************************************************/
TessUnlvRenderer::TessUnlvRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "unlv") {
}
bool TessUnlvRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> unlv(api->GetUNLVText());
if (unlv == nullptr) return false;
AppendString(unlv.get());
return true;
}
/**********************************************************************
* BoxText Renderer interface implementation
**********************************************************************/
TessBoxTextRenderer::TessBoxTextRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "box") {
}
bool TessBoxTextRenderer::AddImageHandler(TessBaseAPI* api) {
const std::unique_ptr<const char[]> text(api->GetBoxText(imagenum()));
if (text == nullptr) return false;
AppendString(text.get());
return true;
}
#ifndef DISABLED_LEGACY_ENGINE
/**********************************************************************
* Osd Text Renderer interface implementation
**********************************************************************/
TessOsdRenderer::TessOsdRenderer(const char* outputbase)
: TessResultRenderer(outputbase, "osd") {}
bool TessOsdRenderer::AddImageHandler(TessBaseAPI* api) {
char* osd = api->GetOsdText(imagenum());
if (osd == nullptr) return false;
AppendString(osd);
delete[] osd;
return true;
}
#endif // ndef DISABLED_LEGACY_ENGINE
} // namespace tesseract
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Norwegian University of Science and Technology
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Norwegian University of Science and
* Technology, nor the names of its contributors may be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* 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.
*********************************************************************/
/*
* Author: Lars Tingelstad <lars.tingelstad@ntnu.no>
*/
#include <kuka_rsi_hw_interface/kuka_hardware_interface.h>
namespace kuka_rsi_hw_interface
{
KukaHardwareInterface::KukaHardwareInterface() :
joint_position_(6, 0.0), joint_velocity_(6, 0.0), joint_effort_(6, 0.0), joint_position_command_(6, 0.0), joint_velocity_command_(
6, 0.0), joint_effort_command_(6, 0.0), joint_names_(6), rsi_initial_joint_positions_(6, 0.0), rsi_joint_position_corrections_(
6, 0.0), ipoc_(0), n_dof_(6)
{
in_buffer_.resize(1024);
out_buffer_.resize(1024);
remote_host_.resize(1024);
remote_port_.resize(1024);
nh_.getParam("controller_joint_names", joint_names_);
//Create ros_control interfaces
for (std::size_t i = 0; i < n_dof_; ++i)
{
// Create joint state interface for all joints
joint_state_interface_.registerHandle(
hardware_interface::JointStateHandle(joint_names_[i], &joint_position_[i], &joint_velocity_[i],
&joint_effort_[i]));
// Create joint position control interface
position_joint_interface_.registerHandle(
hardware_interface::JointHandle(joint_state_interface_.getHandle(joint_names_[i]),
&joint_position_command_[i]));
}
// Register interfaces
registerInterface(&joint_state_interface_);
registerInterface(&position_joint_interface_);
ROS_INFO_STREAM_NAMED("hardware_interface", "Loaded kuka_rsi_hardware_interface");
}
KukaHardwareInterface::~KukaHardwareInterface()
{
}
bool KukaHardwareInterface::read(const ros::Time time, const ros::Duration period)
{
in_buffer_.resize(1024);
if (server_->recv(in_buffer_) == 0)
{
return false;
}
if (rt_rsi_pub_->trylock()){
rt_rsi_pub_->msg_.data = in_buffer_;
rt_rsi_pub_->unlockAndPublish();
}
rsi_state_ = RSIState(in_buffer_);
for (std::size_t i = 0; i < n_dof_; ++i)
{
joint_position_[i] = DEG2RAD * rsi_state_.positions[i];
}
ipoc_ = rsi_state_.ipoc;
return true;
}
bool KukaHardwareInterface::write(const ros::Time time, const ros::Duration period)
{
out_buffer_.resize(1024);
for (std::size_t i = 0; i < n_dof_; ++i)
{
rsi_joint_position_corrections_[i] = (RAD2DEG * joint_position_command_[i]) - rsi_initial_joint_positions_[i];
}
out_buffer_ = RSICommand(rsi_joint_position_corrections_, ipoc_).xml_doc;
server_->send(out_buffer_);
return true;
}
void KukaHardwareInterface::start()
{
// Wait for connection from robot
server_.reset(new UDPServer(local_host_, local_port_));
ROS_INFO_STREAM_NAMED("kuka_hardware_interface", "Waiting for robot!");
int bytes = server_->recv(in_buffer_);
rsi_state_ = RSIState(in_buffer_);
for (std::size_t i = 0; i < n_dof_; ++i)
{
joint_position_[i] = DEG2RAD * rsi_state_.positions[i];
joint_position_command_[i] = joint_position_[i];
rsi_initial_joint_positions_[i] = rsi_state_.initial_positions[i];
}
ipoc_ = rsi_state_.ipoc;
out_buffer_ = RSICommand(rsi_joint_position_corrections_, ipoc_).xml_doc;
server_->send(out_buffer_);
// Set receive timeout to 1 second
server_->set_timeout(1000);
ROS_INFO_STREAM_NAMED("kuka_hardware_interface", "Got connection from robot");
}
void KukaHardwareInterface::configure()
{
if (nh_.getParam("rsi/address", local_host_) && nh_.getParam("rsi/port", local_port_))
{
ROS_INFO_STREAM_NAMED("kuka_hardware_interface",
"Setting up RSI server on: (" << local_host_ << ", " << local_port_ << ")");
}
else
{
ROS_ERROR("Failed to get RSI address and port from parameters server!");
}
rt_rsi_pub_.reset(new realtime_tools::RealtimePublisher<std_msgs::String>(nh_, "rsi_xml_doc", 3));
}
} // namespace kuka_rsi_hardware_interface
<commit_msg>rsi_hw_iface: fail if ip address or port parameters are not provided.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Norwegian University of Science and Technology
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Norwegian University of Science and
* Technology, nor the names of its contributors may be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* 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.
*********************************************************************/
/*
* Author: Lars Tingelstad <lars.tingelstad@ntnu.no>
*/
#include <kuka_rsi_hw_interface/kuka_hardware_interface.h>
#include <stdexcept>
namespace kuka_rsi_hw_interface
{
KukaHardwareInterface::KukaHardwareInterface() :
joint_position_(6, 0.0), joint_velocity_(6, 0.0), joint_effort_(6, 0.0), joint_position_command_(6, 0.0), joint_velocity_command_(
6, 0.0), joint_effort_command_(6, 0.0), joint_names_(6), rsi_initial_joint_positions_(6, 0.0), rsi_joint_position_corrections_(
6, 0.0), ipoc_(0), n_dof_(6)
{
in_buffer_.resize(1024);
out_buffer_.resize(1024);
remote_host_.resize(1024);
remote_port_.resize(1024);
nh_.getParam("controller_joint_names", joint_names_);
//Create ros_control interfaces
for (std::size_t i = 0; i < n_dof_; ++i)
{
// Create joint state interface for all joints
joint_state_interface_.registerHandle(
hardware_interface::JointStateHandle(joint_names_[i], &joint_position_[i], &joint_velocity_[i],
&joint_effort_[i]));
// Create joint position control interface
position_joint_interface_.registerHandle(
hardware_interface::JointHandle(joint_state_interface_.getHandle(joint_names_[i]),
&joint_position_command_[i]));
}
// Register interfaces
registerInterface(&joint_state_interface_);
registerInterface(&position_joint_interface_);
ROS_INFO_STREAM_NAMED("hardware_interface", "Loaded kuka_rsi_hardware_interface");
}
KukaHardwareInterface::~KukaHardwareInterface()
{
}
bool KukaHardwareInterface::read(const ros::Time time, const ros::Duration period)
{
in_buffer_.resize(1024);
if (server_->recv(in_buffer_) == 0)
{
return false;
}
if (rt_rsi_pub_->trylock()){
rt_rsi_pub_->msg_.data = in_buffer_;
rt_rsi_pub_->unlockAndPublish();
}
rsi_state_ = RSIState(in_buffer_);
for (std::size_t i = 0; i < n_dof_; ++i)
{
joint_position_[i] = DEG2RAD * rsi_state_.positions[i];
}
ipoc_ = rsi_state_.ipoc;
return true;
}
bool KukaHardwareInterface::write(const ros::Time time, const ros::Duration period)
{
out_buffer_.resize(1024);
for (std::size_t i = 0; i < n_dof_; ++i)
{
rsi_joint_position_corrections_[i] = (RAD2DEG * joint_position_command_[i]) - rsi_initial_joint_positions_[i];
}
out_buffer_ = RSICommand(rsi_joint_position_corrections_, ipoc_).xml_doc;
server_->send(out_buffer_);
return true;
}
void KukaHardwareInterface::start()
{
// Wait for connection from robot
server_.reset(new UDPServer(local_host_, local_port_));
ROS_INFO_STREAM_NAMED("kuka_hardware_interface", "Waiting for robot!");
int bytes = server_->recv(in_buffer_);
rsi_state_ = RSIState(in_buffer_);
for (std::size_t i = 0; i < n_dof_; ++i)
{
joint_position_[i] = DEG2RAD * rsi_state_.positions[i];
joint_position_command_[i] = joint_position_[i];
rsi_initial_joint_positions_[i] = rsi_state_.initial_positions[i];
}
ipoc_ = rsi_state_.ipoc;
out_buffer_ = RSICommand(rsi_joint_position_corrections_, ipoc_).xml_doc;
server_->send(out_buffer_);
// Set receive timeout to 1 second
server_->set_timeout(1000);
ROS_INFO_STREAM_NAMED("kuka_hardware_interface", "Got connection from robot");
}
void KukaHardwareInterface::configure()
{
if (nh_.getParam("rsi/address", local_host_) && nh_.getParam("rsi/port", local_port_))
{
ROS_INFO_STREAM_NAMED("kuka_hardware_interface",
"Setting up RSI server on: (" << local_host_ << ", " << local_port_ << ")");
}
else
{
ROS_ERROR("Failed to get RSI address or port from parameter server!");
throw std::runtime_error("Failed to get RSI address or port from parameter server.");
}
rt_rsi_pub_.reset(new realtime_tools::RealtimePublisher<std_msgs::String>(nh_, "rsi_xml_doc", 3));
}
} // namespace kuka_rsi_hardware_interface
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, 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 "config.h"
#include "statemachine_mcbp.h"
#include "protocol/mcbp/engine_wrapper.h"
#include "memcached.h"
#include "mcbp.h"
#include "mcbp_executors.h"
#include "connections.h"
#include "sasl_tasks.h"
#include "runtime.h"
#include "mcaudit.h"
void McbpStateMachine::setCurrentTask(McbpConnection& connection, TaskFunction task) {
// Moving to the same state is legal
if (task == currentTask) {
return;
}
if (connection.isDCP()) {
/*
* DCP connections behaves differently than normal
* connections because they operate in a full duplex mode.
* New messages may appear from both sides, so we can't block on
* read from the network / engine
*/
if (task == conn_waiting) {
connection.setCurrentEvent(EV_WRITE);
task = conn_ship_log;
}
if (task == conn_read_packet_header) {
// If we're starting to read data, reset any running timers
connection.setStart(0);
}
}
if (settings.getVerbose() > 2 || task == conn_closing) {
LOG_DETAIL(this,
"%u: going from %s to %s\n",
connection.getId(),
getTaskName(currentTask),
getTaskName(task));
}
if (task == conn_send_data) {
if (connection.getStart() != 0) {
mcbp_collect_timings(&connection);
connection.setStart(0);
}
MEMCACHED_PROCESS_COMMAND_END(connection.getId(),
connection.write.buf,
connection.write.bytes);
}
currentTask = task;
}
const char* McbpStateMachine::getTaskName(TaskFunction task) const {
if (task == conn_new_cmd) {
return "conn_new_cmd";
} else if (task == conn_waiting) {
return "conn_waiting";
} else if (task == conn_read_packet_header) {
return "conn_read_packet_header";
} else if (task == conn_parse_cmd) {
return "conn_parse_cmd";
} else if (task == conn_read_packet_body) {
return "conn_read_packet_body";
} else if (task == conn_execute) {
return "conn_execute";
} else if (task == conn_closing) {
return "conn_closing";
} else if (task == conn_send_data) {
return "conn_send_data";
} else if (task == conn_ship_log) {
return "conn_ship_log";
} else if (task == conn_pending_close) {
return "conn_pending_close";
} else if (task == conn_immediate_close) {
return "conn_immediate_close";
} else if (task == conn_destroyed) {
return "conn_destroyed";
} else {
throw std::invalid_argument(
"McbpStateMachine::getTaskName: Unknown task");
}
}
static void reset_cmd_handler(McbpConnection *c) {
c->setCmd(-1);
c->getCookieObject().reset();
c->resetCommandContext();
if (c->read.bytes == 0) {
/* Make the whole read buffer available. */
c->read.curr = c->read.buf;
}
c->shrinkBuffers();
if (c->read.bytes >= sizeof(c->binary_header)) {
c->setState(conn_parse_cmd);
} else {
c->setState(conn_waiting);
}
}
/**
* Ship tap log to the other end. This state differs with all other states
* in the way that it support full duplex dialog. We're listening to both read
* and write events from libevent most of the time. If a read event occurs we
* switch to the conn_read state to read and execute the input message (that would
* be an ack message from the other side). If a write event occurs we continue to
* send tap log to the other end.
* @param c the tap connection to drive
* @return true if we should continue to process work for this connection, false
* if we should start processing events for other connections.
*/
bool conn_ship_log(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
bool cont = false;
short mask = EV_READ | EV_PERSIST | EV_WRITE;
if (c->isSocketClosed()) {
return false;
}
if (c->isReadEvent() || c->read.bytes > 0) {
if (c->read.bytes >= sizeof(c->binary_header)) {
try_read_mcbp_command(c);
} else {
c->setState(conn_read_packet_header);
}
/* we're going to process something.. let's proceed */
cont = true;
/* We have a finite number of messages in the input queue */
/* so let's process all of them instead of backing off after */
/* reading a subset of them. */
/* Why? Because we've got every time we're calling ship_tap_log */
/* we try to send a chunk of items.. This means that if we end */
/* up in a situation where we're receiving a burst of nack messages */
/* we'll only process a subset of messages in our input queue, */
/* and it will slowly grow.. */
c->setNumEvents(c->getMaxReqsPerEvent());
} else if (c->isWriteEvent()) {
if (c->decrementNumEvents() >= 0) {
c->setEwouldblock(false);
ship_mcbp_dcp_log(c);
if (c->isEwouldblock()) {
mask = EV_READ | EV_PERSIST;
} else {
cont = true;
}
}
}
if (!c->updateEvent(mask)) {
LOG_WARNING(c, "%u: conn_ship_log - Unable to update libevent "
"settings, closing connection (%p) %s", c->getId(),
c->getCookie(), c->getDescription().c_str());
c->setState(conn_closing);
}
return cont;
}
bool conn_waiting(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
if (!c->updateEvent(EV_READ | EV_PERSIST)) {
LOG_WARNING(c, "%u: conn_waiting - Unable to update libevent "
"settings with (EV_READ | EV_PERSIST), closing connection "
"(%p) %s",
c->getId(), c->getCookie(), c->getDescription().c_str());
c->setState(conn_closing);
return true;
}
c->setState(conn_read_packet_header);
return false;
}
bool conn_read_packet_header(McbpConnection* c) {
if (is_bucket_dying(c)) {
return true;
}
switch (c->tryReadNetwork()) {
case McbpConnection::TryReadResult::NoDataReceived:
if (settings.isExitOnConnectionClose()) {
// No more data, proceed to close which will exit the process
c->setState(conn_closing);
} else {
c->setState(conn_waiting);
}
break;
case McbpConnection::TryReadResult::DataReceived:
if (c->read.bytes >= sizeof(c->binary_header)) {
c->setState(conn_parse_cmd);
} else {
c->setState(conn_waiting);
}
break;
case McbpConnection::TryReadResult::SocketClosed:
case McbpConnection::TryReadResult::SocketError:
c->setState(conn_closing);
break;
case McbpConnection::TryReadResult::MemoryError: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
return true;
}
bool conn_parse_cmd(McbpConnection *c) {
try_read_mcbp_command(c);
return !c->isEwouldblock();
}
bool conn_new_cmd(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
c->setStart(0);
/*
* In order to ensure that all clients will be served each
* connection will only process a certain number of operations
* before they will back off.
*/
if (c->decrementNumEvents() >= 0) {
reset_cmd_handler(c);
} else {
get_thread_stats(c)->conn_yields++;
/*
* If we've got data in the input buffer we might get "stuck"
* if we're waiting for a read event. Why? because we might
* already have all of the data for the next command in the
* userspace buffer so the client is idle waiting for the
* response to arrive. Lets set up a _write_ notification,
* since that'll most likely be true really soon.
*
* DCP and TAP connections is different from normal
* connections in the way that they may not even get data from
* the other end so that they'll _have_ to wait for a write event.
*/
if (c->havePendingInputData() || c->isDCP()) {
short flags = EV_WRITE | EV_PERSIST;
// pipe requires EV_READ forcing to ensure we can read until EOF
if (c->isPipeConnection()) {
flags |= EV_READ;
}
if (!c->updateEvent(flags)) {
LOG_WARNING(c, "%u: conn_new_cmd - Unable to update "
"libevent settings, closing connection (%p) %s",
c->getId(), c->getCookie(),
c->getDescription().c_str());
c->setState(conn_closing);
return true;
}
}
return false;
}
return true;
}
bool conn_execute(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
if (c->getRlbytes() != 0) {
throw std::logic_error("conn_execute: Expecting more data (" +
std::to_string(c->getRlbytes()) + ")");
}
c->setEwouldblock(false);
bool block = false;
mcbp_complete_packet(c);
if (c->isEwouldblock()) {
c->unregisterEvent();
block = true;
}
return !block;
}
bool conn_read_packet_body(McbpConnection* c) {
if (is_bucket_dying(c)) {
return true;
}
if (c->getRlbytes() == 0) {
c->setState(conn_execute);
return true;
}
/* first check if we have the bytes present in our input buffer */
if (c->read.bytes > 0) {
auto tocopy = std::min(c->getRlbytes(), c->read.bytes);
c->setRlbytes(c->getRlbytes() - tocopy);
c->read.curr += tocopy;
c->read.bytes -= tocopy;
if (c->getRlbytes() == 0) {
// We've got all we need... go execute the command
c->setState(conn_execute);
return true;
}
}
/* now try reading from the socket */
auto res = c->recv(c->read.curr, c->getRlbytes());
auto error = GetLastNetworkError();
if (res > 0) {
get_thread_stats(c)->bytes_read += res;
c->read.curr += res;
c->setRlbytes(c->getRlbytes() - res);
return true;
}
if (res == 0) { /* end of stream */
c->setState(conn_closing);
return true;
}
if (res == -1 && is_blocking(error)) {
if (!c->updateEvent(EV_READ | EV_PERSIST)) {
LOG_WARNING(c,
"%u: conn_read_packet_body - Unable to update libevent "
"settings with (EV_READ | EV_PERSIST), closing "
"connection (%p) %s",
c->getId(),
c->getCookie(),
c->getDescription().c_str());
c->setState(conn_closing);
return true;
}
return false;
}
/* otherwise we have a real error, on which we close the connection */
if (!is_closed_conn(error)) {
LOG_WARNING(c,
"%u Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
c->getId(), errno, strerror(errno),
(long)c->read.curr, (long)c->read.buf,
(int)c->getRlbytes(), (int)c->read.size);
}
c->setState(conn_closing);
return true;
}
bool conn_send_data(McbpConnection* c) {
bool ret = true;
switch (c->transmit()) {
case McbpConnection::TransmitResult::Complete:
// Release all allocated resources
c->releaseTempAlloc();
c->releaseReservedItems();
// We're done sending the response to the client. Enter the next
// state in the state machine
c->setState(c->getWriteAndGo());
break;
case McbpConnection::TransmitResult::Incomplete:
LOG_INFO(c, "%d - Incomplete transfer. Will retry", c->getId());
break;
case McbpConnection::TransmitResult::HardError:
LOG_NOTICE(c, "%d - Hard error, closing connection", c->getId());
break;
case McbpConnection::TransmitResult::SoftError:
ret = false;
break;
}
if (is_bucket_dying(c)) {
return true;
}
return ret;
}
bool conn_pending_close(McbpConnection *c) {
if (!c->isSocketClosed()) {
throw std::logic_error("conn_pending_close: socketDescriptor must be closed");
}
LOG_DEBUG(c,
"Awaiting clients to release the cookie (pending close for %p)",
(void*)c);
/*
* tell the tap connection that we're disconnecting it now,
* but give it a grace period
*/
perform_callbacks(ON_DISCONNECT, NULL, c->getCookie());
if (c->getRefcount() > 1) {
return false;
}
c->setState(conn_immediate_close);
return true;
}
bool conn_immediate_close(McbpConnection *c) {
ListeningPort *port_instance;
if (!c->isSocketClosed()) {
throw std::logic_error("conn_immediate_close: socketDescriptor must be closed");
}
LOG_DETAIL(c, "Releasing connection %p", c);
{
std::lock_guard<std::mutex> guard(stats_mutex);
port_instance = get_listening_port_instance(c->getParentPort());
if (port_instance) {
--port_instance->curr_conns;
} else if(!c->isPipeConnection()) {
throw std::logic_error("null port_instance and connection "
"is not a pipe");
}
}
perform_callbacks(ON_DISCONNECT, NULL, c->getCookie());
disassociate_bucket(c);
conn_close(c);
return false;
}
bool conn_closing(McbpConnection *c) {
// Delete any attached command context
c->resetCommandContext();
/* We don't want any network notifications anymore.. */
c->unregisterEvent();
safe_close(c->getSocketDescriptor());
c->setSocketDescriptor(INVALID_SOCKET);
/* engine::release any allocated state */
conn_cleanup_engine_allocations(c);
if (c->getRefcount() > 1 || c->isEwouldblock()) {
c->setState(conn_pending_close);
} else {
c->setState(conn_immediate_close);
}
return true;
}
/** sentinal state used to represent a 'destroyed' connection which will
* actually be freed at the end of the event loop. Always returns false.
*/
bool conn_destroyed(McbpConnection*) {
return false;
}
<commit_msg>MB-20940: [33/n] Tap Removal - Remove TAP references from statemachine_mcbp<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, 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 "config.h"
#include "statemachine_mcbp.h"
#include "protocol/mcbp/engine_wrapper.h"
#include "memcached.h"
#include "mcbp.h"
#include "mcbp_executors.h"
#include "connections.h"
#include "sasl_tasks.h"
#include "runtime.h"
#include "mcaudit.h"
void McbpStateMachine::setCurrentTask(McbpConnection& connection, TaskFunction task) {
// Moving to the same state is legal
if (task == currentTask) {
return;
}
if (connection.isDCP()) {
/*
* DCP connections behaves differently than normal
* connections because they operate in a full duplex mode.
* New messages may appear from both sides, so we can't block on
* read from the network / engine
*/
if (task == conn_waiting) {
connection.setCurrentEvent(EV_WRITE);
task = conn_ship_log;
}
if (task == conn_read_packet_header) {
// If we're starting to read data, reset any running timers
connection.setStart(0);
}
}
if (settings.getVerbose() > 2 || task == conn_closing) {
LOG_DETAIL(this,
"%u: going from %s to %s\n",
connection.getId(),
getTaskName(currentTask),
getTaskName(task));
}
if (task == conn_send_data) {
if (connection.getStart() != 0) {
mcbp_collect_timings(&connection);
connection.setStart(0);
}
MEMCACHED_PROCESS_COMMAND_END(connection.getId(),
connection.write.buf,
connection.write.bytes);
}
currentTask = task;
}
const char* McbpStateMachine::getTaskName(TaskFunction task) const {
if (task == conn_new_cmd) {
return "conn_new_cmd";
} else if (task == conn_waiting) {
return "conn_waiting";
} else if (task == conn_read_packet_header) {
return "conn_read_packet_header";
} else if (task == conn_parse_cmd) {
return "conn_parse_cmd";
} else if (task == conn_read_packet_body) {
return "conn_read_packet_body";
} else if (task == conn_execute) {
return "conn_execute";
} else if (task == conn_closing) {
return "conn_closing";
} else if (task == conn_send_data) {
return "conn_send_data";
} else if (task == conn_ship_log) {
return "conn_ship_log";
} else if (task == conn_pending_close) {
return "conn_pending_close";
} else if (task == conn_immediate_close) {
return "conn_immediate_close";
} else if (task == conn_destroyed) {
return "conn_destroyed";
} else {
throw std::invalid_argument(
"McbpStateMachine::getTaskName: Unknown task");
}
}
static void reset_cmd_handler(McbpConnection *c) {
c->setCmd(-1);
c->getCookieObject().reset();
c->resetCommandContext();
if (c->read.bytes == 0) {
/* Make the whole read buffer available. */
c->read.curr = c->read.buf;
}
c->shrinkBuffers();
if (c->read.bytes >= sizeof(c->binary_header)) {
c->setState(conn_parse_cmd);
} else {
c->setState(conn_waiting);
}
}
/**
* Ship DCP log to the other end. This state differs with all other states
* in the way that it support full duplex dialog. We're listening to both read
* and write events from libevent most of the time. If a read event occurs we
* switch to the conn_read state to read and execute the input message (that would
* be an ack message from the other side). If a write event occurs we continue to
* send DCP log to the other end.
* @param c the DCP connection to drive
* @return true if we should continue to process work for this connection, false
* if we should start processing events for other connections.
*/
bool conn_ship_log(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
bool cont = false;
short mask = EV_READ | EV_PERSIST | EV_WRITE;
if (c->isSocketClosed()) {
return false;
}
if (c->isReadEvent() || c->read.bytes > 0) {
if (c->read.bytes >= sizeof(c->binary_header)) {
try_read_mcbp_command(c);
} else {
c->setState(conn_read_packet_header);
}
/* we're going to process something.. let's proceed */
cont = true;
/* We have a finite number of messages in the input queue */
/* so let's process all of them instead of backing off after */
/* reading a subset of them. */
/* Why? Because we've got every time we're calling ship_mcbp_dcp_log */
/* we try to send a chunk of items.. This means that if we end */
/* up in a situation where we're receiving a burst of nack messages */
/* we'll only process a subset of messages in our input queue, */
/* and it will slowly grow.. */
c->setNumEvents(c->getMaxReqsPerEvent());
} else if (c->isWriteEvent()) {
if (c->decrementNumEvents() >= 0) {
c->setEwouldblock(false);
ship_mcbp_dcp_log(c);
if (c->isEwouldblock()) {
mask = EV_READ | EV_PERSIST;
} else {
cont = true;
}
}
}
if (!c->updateEvent(mask)) {
LOG_WARNING(c, "%u: conn_ship_log - Unable to update libevent "
"settings, closing connection (%p) %s", c->getId(),
c->getCookie(), c->getDescription().c_str());
c->setState(conn_closing);
}
return cont;
}
bool conn_waiting(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
if (!c->updateEvent(EV_READ | EV_PERSIST)) {
LOG_WARNING(c, "%u: conn_waiting - Unable to update libevent "
"settings with (EV_READ | EV_PERSIST), closing connection "
"(%p) %s",
c->getId(), c->getCookie(), c->getDescription().c_str());
c->setState(conn_closing);
return true;
}
c->setState(conn_read_packet_header);
return false;
}
bool conn_read_packet_header(McbpConnection* c) {
if (is_bucket_dying(c)) {
return true;
}
switch (c->tryReadNetwork()) {
case McbpConnection::TryReadResult::NoDataReceived:
if (settings.isExitOnConnectionClose()) {
// No more data, proceed to close which will exit the process
c->setState(conn_closing);
} else {
c->setState(conn_waiting);
}
break;
case McbpConnection::TryReadResult::DataReceived:
if (c->read.bytes >= sizeof(c->binary_header)) {
c->setState(conn_parse_cmd);
} else {
c->setState(conn_waiting);
}
break;
case McbpConnection::TryReadResult::SocketClosed:
case McbpConnection::TryReadResult::SocketError:
c->setState(conn_closing);
break;
case McbpConnection::TryReadResult::MemoryError: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
return true;
}
bool conn_parse_cmd(McbpConnection *c) {
try_read_mcbp_command(c);
return !c->isEwouldblock();
}
bool conn_new_cmd(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
c->setStart(0);
/*
* In order to ensure that all clients will be served each
* connection will only process a certain number of operations
* before they will back off.
*/
if (c->decrementNumEvents() >= 0) {
reset_cmd_handler(c);
} else {
get_thread_stats(c)->conn_yields++;
/*
* If we've got data in the input buffer we might get "stuck"
* if we're waiting for a read event. Why? because we might
* already have all of the data for the next command in the
* userspace buffer so the client is idle waiting for the
* response to arrive. Lets set up a _write_ notification,
* since that'll most likely be true really soon.
*
* DCP connections are different from normal
* connections in the way that they may not even get data from
* the other end so that they'll _have_ to wait for a write event.
*/
if (c->havePendingInputData() || c->isDCP()) {
short flags = EV_WRITE | EV_PERSIST;
// pipe requires EV_READ forcing to ensure we can read until EOF
if (c->isPipeConnection()) {
flags |= EV_READ;
}
if (!c->updateEvent(flags)) {
LOG_WARNING(c, "%u: conn_new_cmd - Unable to update "
"libevent settings, closing connection (%p) %s",
c->getId(), c->getCookie(),
c->getDescription().c_str());
c->setState(conn_closing);
return true;
}
}
return false;
}
return true;
}
bool conn_execute(McbpConnection *c) {
if (is_bucket_dying(c)) {
return true;
}
if (c->getRlbytes() != 0) {
throw std::logic_error("conn_execute: Expecting more data (" +
std::to_string(c->getRlbytes()) + ")");
}
c->setEwouldblock(false);
bool block = false;
mcbp_complete_packet(c);
if (c->isEwouldblock()) {
c->unregisterEvent();
block = true;
}
return !block;
}
bool conn_read_packet_body(McbpConnection* c) {
if (is_bucket_dying(c)) {
return true;
}
if (c->getRlbytes() == 0) {
c->setState(conn_execute);
return true;
}
/* first check if we have the bytes present in our input buffer */
if (c->read.bytes > 0) {
auto tocopy = std::min(c->getRlbytes(), c->read.bytes);
c->setRlbytes(c->getRlbytes() - tocopy);
c->read.curr += tocopy;
c->read.bytes -= tocopy;
if (c->getRlbytes() == 0) {
// We've got all we need... go execute the command
c->setState(conn_execute);
return true;
}
}
/* now try reading from the socket */
auto res = c->recv(c->read.curr, c->getRlbytes());
auto error = GetLastNetworkError();
if (res > 0) {
get_thread_stats(c)->bytes_read += res;
c->read.curr += res;
c->setRlbytes(c->getRlbytes() - res);
return true;
}
if (res == 0) { /* end of stream */
c->setState(conn_closing);
return true;
}
if (res == -1 && is_blocking(error)) {
if (!c->updateEvent(EV_READ | EV_PERSIST)) {
LOG_WARNING(c,
"%u: conn_read_packet_body - Unable to update libevent "
"settings with (EV_READ | EV_PERSIST), closing "
"connection (%p) %s",
c->getId(),
c->getCookie(),
c->getDescription().c_str());
c->setState(conn_closing);
return true;
}
return false;
}
/* otherwise we have a real error, on which we close the connection */
if (!is_closed_conn(error)) {
LOG_WARNING(c,
"%u Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
c->getId(), errno, strerror(errno),
(long)c->read.curr, (long)c->read.buf,
(int)c->getRlbytes(), (int)c->read.size);
}
c->setState(conn_closing);
return true;
}
bool conn_send_data(McbpConnection* c) {
bool ret = true;
switch (c->transmit()) {
case McbpConnection::TransmitResult::Complete:
// Release all allocated resources
c->releaseTempAlloc();
c->releaseReservedItems();
// We're done sending the response to the client. Enter the next
// state in the state machine
c->setState(c->getWriteAndGo());
break;
case McbpConnection::TransmitResult::Incomplete:
LOG_INFO(c, "%d - Incomplete transfer. Will retry", c->getId());
break;
case McbpConnection::TransmitResult::HardError:
LOG_NOTICE(c, "%d - Hard error, closing connection", c->getId());
break;
case McbpConnection::TransmitResult::SoftError:
ret = false;
break;
}
if (is_bucket_dying(c)) {
return true;
}
return ret;
}
bool conn_pending_close(McbpConnection *c) {
if (!c->isSocketClosed()) {
throw std::logic_error("conn_pending_close: socketDescriptor must be closed");
}
LOG_DEBUG(c,
"Awaiting clients to release the cookie (pending close for %p)",
(void*)c);
/*
* tell the DCP connection that we're disconnecting it now,
* but give it a grace period
*/
perform_callbacks(ON_DISCONNECT, NULL, c->getCookie());
if (c->getRefcount() > 1) {
return false;
}
c->setState(conn_immediate_close);
return true;
}
bool conn_immediate_close(McbpConnection *c) {
ListeningPort *port_instance;
if (!c->isSocketClosed()) {
throw std::logic_error("conn_immediate_close: socketDescriptor must be closed");
}
LOG_DETAIL(c, "Releasing connection %p", c);
{
std::lock_guard<std::mutex> guard(stats_mutex);
port_instance = get_listening_port_instance(c->getParentPort());
if (port_instance) {
--port_instance->curr_conns;
} else if(!c->isPipeConnection()) {
throw std::logic_error("null port_instance and connection "
"is not a pipe");
}
}
perform_callbacks(ON_DISCONNECT, NULL, c->getCookie());
disassociate_bucket(c);
conn_close(c);
return false;
}
bool conn_closing(McbpConnection *c) {
// Delete any attached command context
c->resetCommandContext();
/* We don't want any network notifications anymore.. */
c->unregisterEvent();
safe_close(c->getSocketDescriptor());
c->setSocketDescriptor(INVALID_SOCKET);
/* engine::release any allocated state */
conn_cleanup_engine_allocations(c);
if (c->getRefcount() > 1 || c->isEwouldblock()) {
c->setState(conn_pending_close);
} else {
c->setState(conn_immediate_close);
}
return true;
}
/** sentinal state used to represent a 'destroyed' connection which will
* actually be freed at the end of the event loop. Always returns false.
*/
bool conn_destroyed(McbpConnection*) {
return false;
}
<|endoftext|> |
<commit_before>#include <thread>
#include <future>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "ProcFd.h"
#include "ProcNet.h"
#include "InodeIpHelper.h"
#include "ProcNetPublisher.h"
#include "ProcReadTimer.h"
using namespace std;
using namespace boost;
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string& pid);
ProcNetPublisher* procNetPublisher;
ProcReadTimer::ProcReadTimer() {
procNetPublisher = this;
}
void ProcReadTimer::start(const char *pid) {
thread procReadThread([](const char* processId) {
asio::io_service io;
asio::deadline_timer timer(io, posix_time::milliseconds(0));
timer.async_wait(bind(procRead, asio::placeholders::error, &timer, processId));
io.run();
}, pid);
procReadThread.detach();
}
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string& pid) {
ProcFd procFd(pid);
auto socketsInodeFuture = async(&ProcFd::getSocketInodeList, &procFd);
ProcNet procNetTcp("tcp");
auto tcpInodeIpFuture = async(&ProcNet::getInodesIpMap, &procNetTcp);
ProcNet procNetUdp("udp");
auto udpInodeIpFuture = async(&ProcNet::getInodesIpMap, &procNetUdp);
auto socketsInode = socketsInodeFuture.get();
auto tcpInodeIp = tcpInodeIpFuture.get();
auto udpInodeIp = udpInodeIpFuture.get();
auto tcpNetDataFuture = async(&InodeIpHelper::filterProccessIp, socketsInode, tcpInodeIp);
auto udpNetDataFuture = async(&InodeIpHelper::filterProccessIp, socketsInode, udpInodeIp);
auto tcpNetData = tcpNetDataFuture.get();
auto udpNetData = udpNetDataFuture.get();
procNetPublisher->setNetData(tcpNetData, udpNetData);
procNetPublisher->notifyObservers();
timer->expires_at(timer->expires_at() + posix_time::milliseconds(500));
timer->async_wait(bind(procRead, asio::placeholders::error, timer, pid));
}<commit_msg>Set asynchronous policy for std::async<commit_after>#include <thread>
#include <future>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "ProcFd.h"
#include "ProcNet.h"
#include "InodeIpHelper.h"
#include "ProcNetPublisher.h"
#include "ProcReadTimer.h"
using namespace std;
using namespace boost;
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string& pid);
ProcNetPublisher* procNetPublisher;
ProcReadTimer::ProcReadTimer() {
procNetPublisher = this;
}
void ProcReadTimer::start(const char *pid) {
thread procReadThread([](const char* processId) {
asio::io_service io;
asio::deadline_timer timer(io, posix_time::milliseconds(0));
timer.async_wait(bind(procRead, asio::placeholders::error, &timer, processId));
io.run();
}, pid);
procReadThread.detach();
}
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string& pid) {
ProcFd procFd(pid);
auto socketsInodeFuture = async(launch::async, &ProcFd::getSocketInodeList, &procFd);
ProcNet procNetTcp("tcp");
auto tcpInodeIpFuture = async(launch::async, &ProcNet::getInodesIpMap, &procNetTcp);
ProcNet procNetUdp("udp");
auto udpInodeIpFuture = async(launch::async, &ProcNet::getInodesIpMap, &procNetUdp);
auto socketsInode = socketsInodeFuture.get();
auto tcpInodeIp = tcpInodeIpFuture.get();
auto udpInodeIp = udpInodeIpFuture.get();
auto tcpNetDataFuture = async(launch::async, &InodeIpHelper::filterProccessIp, socketsInode, tcpInodeIp);
auto udpNetDataFuture = async(launch::async, &InodeIpHelper::filterProccessIp, socketsInode, udpInodeIp);
auto tcpNetData = tcpNetDataFuture.get();
auto udpNetData = udpNetDataFuture.get();
procNetPublisher->setNetData(tcpNetData, udpNetData);
procNetPublisher->notifyObservers();
timer->expires_at(timer->expires_at() + posix_time::milliseconds(500));
timer->async_wait(bind(procRead, asio::placeholders::error, timer, pid));
}<|endoftext|> |
<commit_before>#ifndef __STORE_HPP__
#define __STORE_HPP__
#include "utils.hpp"
#include "arch/arch.hpp"
#include "data_provider.hpp"
#include "concurrency/cond_var.hpp"
#include "containers/iterators.hpp"
#include "containers/unique_ptr.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
typedef uint32_t mcflags_t;
typedef uint32_t exptime_t;
typedef uint64_t cas_t;
struct store_key_t {
uint8_t size;
char contents[MAX_KEY_SIZE];
store_key_t() { }
store_key_t(int sz, const char *buf) {
assign(sz, buf);
}
void assign(int sz, const char *buf) {
rassert(sz <= MAX_KEY_SIZE);
size = sz;
memcpy(contents, buf, sz);
}
void print() const {
printf("%*.*s", size, size, contents);
}
};
inline bool str_to_key(const char *str, store_key_t *buf) {
int len = strlen(str);
if (len <= MAX_KEY_SIZE) {
memcpy(buf->contents, str, len);
buf->size = (uint8_t) len;
return true;
} else {
return false;
}
}
inline std::string key_to_str(const store_key_t &key) {
return std::string(key.contents, key.size);
}
enum rget_bound_mode_t {
rget_bound_open, // Don't include boundary key
rget_bound_closed, // Include boundary key
rget_bound_none // Ignore boundary key and go all the way to the left/right side of the tree
};
struct key_with_data_provider_t {
std::string key;
mcflags_t mcflags;
boost::shared_ptr<data_provider_t> value_provider;
key_with_data_provider_t(const std::string &key, mcflags_t mcflags, boost::shared_ptr<data_provider_t> value_provider) :
key(key), mcflags(mcflags), value_provider(value_provider) { }
struct less {
bool operator()(const key_with_data_provider_t &pair1, const key_with_data_provider_t &pair2) {
return pair1.key < pair2.key;
}
};
};
// A NULL unique pointer means not allowed
typedef unique_ptr_t<one_way_iterator_t<key_with_data_provider_t> > rget_result_t;
struct get_result_t {
get_result_t(unique_ptr_t<data_provider_t> v, mcflags_t f, cas_t c) :
is_not_allowed(false), value(v), flags(f), cas(c) { }
get_result_t() :
is_not_allowed(false), value(), flags(0), cas(0) { }
/* If true, then all other fields should be ignored. */
bool is_not_allowed;
// NULL means not found. Parts of the store may wait for the data_provider_t's destructor,
// so don't hold on to it forever.
unique_ptr_t<data_provider_t> value;
mcflags_t flags;
cas_t cas;
};
struct get_store_t {
virtual get_result_t get(const store_key_t &key) = 0;
virtual rget_result_t rget(rget_bound_mode_t left_mode, const store_key_t &left_key,
rget_bound_mode_t right_mode, const store_key_t &right_key) = 0;
virtual ~get_store_t() {}
};
// A castime_t contains proposed cas information (if it's needed) and
// timestamp information. By deciding these now and passing them in
// at the top, the precise same information gets sent to the replicas.
struct castime_t {
cas_t proposed_cas;
repli_timestamp timestamp;
castime_t(cas_t proposed_cas_, repli_timestamp timestamp_)
: proposed_cas(proposed_cas_), timestamp(timestamp_) { }
// TODO: ugh.
castime_t() { }
};
/* get_cas is a mutation instead of another method on get_store_t because it may need to
put a CAS-unique on a key that didn't have one before */
struct get_cas_mutation_t {
store_key_t key;
};
enum add_policy_t {
add_policy_yes,
add_policy_no
};
enum replace_policy_t {
replace_policy_yes,
replace_policy_if_cas_matches,
replace_policy_no
};
#define NO_CAS_SUPPLIED 0
struct sarc_mutation_t {
store_key_t key;
unique_ptr_t<data_provider_t> data;
mcflags_t flags;
exptime_t exptime;
add_policy_t add_policy;
replace_policy_t replace_policy;
cas_t old_cas;
};
enum set_result_t {
/* Returned on success */
sr_stored,
/* Returned if add_policy is add_policy_no and the key is absent */
sr_didnt_add,
/* Returned if replace_policy is replace_policy_no and the key is present or replace_policy
is replace_policy_if_cas_matches and the CAS does not match */
sr_didnt_replace,
/* Returned if the value to be stored is too big */
sr_too_large,
/* Returned if the data_provider_t that you gave returned have_failed(). */
sr_data_provider_failed,
/* Returned if the store doesn't want you to do what you're doing. */
sr_not_allowed,
};
struct delete_mutation_t {
store_key_t key;
};
enum delete_result_t {
dr_deleted,
dr_not_found,
dr_not_allowed
};
enum incr_decr_kind_t {
incr_decr_INCR,
incr_decr_DECR
};
struct incr_decr_mutation_t {
incr_decr_kind_t kind;
store_key_t key;
uint64_t amount;
};
struct incr_decr_result_t {
enum result_t {
idr_success,
idr_not_found,
idr_not_numeric,
idr_not_allowed,
} res;
uint64_t new_value; // Valid only if idr_success
incr_decr_result_t() { }
incr_decr_result_t(result_t r, uint64_t n = 0) : res(r), new_value(n) { }
};
enum append_prepend_kind_t { append_prepend_APPEND, append_prepend_PREPEND };
struct append_prepend_mutation_t {
append_prepend_kind_t kind;
store_key_t key;
unique_ptr_t<data_provider_t> data;
};
enum append_prepend_result_t {
apr_success,
apr_too_large,
apr_not_found,
apr_data_provider_failed,
apr_not_allowed,
};
struct mutation_t {
boost::variant<get_cas_mutation_t, sarc_mutation_t, delete_mutation_t, incr_decr_mutation_t, append_prepend_mutation_t> mutation;
// implicit
template<class T>
mutation_t(const T &m) : mutation(m) { }
/* get_key() extracts the "key" field from whichever sub-mutation we actually are */
store_key_t get_key() const;
};
struct mutation_result_t {
boost::variant<get_result_t, set_result_t, delete_result_t, incr_decr_result_t, append_prepend_result_t> result;
// implicit
template<class T>
mutation_result_t(const T &r) : result(r) { }
};
class set_store_interface_t {
public:
/* These NON-VIRTUAL methods all construct a mutation_t and then call change(). */
get_result_t get_cas(const store_key_t &key);
set_result_t sarc(const store_key_t &key, unique_ptr_t<data_provider_t> data, mcflags_t flags, exptime_t exptime, add_policy_t add_policy, replace_policy_t replace_policy, cas_t old_cas);
incr_decr_result_t incr_decr(incr_decr_kind_t kind, const store_key_t &key, uint64_t amount);
append_prepend_result_t append_prepend(append_prepend_kind_t kind, const store_key_t &key, unique_ptr_t<data_provider_t> data);
delete_result_t delete_key(const store_key_t &key);
virtual mutation_result_t change(const mutation_t&) = 0;
virtual ~set_store_interface_t() {}
};
/* set_store_t is different from set_store_interface_t in that it is completely deterministic. If
you have two identical set_store_ts and you send exactly the same data to them, you will put them
into exactly the same state. This is important for keeping replicas in sync.
Usually, all of the changes for a given key must arrive at a set_store_t from the same thread;
otherwise this would defeat the purpose of being deterministic because they would arrive in an
arbitrary order.*/
class set_store_t {
public:
virtual mutation_result_t change(const mutation_t&, castime_t) = 0;
virtual ~set_store_t() {}
};
/* timestamping_store_interface_t timestamps any operations that are given to it and then passes
them on to the underlying store_t. It also linearizes operations; it routes all operations to its
home thread before passing them on, so they happen in a well-defined order. In this way it acts as
a translator between set_store_interface_t and set_store_t. */
class timestamping_set_store_interface_t :
public set_store_interface_t,
public home_thread_mixin_t
{
public:
timestamping_set_store_interface_t(set_store_t *target);
mutation_result_t change(const mutation_t &);
private:
castime_t make_castime();
set_store_t *target;
uint32_t cas_counter;
};
#endif /* __STORE_HPP__ */
<commit_msg>Added some comments in store.hpp.<commit_after>#ifndef __STORE_HPP__
#define __STORE_HPP__
#include "utils.hpp"
#include "arch/arch.hpp"
#include "data_provider.hpp"
#include "concurrency/cond_var.hpp"
#include "containers/iterators.hpp"
#include "containers/unique_ptr.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
typedef uint32_t mcflags_t;
typedef uint32_t exptime_t;
typedef uint64_t cas_t;
struct store_key_t {
uint8_t size;
char contents[MAX_KEY_SIZE];
store_key_t() { }
store_key_t(int sz, const char *buf) {
assign(sz, buf);
}
void assign(int sz, const char *buf) {
rassert(sz <= MAX_KEY_SIZE);
size = sz;
memcpy(contents, buf, sz);
}
void print() const {
printf("%*.*s", size, size, contents);
}
};
inline bool str_to_key(const char *str, store_key_t *buf) {
int len = strlen(str);
if (len <= MAX_KEY_SIZE) {
memcpy(buf->contents, str, len);
buf->size = (uint8_t) len;
return true;
} else {
return false;
}
}
inline std::string key_to_str(const store_key_t &key) {
return std::string(key.contents, key.size);
}
enum rget_bound_mode_t {
rget_bound_open, // Don't include boundary key
rget_bound_closed, // Include boundary key
rget_bound_none // Ignore boundary key and go all the way to the left/right side of the tree
};
struct key_with_data_provider_t {
std::string key;
mcflags_t mcflags;
boost::shared_ptr<data_provider_t> value_provider;
key_with_data_provider_t(const std::string &key, mcflags_t mcflags, boost::shared_ptr<data_provider_t> value_provider) :
key(key), mcflags(mcflags), value_provider(value_provider) { }
struct less {
bool operator()(const key_with_data_provider_t &pair1, const key_with_data_provider_t &pair2) {
return pair1.key < pair2.key;
}
};
};
// A NULL unique pointer means not allowed
typedef unique_ptr_t<one_way_iterator_t<key_with_data_provider_t> > rget_result_t;
struct get_result_t {
get_result_t(unique_ptr_t<data_provider_t> v, mcflags_t f, cas_t c) :
is_not_allowed(false), value(v), flags(f), cas(c) { }
get_result_t() :
is_not_allowed(false), value(), flags(0), cas(0) { }
/* If true, then all other fields should be ignored. */
bool is_not_allowed;
// NULL means not found. Parts of the store may wait for the data_provider_t's destructor,
// so don't hold on to it forever.
unique_ptr_t<data_provider_t> value;
mcflags_t flags;
cas_t cas;
};
struct get_store_t {
virtual get_result_t get(const store_key_t &key) = 0;
virtual rget_result_t rget(rget_bound_mode_t left_mode, const store_key_t &left_key,
rget_bound_mode_t right_mode, const store_key_t &right_key) = 0;
virtual ~get_store_t() {}
};
// A castime_t contains proposed cas information (if it's needed) and
// timestamp information. By deciding these now and passing them in
// at the top, the precise same information gets sent to the replicas.
struct castime_t {
cas_t proposed_cas;
repli_timestamp timestamp;
castime_t(cas_t proposed_cas_, repli_timestamp timestamp_)
: proposed_cas(proposed_cas_), timestamp(timestamp_) { }
// TODO: ugh.
castime_t() { }
};
/* get_cas is a mutation instead of another method on get_store_t because it may need to
put a CAS-unique on a key that didn't have one before */
struct get_cas_mutation_t {
store_key_t key;
};
enum add_policy_t {
add_policy_yes,
add_policy_no
};
enum replace_policy_t {
replace_policy_yes,
replace_policy_if_cas_matches,
replace_policy_no
};
#define NO_CAS_SUPPLIED 0
struct sarc_mutation_t {
/* The key to operate on */
store_key_t key;
/* The value to give the key; must not be NULL.
TODO: Should NULL mean a deletion? */
unique_ptr_t<data_provider_t> data;
/* The flags to store with the value */
mcflags_t flags;
/* When to make the value expire */
exptime_t exptime;
/* If add_policy is add_policy_no and the key doesn't already exist, then the operation
will be cancelled and the return value will be sr_didnt_add */
add_policy_t add_policy;
/* If replace_policy is replace_policy_no and the key already exists, or if
replace_policy is replace_policy_if_cas_matches and the key is either missing a
CAS or has a CAS different from old cas, then the operation will be cancelled and
the return value will be sr_didnt_replace. */
replace_policy_t replace_policy;
cas_t old_cas;
};
enum set_result_t {
/* Returned on success */
sr_stored,
/* Returned if add_policy is add_policy_no and the key is absent */
sr_didnt_add,
/* Returned if replace_policy is replace_policy_no and the key is present or replace_policy
is replace_policy_if_cas_matches and the CAS does not match */
sr_didnt_replace,
/* Returned if the value to be stored is too big */
sr_too_large,
/* Returned if the data_provider_t that you gave returned have_failed(). */
sr_data_provider_failed,
/* Returned if the store doesn't want you to do what you're doing. */
sr_not_allowed,
};
struct delete_mutation_t {
store_key_t key;
};
enum delete_result_t {
dr_deleted,
dr_not_found,
dr_not_allowed
};
enum incr_decr_kind_t {
incr_decr_INCR,
incr_decr_DECR
};
struct incr_decr_mutation_t {
incr_decr_kind_t kind;
store_key_t key;
uint64_t amount;
};
struct incr_decr_result_t {
enum result_t {
idr_success,
idr_not_found,
idr_not_numeric,
idr_not_allowed,
} res;
uint64_t new_value; // Valid only if idr_success
incr_decr_result_t() { }
incr_decr_result_t(result_t r, uint64_t n = 0) : res(r), new_value(n) { }
};
enum append_prepend_kind_t { append_prepend_APPEND, append_prepend_PREPEND };
struct append_prepend_mutation_t {
append_prepend_kind_t kind;
store_key_t key;
unique_ptr_t<data_provider_t> data;
};
enum append_prepend_result_t {
apr_success,
apr_too_large,
apr_not_found,
apr_data_provider_failed,
apr_not_allowed,
};
struct mutation_t {
boost::variant<get_cas_mutation_t, sarc_mutation_t, delete_mutation_t, incr_decr_mutation_t, append_prepend_mutation_t> mutation;
// implicit
template<class T>
mutation_t(const T &m) : mutation(m) { }
/* get_key() extracts the "key" field from whichever sub-mutation we actually are */
store_key_t get_key() const;
};
struct mutation_result_t {
boost::variant<get_result_t, set_result_t, delete_result_t, incr_decr_result_t, append_prepend_result_t> result;
// implicit
template<class T>
mutation_result_t(const T &r) : result(r) { }
};
class set_store_interface_t {
public:
/* These NON-VIRTUAL methods all construct a mutation_t and then call change(). */
get_result_t get_cas(const store_key_t &key);
set_result_t sarc(const store_key_t &key, unique_ptr_t<data_provider_t> data, mcflags_t flags, exptime_t exptime, add_policy_t add_policy, replace_policy_t replace_policy, cas_t old_cas);
incr_decr_result_t incr_decr(incr_decr_kind_t kind, const store_key_t &key, uint64_t amount);
append_prepend_result_t append_prepend(append_prepend_kind_t kind, const store_key_t &key, unique_ptr_t<data_provider_t> data);
delete_result_t delete_key(const store_key_t &key);
virtual mutation_result_t change(const mutation_t&) = 0;
virtual ~set_store_interface_t() {}
};
/* set_store_t is different from set_store_interface_t in that it is completely deterministic. If
you have two identical set_store_ts and you send exactly the same data to them, you will put them
into exactly the same state. This is important for keeping replicas in sync.
Usually, all of the changes for a given key must arrive at a set_store_t from the same thread;
otherwise this would defeat the purpose of being deterministic because they would arrive in an
arbitrary order.*/
class set_store_t {
public:
virtual mutation_result_t change(const mutation_t&, castime_t) = 0;
virtual ~set_store_t() {}
};
/* timestamping_store_interface_t timestamps any operations that are given to it and then passes
them on to the underlying store_t. It also linearizes operations; it routes all operations to its
home thread before passing them on, so they happen in a well-defined order. In this way it acts as
a translator between set_store_interface_t and set_store_t. */
class timestamping_set_store_interface_t :
public set_store_interface_t,
public home_thread_mixin_t
{
public:
timestamping_set_store_interface_t(set_store_t *target);
mutation_result_t change(const mutation_t &);
private:
castime_t make_castime();
set_store_t *target;
uint32_t cas_counter;
};
#endif /* __STORE_HPP__ */
<|endoftext|> |
<commit_before>#include "RobotStateControl.h"
#include "OrientationSensorsWrapper.hpp"
#include "SDLogDriver.hpp"
#include "DualEncoderDriver.hpp"
#include "MotorDriver.h"
#include "TireContactModule.hpp"
#include "FrontLiftedDetection.hpp"
#include "MainLogic.h"
#include "ProximitySensors.hpp"
#include "SerialCommander.h"
#include "planar/PlanarAccelerationModule.hpp"
#include "planar/PlanarSpeedModule.hpp"
#include <Wire.h>
#include <SD.h>
#define SERIAL_BAUD_RATE 115200
#define I2C_FREQUENCY 400000
#define SD_CHIP_SELECT 4
#define LOG_FREQUENCY 100
#define SAMPLE_FREQUENCY 250
#define MICROS_PER_SECOND 1000000
#define LED_PIN 13
#define LEFT_A_PIN 12
#define LEFT_B_PIN 11
#define RIGHT_A_PIN 9
#define RIGHT_B_PIN 10
enum {
WAITING_FOR_COMMAND,
PREPARE_TO_FIGHT,
FIGHT_MODE,
BRAINDEAD,
TEST_MODE
} robot_state = WAITING_FOR_COMMAND;
OrientationSensors position;
DualEncoder leftEncoder(LEFT_A_PIN, LEFT_B_PIN);
DualEncoder rightEncoder(RIGHT_A_PIN, RIGHT_B_PIN);
void setup()
{
Serial.begin(SERIAL_BAUD_RATE);
SD.begin(SD_CHIP_SELECT);
initLogger();
leftEncoder.init([](){leftEncoder.A_handler();}, [](){leftEncoder.B_handler();});
rightEncoder.init([](){rightEncoder.A_handler();}, [](){rightEncoder.B_handler();});
initMotors();
initProximitySensors();
Wire.begin();
Wire.setClock(I2C_FREQUENCY);
position.init();
}
uint32_t event_micros;
void calibrate() {
digitalWrite(LED_PIN, HIGH);
position.calibrate();
initPlanarSpeed(position);
}
void setState(int new_state) {
robot_state = (decltype(robot_state)) new_state;
}
void getProximityCommand()
{
static uint8_t left = 0;
static uint8_t right = 0;
static uint8_t last_left = 0;
static uint8_t last_right = 0;
static int command_counter = 0;
readProximitySensors(left, right);
if(robot_state == WAITING_FOR_COMMAND)
{
if(right)
{
if(left < last_left)
{
++command_counter;
Serial.print("Counter: ");
Serial.println(command_counter);
}
}
else if(right < last_right)
{
if(!left)
{
switch(command_counter)
{
case 0:
robot_state = PREPARE_TO_FIGHT;
event_micros = micros();
break;
case 1:
calibrate();
break;
case 2:
robot_state = TEST_MODE;
Serial.println("Welcome to test mode");
break;
}
}
command_counter = 0;
}
}
else if(left && right)
{
if(robot_state == FIGHT_MODE)
{
robot_state = BRAINDEAD;
}
else
{
robot_state = WAITING_FOR_COMMAND;
command_counter = 42; // Just something invalid and BIG
}
robot_state = WAITING_FOR_COMMAND; // Remove
setMotors(0, 0);
}
last_left = left;
last_right = right;
}
void loop()
{
static uint32_t last_sample_micros = 0;
static uint32_t last_log_micros = 0;
static uint32_t last_blink_micros = 0;
uint32_t current_micros = micros();
{ // blink control
uint32_t full_cycle = MICROS_PER_SECOND;
uint32_t high_cycle = MICROS_PER_SECOND;
switch(robot_state)
{
case BRAINDEAD:
full_cycle *= 2;
high_cycle *= 1;
break;
case PREPARE_TO_FIGHT:
full_cycle /= 10;
high_cycle /= 20;
break;
case FIGHT_MODE:
case TEST_MODE:
full_cycle /= 2;
high_cycle /= 3;
default:
full_cycle /= 2;
high_cycle /= 5;
break;
}
if(current_micros - last_blink_micros >= full_cycle)
{
digitalWrite(LED_PIN, HIGH);
last_blink_micros = current_micros;
}
else if(current_micros - last_blink_micros >= high_cycle)
{
digitalWrite(LED_PIN, LOW);
}
}
switch(robot_state)
{
case BRAINDEAD:
setMotors(0, 0);
return;
case PREPARE_TO_FIGHT:
if(current_micros - event_micros >= MICROS_PER_SECOND * 5)
{
robot_state = FIGHT_MODE;
}
break;
case FIGHT_MODE:
{
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
/*if(getLeftTireContactState() == 0 && getRightTireContactState() == 0)
{
robot_state = BRAINDEAD;
break;
}*/
MainLogic(leftEncoder.getSpeed(), rightEncoder.getSpeed());
}
}
break;
case TEST_MODE:
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
/* PERFORM TESTS */
}
break;
default:
break;
}
// Read sensors
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
position.update();
leftEncoder.update();
rightEncoder.update();
updatePlanarSpeed(position);
getProximityCommand();
last_sample_micros = current_micros;
}
// Log data
if(current_micros - last_log_micros >= MICROS_PER_SECOND / LOG_FREQUENCY)
{
logDataPack(position, leftEncoder, rightEncoder, acceleration_vector, speed_vector);
last_log_micros = current_micros;
}
getSerialCommand();
}
<commit_msg>Fix compile error<commit_after>#include "RobotStateControl.h"
#include "OrientationSensorsWrapper.hpp"
#include "SDLogDriver.hpp"
#include "DualEncoderDriver.hpp"
#include "MotorDriver.h"
#include "TireContactModule.hpp"
#include "FrontLiftedDetection.hpp"
#include "MainLogic.h"
#include "ProximitySensors.hpp"
#include "SerialCommander.h"
#include "planar/PlanarAccelerationModule.hpp"
#include "planar/PlanarSpeedModule.hpp"
#include <Wire.h>
#include <SD.h>
#define SERIAL_BAUD_RATE 115200
#define I2C_FREQUENCY 400000
#define SD_CHIP_SELECT 4
#define LOG_FREQUENCY 100
#define SAMPLE_FREQUENCY 250
#define MICROS_PER_SECOND 1000000
#define LED_PIN 13
#define LEFT_A_PIN 12
#define LEFT_B_PIN 11
#define RIGHT_A_PIN 9
#define RIGHT_B_PIN 10
enum {
WAITING_FOR_COMMAND,
PREPARE_TO_FIGHT,
FIGHT_MODE,
BRAINDEAD,
TEST_MODE
} robot_state = WAITING_FOR_COMMAND;
OrientationSensors position;
DualEncoder leftEncoder(LEFT_A_PIN, LEFT_B_PIN);
DualEncoder rightEncoder(RIGHT_A_PIN, RIGHT_B_PIN);
void setup()
{
Serial.begin(SERIAL_BAUD_RATE);
SD.begin(SD_CHIP_SELECT);
initLogger();
leftEncoder.init([](){leftEncoder.A_handler();}, [](){leftEncoder.B_handler();});
rightEncoder.init([](){rightEncoder.A_handler();}, [](){rightEncoder.B_handler();});
initMotors();
initProximitySensors();
Wire.begin();
Wire.setClock(I2C_FREQUENCY);
position.init();
}
uint32_t event_micros;
void calibrate() {
digitalWrite(LED_PIN, HIGH);
position.calibrate();
initPlanarSpeed();
}
void setState(int new_state) {
robot_state = (decltype(robot_state)) new_state;
}
void getProximityCommand()
{
static uint8_t left = 0;
static uint8_t right = 0;
static uint8_t last_left = 0;
static uint8_t last_right = 0;
static int command_counter = 0;
readProximitySensors(left, right);
if(robot_state == WAITING_FOR_COMMAND)
{
if(right)
{
if(left < last_left)
{
++command_counter;
Serial.print("Counter: ");
Serial.println(command_counter);
}
}
else if(right < last_right)
{
if(!left)
{
switch(command_counter)
{
case 0:
robot_state = PREPARE_TO_FIGHT;
event_micros = micros();
break;
case 1:
calibrate();
break;
case 2:
robot_state = TEST_MODE;
Serial.println("Welcome to test mode");
break;
}
}
command_counter = 0;
}
}
else if(left && right)
{
if(robot_state == FIGHT_MODE)
{
robot_state = BRAINDEAD;
}
else
{
robot_state = WAITING_FOR_COMMAND;
command_counter = 42; // Just something invalid and BIG
}
robot_state = WAITING_FOR_COMMAND; // Remove
setMotors(0, 0);
}
last_left = left;
last_right = right;
}
void loop()
{
static uint32_t last_sample_micros = 0;
static uint32_t last_log_micros = 0;
static uint32_t last_blink_micros = 0;
uint32_t current_micros = micros();
{ // blink control
uint32_t full_cycle = MICROS_PER_SECOND;
uint32_t high_cycle = MICROS_PER_SECOND;
switch(robot_state)
{
case BRAINDEAD:
full_cycle *= 2;
high_cycle *= 1;
break;
case PREPARE_TO_FIGHT:
full_cycle /= 10;
high_cycle /= 20;
break;
case FIGHT_MODE:
case TEST_MODE:
full_cycle /= 2;
high_cycle /= 3;
default:
full_cycle /= 2;
high_cycle /= 5;
break;
}
if(current_micros - last_blink_micros >= full_cycle)
{
digitalWrite(LED_PIN, HIGH);
last_blink_micros = current_micros;
}
else if(current_micros - last_blink_micros >= high_cycle)
{
digitalWrite(LED_PIN, LOW);
}
}
switch(robot_state)
{
case BRAINDEAD:
setMotors(0, 0);
return;
case PREPARE_TO_FIGHT:
if(current_micros - event_micros >= MICROS_PER_SECOND * 5)
{
robot_state = FIGHT_MODE;
}
break;
case FIGHT_MODE:
{
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
/*if(getLeftTireContactState() == 0 && getRightTireContactState() == 0)
{
robot_state = BRAINDEAD;
break;
}*/
MainLogic(leftEncoder.getSpeed(), rightEncoder.getSpeed());
}
}
break;
case TEST_MODE:
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
/* PERFORM TESTS */
}
break;
default:
break;
}
// Read sensors
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
position.update();
leftEncoder.update();
rightEncoder.update();
updatePlanarSpeed(position);
getProximityCommand();
last_sample_micros = current_micros;
}
// Log data
if(current_micros - last_log_micros >= MICROS_PER_SECOND / LOG_FREQUENCY)
{
logDataPack(position, leftEncoder, rightEncoder, acceleration_vector, speed_vector);
last_log_micros = current_micros;
}
getSerialCommand();
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef URI_HPP
#define URI_HPP
#include <gsl.h>
#include <unordered_map>
namespace uri {
/**
* Representation of RFC 3986 URI's.
* Ref. https://tools.ietf.org/html/rfc3986
**/
class URI {
private:
/** Non-owning pointer-size type */
struct Span_t {
size_t begin;
size_t end;
Span_t(const size_t b = 0U, const size_t e = 0U) noexcept
: begin{b}
, end{e}
{}
}; //< struct Span_t
public:
/*
* Default constructor
*/
URI() = default;
/*
* Default copy and move constructors
*/
URI(URI&) = default;
URI(URI&&) = default;
/*
* Default destructor
*/
~URI() = default;
/*
* Default assignment operators
*/
URI& operator=(const URI&) = default;
URI& operator=(URI&&) = default;
//
// We might do a span-based constructor later.
// URI(gsl::span<const char>);
//
/**
* @brief Construct using a C-String
*
* @param uri : A C-String representing a uri
*/
URI(const char* uri);
/**
* @brief Construct using a string
*
* @param uri : A string representing a uri
*/
URI(const std::string& uri);
///////////////////////////////////////////////
//----------RFC-specified URI parts----------//
///////////////////////////////////////////////
/**
* @brief Get userinfo.
*
* E.g. 'username@'...
*
* @return The user's information
*/
std::string userinfo() const;
/**
* @brief Get host.
*
* E.g. 'includeos.org', '10.0.0.42' etc.
*
* @return The host's information
*/
std::string host() const;
/**
* @brief Get the raw port number in decimal character representation.
*
* @return The raw port number as a string
*/
std::string port_str() const;
/**
* @brief Get numeric port number.
*
* @warning The RFC doesn't specify dimension. This funcion will truncate
* any overflowing digits.
*
* @return The numeric port number as a 16-bit number
*/
uint16_t port() const noexcept;
/**
* @brief Get the path.
*
* E.g. /pictures/logo.png
*
* @return The path information
*/
std::string path() const;
/**
* @brief Get the complete unparsed query string.
*
* @return The complete unparsed query string
*/
std::string query() const;
/**
* @brief Get the fragment part.
*
* E.g. "...#anchor1"
*
* @return the fragment part
*/
std::string fragment() const;
///
/// Convenience
///
/**
* Get the URI-decoded value of a query-string key.
*
* E.g. for query() => "?name=Bjarne%20Stroustrup",
* query("name") returns "Bjarne Stroustrup" */
std::string query(std::string key);
/** String representation **/
std::string to_string() const;
private:
std::unordered_map<std::string,std::string> queries_;
Span_t uri_data_;
Span_t userinfo_;
Span_t host_;
Span_t port_str_;
uint16_t port_ = 0;
Span_t path_;
Span_t query_;
Span_t fragment_;
static const Span_t zero_span_;
// A copy of the data, if the string-based constructor was used
std::string uri_str_;
/**
* @brief Parse the given string representing a uri
* into its given parts according to RFC 3986
*
* @param uri : The string representing a uri
*/
void parse(const std::string& uri);
}; // class uri::URI
std::ostream& operator<< (std::ostream&, const URI&);
} // namespace uri
#endif
<commit_msg>Changed API doc for method API::query(std::string)<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef URI_HPP
#define URI_HPP
#include <gsl.h>
#include <unordered_map>
namespace uri {
/**
* Representation of RFC 3986 URI's.
* Ref. https://tools.ietf.org/html/rfc3986
**/
class URI {
private:
/** Non-owning pointer-size type */
struct Span_t {
size_t begin;
size_t end;
Span_t(const size_t b = 0U, const size_t e = 0U) noexcept
: begin{b}
, end{e}
{}
}; //< struct Span_t
public:
/*
* Default constructor
*/
URI() = default;
/*
* Default copy and move constructors
*/
URI(URI&) = default;
URI(URI&&) = default;
/*
* Default destructor
*/
~URI() = default;
/*
* Default assignment operators
*/
URI& operator=(const URI&) = default;
URI& operator=(URI&&) = default;
//
// We might do a span-based constructor later.
// URI(gsl::span<const char>);
//
/**
* @brief Construct using a C-String
*
* @param uri : A C-String representing a uri
*/
URI(const char* uri);
/**
* @brief Construct using a string
*
* @param uri : A string representing a uri
*/
URI(const std::string& uri);
///////////////////////////////////////////////
//----------RFC-specified URI parts----------//
///////////////////////////////////////////////
/**
* @brief Get userinfo.
*
* E.g. 'username@'...
*
* @return The user's information
*/
std::string userinfo() const;
/**
* @brief Get host.
*
* E.g. 'includeos.org', '10.0.0.42' etc.
*
* @return The host's information
*/
std::string host() const;
/**
* @brief Get the raw port number in decimal character representation.
*
* @return The raw port number as a string
*/
std::string port_str() const;
/**
* @brief Get numeric port number.
*
* @warning The RFC doesn't specify dimension. This funcion will truncate
* any overflowing digits.
*
* @return The numeric port number as a 16-bit number
*/
uint16_t port() const noexcept;
/**
* @brief Get the path.
*
* E.g. /pictures/logo.png
*
* @return The path information
*/
std::string path() const;
/**
* @brief Get the complete unparsed query string.
*
* @return The complete unparsed query string
*/
std::string query() const;
/**
* @brief Get the fragment part.
*
* E.g. "...#anchor1"
*
* @return the fragment part
*/
std::string fragment() const;
/**
* @brief Get the URI-decoded value of a query-string key.
*
* @param key : The key to find the associated value
*
* @return The key's associated value
*
* @example For the query: "?name=Bjarne%20Stroustrup",
* query("name") returns "Bjarne Stroustrup"
*/
std::string query(const std::string& key);
/** String representation **/
std::string to_string() const;
private:
std::unordered_map<std::string,std::string> queries_;
Span_t uri_data_;
Span_t userinfo_;
Span_t host_;
Span_t port_str_;
uint16_t port_ = 0;
Span_t path_;
Span_t query_;
Span_t fragment_;
static const Span_t zero_span_;
// A copy of the data, if the string-based constructor was used
std::string uri_str_;
/**
* @brief Parse the given string representing a uri
* into its given parts according to RFC 3986
*
* @param uri : The string representing a uri
*/
void parse(const std::string& uri);
}; // class uri::URI
std::ostream& operator<< (std::ostream&, const URI&);
} // namespace uri
#endif
<|endoftext|> |
<commit_before>#if !defined(DOUBLETAKE_XRUN_H)
#define DOUBLETAKE_XRUN_H
/*
* @file xrun.h
* @brief The main engine for consistency management, etc.
* @author Emery Berger <http://www.cs.umass.edu/~emery>
* @author Tongping Liu <http://www.cs.umass.edu/~tonyliu>
*/
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <unistd.h>
#include <new>
#include "globalinfo.hh"
#include "internalheap.hh"
#include "log.hh"
#include "mm.hh"
#include "real.hh"
#include "watchpoint.hh"
#include "xdefines.hh"
#include "xmemory.hh"
#include "xthread.hh"
#ifdef GET_CHARECTERISTICS
extern "C" {
extern unsigned long count_epochs;
};
#endif
class xrun {
private:
xrun()
: _memory(xmemory::getInstance()), _thread(xthread::getInstance()),
_watchpoint(watchpoint::getInstance())
{
// PRINF("xrun constructor\n");
}
public:
static xrun& getInstance() {
static char buf[sizeof(xrun)];
static xrun* theOneTrueObject = new (buf) xrun();
return *theOneTrueObject;
}
/// @brief Initialize the system.
void initialize() {
// PRINT("xrun: initialization at line %d\n", __LINE__);
struct rlimit rl;
// Get the stack size.
if(Real::getrlimit(RLIMIT_STACK, &rl) != 0) {
PRWRN("Get the stack size failed.\n");
Real::exit(-1);
}
// Check the stack size.
__max_stack_size = rl.rlim_cur;
#if 0
rl.rlim_cur = 524288;
rl.rlim_max = 1048576;
if(Real::setrlimit(RLIMIT_NOFILE, &rl)) {
PRINF("change limit failed, error %s\n", strerror(errno));
}
PRINF("NUMBER files limit %d\n", rl.rlim_cur);
while(1);
#endif
// Initialize the locks and condvar used in epoch switches
global_initialize();
installSignalHandler();
// Initialize the internal heap at first.
InternalHeap::getInstance().initialize();
_thread.initialize();
// Initialize the memory (install the memory handler)
_memory.initialize();
syscallsInitialize();
}
void finalize() {
#ifdef GET_CHARECTERISTICS
fprintf(stderr, "DOUBLETAKE has epochs %ld\n", count_epochs);
#endif
// If we are not in rollback phase, then we should check buffer overflow.
if(!global_isRollback()) {
#ifdef DETECT_USAGE_AFTER_FREE
finalUAFCheck();
#endif
epochEnd(true);
}
// PRINF("%d: finalize now !!!!!\n", getpid());
// Now we have to cleanup all semaphores.
_thread.finalize();
}
#ifdef DETECT_USAGE_AFTER_FREE
void finalUAFCheck();
#endif
// Simply commit specified memory block
void atomicCommit(void* addr, size_t size) { _memory.atomicCommit(addr, size); }
/* Transaction-related functions. */
void saveContext() { _thread.saveContext(); }
/// Rollback to previous saved point
void rollback();
/// Rollback to previous
void rollbackandstop();
void epochBegin();
void epochEnd(bool endOfProgram);
int getThreadIndex() const { return _thread.getThreadIndex(); }
char *getCurrentThreadBuffer() { return _thread.getCurrentThreadBuffer(); }
private:
void syscallsInitialize();
void stopAllThreads();
// Handling the signal SIGUSR2
static void sigusr2Handler(int signum, siginfo_t* siginfo, void* context);
/// @brief Install a handler for SIGUSR2 signals.
/// We are using the SIGUSR2 to stop all other threads.
void installSignalHandler() {
struct sigaction sigusr2;
static stack_t _sigstk;
// Set up an alternate signal stack.
_sigstk.ss_sp = MM::mmapAllocatePrivate(SIGSTKSZ);
_sigstk.ss_size = SIGSTKSZ;
_sigstk.ss_flags = 0;
Real::sigaltstack(&_sigstk, (stack_t*)0);
// We don't want to receive SIGUSR2 again when a thread is inside signal handler.
sigemptyset(&sigusr2.sa_mask);
sigaddset(&sigusr2.sa_mask, SIGUSR2);
// Real::sigprocmask (SIG_BLOCK, &sigusr2.sa_mask, NULL);
/**
Some parameters used here:
SA_RESTART: Provide behaviour compatible with BSD signal
semantics by making certain system calls restartable across signals.
SA_SIGINFO: The signal handler takes 3 arguments, not one. In this case, sa_sigac-
tion should be set instead of sa_handler.
So, we can acquire the user context inside the signal handler
*/
sigusr2.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
sigusr2.sa_sigaction = xrun::sigusr2Handler;
if(Real::sigaction(SIGUSR2, &sigusr2, NULL) == -1) {
fprintf(stderr, "setting signal handler SIGUSR2 failed.\n");
abort();
}
}
// Notify the system call handler about rollback phase
void startRollback();
/* volatile bool _hasRolledBack; */
/// The memory manager (for both heap and globals).
xmemory& _memory;
xthread& _thread;
watchpoint& _watchpoint;
// int _rollbackStatus;
/* int _pid; // The first process's id. */
/* int _main_id; */
};
#endif
<commit_msg>xrun: behave reasonably in the face of an unlimited stack size rlimit (thanks Make)<commit_after>#if !defined(DOUBLETAKE_XRUN_H)
#define DOUBLETAKE_XRUN_H
/*
* @file xrun.h
* @brief The main engine for consistency management, etc.
* @author Emery Berger <http://www.cs.umass.edu/~emery>
* @author Tongping Liu <http://www.cs.umass.edu/~tonyliu>
*/
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <unistd.h>
#include <new>
#include "globalinfo.hh"
#include "internalheap.hh"
#include "log.hh"
#include "mm.hh"
#include "real.hh"
#include "watchpoint.hh"
#include "xdefines.hh"
#include "xmemory.hh"
#include "xthread.hh"
#ifdef GET_CHARECTERISTICS
extern "C" {
extern unsigned long count_epochs;
};
#endif
class xrun {
private:
xrun()
: _memory(xmemory::getInstance()), _thread(xthread::getInstance()),
_watchpoint(watchpoint::getInstance())
{
// PRINF("xrun constructor\n");
}
public:
static xrun& getInstance() {
static char buf[sizeof(xrun)];
static xrun* theOneTrueObject = new (buf) xrun();
return *theOneTrueObject;
}
/// @brief Initialize the system.
void initialize() {
// PRINT("xrun: initialization at line %d\n", __LINE__);
struct rlimit rl;
// Get the stack size.
if(Real::getrlimit(RLIMIT_STACK, &rl) != 0) {
PRWRN("Get the stack size failed.\n");
Real::exit(-1);
}
// if there is no limit for our stack size, then just pick a
// reasonable limit.
if (rl.rlim_cur == (rlim_t)-1) {
rl.rlim_cur = 2048*4096; // 8 MB
}
// Check the stack size.
__max_stack_size = rl.rlim_cur;
#if 0
rl.rlim_cur = 524288;
rl.rlim_max = 1048576;
if(Real::setrlimit(RLIMIT_NOFILE, &rl)) {
PRINF("change limit failed, error %s\n", strerror(errno));
}
PRINF("NUMBER files limit %d\n", rl.rlim_cur);
while(1);
#endif
// Initialize the locks and condvar used in epoch switches
global_initialize();
installSignalHandler();
// Initialize the internal heap at first.
InternalHeap::getInstance().initialize();
_thread.initialize();
// Initialize the memory (install the memory handler)
_memory.initialize();
syscallsInitialize();
}
void finalize() {
#ifdef GET_CHARECTERISTICS
fprintf(stderr, "DOUBLETAKE has epochs %ld\n", count_epochs);
#endif
// If we are not in rollback phase, then we should check buffer overflow.
if(!global_isRollback()) {
#ifdef DETECT_USAGE_AFTER_FREE
finalUAFCheck();
#endif
epochEnd(true);
}
// PRINF("%d: finalize now !!!!!\n", getpid());
// Now we have to cleanup all semaphores.
_thread.finalize();
}
#ifdef DETECT_USAGE_AFTER_FREE
void finalUAFCheck();
#endif
// Simply commit specified memory block
void atomicCommit(void* addr, size_t size) { _memory.atomicCommit(addr, size); }
/* Transaction-related functions. */
void saveContext() { _thread.saveContext(); }
/// Rollback to previous saved point
void rollback();
/// Rollback to previous
void rollbackandstop();
void epochBegin();
void epochEnd(bool endOfProgram);
int getThreadIndex() const { return _thread.getThreadIndex(); }
char *getCurrentThreadBuffer() { return _thread.getCurrentThreadBuffer(); }
private:
void syscallsInitialize();
void stopAllThreads();
// Handling the signal SIGUSR2
static void sigusr2Handler(int signum, siginfo_t* siginfo, void* context);
/// @brief Install a handler for SIGUSR2 signals.
/// We are using the SIGUSR2 to stop all other threads.
void installSignalHandler() {
struct sigaction sigusr2;
static stack_t _sigstk;
// Set up an alternate signal stack.
_sigstk.ss_sp = MM::mmapAllocatePrivate(SIGSTKSZ);
_sigstk.ss_size = SIGSTKSZ;
_sigstk.ss_flags = 0;
Real::sigaltstack(&_sigstk, (stack_t*)0);
// We don't want to receive SIGUSR2 again when a thread is inside signal handler.
sigemptyset(&sigusr2.sa_mask);
sigaddset(&sigusr2.sa_mask, SIGUSR2);
// Real::sigprocmask (SIG_BLOCK, &sigusr2.sa_mask, NULL);
/**
Some parameters used here:
SA_RESTART: Provide behaviour compatible with BSD signal
semantics by making certain system calls restartable across signals.
SA_SIGINFO: The signal handler takes 3 arguments, not one. In this case, sa_sigac-
tion should be set instead of sa_handler.
So, we can acquire the user context inside the signal handler
*/
sigusr2.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
sigusr2.sa_sigaction = xrun::sigusr2Handler;
if(Real::sigaction(SIGUSR2, &sigusr2, NULL) == -1) {
fprintf(stderr, "setting signal handler SIGUSR2 failed.\n");
abort();
}
}
// Notify the system call handler about rollback phase
void startRollback();
/* volatile bool _hasRolledBack; */
/// The memory manager (for both heap and globals).
xmemory& _memory;
xthread& _thread;
watchpoint& _watchpoint;
// int _rollbackStatus;
/* int _pid; // The first process's id. */
/* int _main_id; */
};
#endif
<|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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what handling_expose is for.
handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
handling_expose = false;
return FALSE;
}
gboolean DestroyEvent(GtkWidget* widget, GdkEvent* event,
WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// This signal is called when arrow keys or tab is pressed. If we return true,
// we prevent focus from being moved to another widget. If we want to allow
// focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
gboolean FocusMove(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
} // anonymous namespace
// -----------------------------------------------------------------------------
gfx::WindowHandle WebWidgetHost::CreateWindow(gfx::WindowHandle box,
void* host) {
GtkWidget* widget = gtk_drawing_area_new();
gtk_box_pack_start(GTK_BOX(box), widget, TRUE, TRUE, 0);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event", G_CALLBACK(ConfigureEvent), host);
g_signal_connect(widget, "expose-event", G_CALLBACK(ExposeEvent), host);
g_signal_connect(widget, "destroy-event", G_CALLBACK(DestroyEvent), host);
g_signal_connect(widget, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host);
g_signal_connect(widget, "focus", G_CALLBACK(FocusMove), host);
g_signal_connect(widget, "focus-in-event", G_CALLBACK(FocusIn), host);
g_signal_connect(widget, "focus-out-event", G_CALLBACK(FocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
host);
g_signal_connect(widget, "scroll-event", G_CALLBACK(MouseScrollEvent),
host);
return widget;
}
WebWidgetHost* WebWidgetHost::Create(gfx::WindowHandle box,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWindow(box, host);
host->webwidget_ = WebWidget::Create(delegate);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost* FromWindow(gfx::WindowHandle view) {
const gpointer p = g_object_get_data(G_OBJECT(view), "webwidgethost");
return (WebWidgetHost* ) p;
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new gfx::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// BitBlit to the X server
gfx::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
gfx::BitmapPlatformDeviceLinux* const bitdev =
static_cast<gfx::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(view_->window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
// -----------------------------------------------------------------------------
// This is called when the GTK window is destroyed. In the Windows code this
// deletes this object. Since it's only test_shell it probably doesn't matter
// that much.
// -----------------------------------------------------------------------------
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<commit_msg>Turn off gtk double buffering of webwidget host's view_ widget, and manually update underlying gdk window during paint operation.<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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what handling_expose is for.
handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
handling_expose = false;
return FALSE;
}
gboolean DestroyEvent(GtkWidget* widget, GdkEvent* event,
WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// This signal is called when arrow keys or tab is pressed. If we return true,
// we prevent focus from being moved to another widget. If we want to allow
// focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
gboolean FocusMove(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
} // anonymous namespace
// -----------------------------------------------------------------------------
gfx::WindowHandle WebWidgetHost::CreateWindow(gfx::WindowHandle box,
void* host) {
GtkWidget* widget = gtk_drawing_area_new();
gtk_box_pack_start(GTK_BOX(box), widget, TRUE, TRUE, 0);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event", G_CALLBACK(ConfigureEvent), host);
g_signal_connect(widget, "expose-event", G_CALLBACK(ExposeEvent), host);
g_signal_connect(widget, "destroy-event", G_CALLBACK(DestroyEvent), host);
g_signal_connect(widget, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host);
g_signal_connect(widget, "focus", G_CALLBACK(FocusMove), host);
g_signal_connect(widget, "focus-in-event", G_CALLBACK(FocusIn), host);
g_signal_connect(widget, "focus-out-event", G_CALLBACK(FocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
host);
g_signal_connect(widget, "scroll-event", G_CALLBACK(MouseScrollEvent),
host);
return widget;
}
WebWidgetHost* WebWidgetHost::Create(gfx::WindowHandle box,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWindow(box, host);
host->webwidget_ = WebWidget::Create(delegate);
// We manage our own double buffering because we need to be able to update
// the expose area in an ExposeEvent within the lifetime of the event handler.
gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost* FromWindow(gfx::WindowHandle view) {
const gpointer p = g_object_get_data(G_OBJECT(view), "webwidgethost");
return (WebWidgetHost* ) p;
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new gfx::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
// Store the total area painted in total_paint. Then tell the gdk window
// to update that area after we're done painting it.
gfx::Rect total_paint;
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
total_paint = total_paint.Union(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
// we wish to avoid. So instead we use calls to begin_paint/end_paint.
GdkRectangle grect = {
total_paint.x(),
total_paint.y(),
total_paint.width(),
total_paint.height(),
};
gdk_window_begin_paint_rect(view_->window, &grect);
// BitBlit to the gdk window.
gfx::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
gfx::BitmapPlatformDeviceLinux* const bitdev =
static_cast<gfx::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(view_->window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(view_->window);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
// -----------------------------------------------------------------------------
// This is called when the GTK window is destroyed. In the Windows code this
// deletes this object. Since it's only test_shell it probably doesn't matter
// that much.
// -----------------------------------------------------------------------------
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<|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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what handling_expose is for.
handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
handling_expose = false;
return FALSE;
}
gboolean DestroyEvent(GtkWidget* widget, GdkEvent* event,
WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// This signal is called when arrow keys or tab is pressed. If we return true,
// we prevent focus from being moved to another widget. If we want to allow
// focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
gboolean FocusMove(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
} // anonymous namespace
// -----------------------------------------------------------------------------
gfx::WindowHandle WebWidgetHost::CreateWindow(gfx::WindowHandle box,
void* host) {
GtkWidget* widget = gtk_drawing_area_new();
gtk_box_pack_start(GTK_BOX(box), widget, TRUE, TRUE, 0);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event", G_CALLBACK(ConfigureEvent), host);
g_signal_connect(widget, "expose-event", G_CALLBACK(ExposeEvent), host);
g_signal_connect(widget, "destroy-event", G_CALLBACK(DestroyEvent), host);
g_signal_connect(widget, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host);
g_signal_connect(widget, "focus", G_CALLBACK(FocusMove), host);
g_signal_connect(widget, "focus-in-event", G_CALLBACK(FocusIn), host);
g_signal_connect(widget, "focus-out-event", G_CALLBACK(FocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
host);
g_signal_connect(widget, "scroll-event", G_CALLBACK(MouseScrollEvent),
host);
return widget;
}
WebWidgetHost* WebWidgetHost::Create(gfx::WindowHandle box,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWindow(box, host);
host->webwidget_ = WebWidget::Create(delegate);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost* FromWindow(gfx::WindowHandle view) {
const gpointer p = g_object_get_data(G_OBJECT(view), "webwidgethost");
return (WebWidgetHost* ) p;
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new gfx::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// BitBlit to the X server
gfx::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
gfx::BitmapPlatformDeviceLinux* const bitdev =
static_cast<gfx::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(view_->window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
// -----------------------------------------------------------------------------
// This is called when the GTK window is destroyed. In the Windows code this
// deletes this object. Since it's only test_shell it probably doesn't matter
// that much.
// -----------------------------------------------------------------------------
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<commit_msg>Turn off gtk double buffering of webwidget host's view_ widget, and manually update underlying gdk window during paint operation.<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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what handling_expose is for.
handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
handling_expose = false;
return FALSE;
}
gboolean DestroyEvent(GtkWidget* widget, GdkEvent* event,
WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// This signal is called when arrow keys or tab is pressed. If we return true,
// we prevent focus from being moved to another widget. If we want to allow
// focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
gboolean FocusMove(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
} // anonymous namespace
// -----------------------------------------------------------------------------
gfx::WindowHandle WebWidgetHost::CreateWindow(gfx::WindowHandle box,
void* host) {
GtkWidget* widget = gtk_drawing_area_new();
gtk_box_pack_start(GTK_BOX(box), widget, TRUE, TRUE, 0);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event", G_CALLBACK(ConfigureEvent), host);
g_signal_connect(widget, "expose-event", G_CALLBACK(ExposeEvent), host);
g_signal_connect(widget, "destroy-event", G_CALLBACK(DestroyEvent), host);
g_signal_connect(widget, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host);
g_signal_connect(widget, "focus", G_CALLBACK(FocusMove), host);
g_signal_connect(widget, "focus-in-event", G_CALLBACK(FocusIn), host);
g_signal_connect(widget, "focus-out-event", G_CALLBACK(FocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
host);
g_signal_connect(widget, "scroll-event", G_CALLBACK(MouseScrollEvent),
host);
return widget;
}
WebWidgetHost* WebWidgetHost::Create(gfx::WindowHandle box,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWindow(box, host);
host->webwidget_ = WebWidget::Create(delegate);
// We manage our own double buffering because we need to be able to update
// the expose area in an ExposeEvent within the lifetime of the event handler.
gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost* FromWindow(gfx::WindowHandle view) {
const gpointer p = g_object_get_data(G_OBJECT(view), "webwidgethost");
return (WebWidgetHost* ) p;
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new gfx::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
// Store the total area painted in total_paint. Then tell the gdk window
// to update that area after we're done painting it.
gfx::Rect total_paint;
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
total_paint = total_paint.Union(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
// we wish to avoid. So instead we use calls to begin_paint/end_paint.
GdkRectangle grect = {
total_paint.x(),
total_paint.y(),
total_paint.width(),
total_paint.height(),
};
gdk_window_begin_paint_rect(view_->window, &grect);
// BitBlit to the gdk window.
gfx::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
gfx::BitmapPlatformDeviceLinux* const bitdev =
static_cast<gfx::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(view_->window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(view_->window);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
// -----------------------------------------------------------------------------
// This is called when the GTK window is destroyed. In the Windows code this
// deletes this object. Since it's only test_shell it probably doesn't matter
// that much.
// -----------------------------------------------------------------------------
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<|endoftext|> |
<commit_before>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "base/util.h"
#include "base/stringpiece.h"
namespace operations_research {
// Walltimer
#if !defined(_MSC_VER)
namespace {
static inline int64 TimevalToUsec(const timeval &tv) {
return static_cast<int64>(1000000) * tv.tv_sec + tv.tv_usec;
}
} // namespace
#endif
WallTimer::WallTimer() :
start_usec_(0LL), sum_usec_(0LL), has_started_(false) {}
void WallTimer::Start() { // Just save when we started
#if defined(_MSC_VER)
start_usec_ = clock();
#elif defined(__GNUC__)
struct timeval tv;
gettimeofday(&tv, NULL);
start_usec_ = TimevalToUsec(tv);
#endif
has_started_ = true;
}
void WallTimer::Stop() { // Update total time, 1st time it's called
if ( has_started_ ) { // so two Stop()s is safe
#if defined(_MSC_VER)
sum_usec_ += clock() - start_usec_;
#elif defined(__GNUC__)
struct timeval tv;
gettimeofday(&tv, NULL);
sum_usec_ += TimevalToUsec(tv) - start_usec_;
#endif
has_started_ = false;
}
}
bool WallTimer::Reset() { // As if we had hit Stop() first
start_usec_ = 0;
sum_usec_ = 0;
has_started_ = false;
return true;
}
void WallTimer::Restart() {
Reset(); Start();
}
bool WallTimer::IsRunning() const {
return has_started_;
}
int64 WallTimer::GetInMs() const {
#if defined(_MSC_VER)
int64 local_sum_usec = sum_usec_;
if ( has_started_ ) { // need to include current time too
local_sum_usec += clock() - start_usec_;
}
return local_sum_usec;
#elif defined(__GNUC__)
static const int64 kMilliSecInMicroSec = 1000LL;
int64 local_sum_usec = sum_usec_;
if ( has_started_ ) { // need to include current time too
struct timeval tv;
gettimeofday(&tv, NULL);
local_sum_usec += TimevalToUsec(tv) - start_usec_;
}
return local_sum_usec / kMilliSecInMicroSec;
#endif
}
// GetUsedMemory
#if defined(__APPLE__) && defined(__GNUC__)
#include <mach/mach_init.h>
#include <mach/task.h>
int64 GetMemoryUsage () {
task_t task = MACH_PORT_NULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&t_info,
&t_info_count)) {
return -1;
}
int64 resident_memory = t_info.resident_size;
// int64 virtual_memory = t_info.virtual_size;
return resident_memory;
}
#elif defined(__GNUC__) // LINUX
int64 GetMemoryUsage() {
return 0;
}
#elif DEFINED(_MSC_VER) // WINDOWS
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
int64 GetMemoryInfo() {
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
GetCurrentProcess());
int64 memory = 0;
if (hProcess) {
if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) {
memory = pmc.WorkingSetSize;
}
Closehandle(hProcess);
}
return memory;
}
#else // Unknown, returning 0.
int64 GetMemoryUsage() {
return 0;
}
#endif
} // namespace operations_research
<commit_msg>Memory usage implemented in Linux<commit_after>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "base/util.h"
#include "base/stringpiece.h"
namespace operations_research {
// Walltimer
#if !defined(_MSC_VER)
namespace {
static inline int64 TimevalToUsec(const timeval &tv) {
return static_cast<int64>(1000000) * tv.tv_sec + tv.tv_usec;
}
} // namespace
#endif
WallTimer::WallTimer() :
start_usec_(0LL), sum_usec_(0LL), has_started_(false) {}
void WallTimer::Start() { // Just save when we started
#if defined(_MSC_VER)
start_usec_ = clock();
#elif defined(__GNUC__)
struct timeval tv;
gettimeofday(&tv, NULL);
start_usec_ = TimevalToUsec(tv);
#endif
has_started_ = true;
}
void WallTimer::Stop() { // Update total time, 1st time it's called
if ( has_started_ ) { // so two Stop()s is safe
#if defined(_MSC_VER)
sum_usec_ += clock() - start_usec_;
#elif defined(__GNUC__)
struct timeval tv;
gettimeofday(&tv, NULL);
sum_usec_ += TimevalToUsec(tv) - start_usec_;
#endif
has_started_ = false;
}
}
bool WallTimer::Reset() { // As if we had hit Stop() first
start_usec_ = 0;
sum_usec_ = 0;
has_started_ = false;
return true;
}
void WallTimer::Restart() {
Reset(); Start();
}
bool WallTimer::IsRunning() const {
return has_started_;
}
int64 WallTimer::GetInMs() const {
#if defined(_MSC_VER)
int64 local_sum_usec = sum_usec_;
if ( has_started_ ) { // need to include current time too
local_sum_usec += clock() - start_usec_;
}
return local_sum_usec;
#elif defined(__GNUC__)
static const int64 kMilliSecInMicroSec = 1000LL;
int64 local_sum_usec = sum_usec_;
if ( has_started_ ) { // need to include current time too
struct timeval tv;
gettimeofday(&tv, NULL);
local_sum_usec += TimevalToUsec(tv) - start_usec_;
}
return local_sum_usec / kMilliSecInMicroSec;
#endif
}
// GetUsedMemory
#if defined(__APPLE__) && defined(__GNUC__)
#include <mach/mach_init.h>
#include <mach/task.h>
int64 GetMemoryUsage () {
task_t task = MACH_PORT_NULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&t_info,
&t_info_count)) {
return -1;
}
int64 resident_memory = t_info.resident_size;
// int64 virtual_memory = t_info.virtual_size;
return resident_memory;
}
#elif defined(__GNUC__) // LINUX
int64 GetMemoryUsage() {
unsigned size = 0;
int result;
char buf[30];
snprintf(buf, 30, "/proc/%u/statm", (unsigned)getpid());
FILE* pf = fopen(buf, "r");
if (pf) {
result = fscanf(pf, "%u", &size);
}
fclose(pf);
return size * GG_LONGLONG(1024);
}
#elif defined(_MSC_VER) // WINDOWS
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
int64 GetMemoryInfo() {
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
GetCurrentProcess());
int64 memory = 0;
if (hProcess) {
if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) {
memory = pmc.WorkingSetSize;
}
Closehandle(hProcess);
}
return memory;
}
#else // Unknown, returning 0.
int64 GetMemoryUsage() {
return 0;
}
#endif
} // namespace operations_research
<|endoftext|> |
<commit_before><commit_msg>Blind fix attempt: include <osl/diagnose.h><commit_after><|endoftext|> |
<commit_before>//!
//! @author Yue Wang
//! @date 18.11.2014
//!
//! Disscussion on SO:
//! http://stackoverflow.com/questions/26971625/whats-the-difference-between-functor-and-lambda-when-used-for-constructing-std
//!
//! Based on Listing 2.8, serveral differences.
//!
#include <thread>
#include <algorithm>
#include <vector>
#include <iostream>
namespace para {
template<typename Iter, typename Value>
Value parallel_accumulate(Iter first, Iter last, Value init_val)
{
using std::size_t;
size_t length = std::distance(first, last);
if(length == 0) return init_val; // trivial case
size_t min_per_thread = 25;
size_t max_threads = (length + min_per_thread - 1) / min_per_thread;
size_t hardware_threads = std::thread::hardware_concurrency();
size_t num_threads = std::min((hardware_threads!=0 ? hardware_threads : 2), max_threads);
size_t block_size = length/num_threads;
std::vector<Value> results(num_threads);
std::vector<std::thread> threads{num_threads - 1};
Iter block_start = first;
for(unsigned long idx=0; idx!=(num_threads-1); ++idx )
{
Iter block_end = block_start;
std::advance(block_end, block_size);
Value & result = results[idx];
threads[idx] = std::thread
{
[=,&result]{
result = std::accumulate(block_start, block_end, result);
}
};
block_start = block_end;
}
results.back() = std::accumulate(block_start, last, results.back());
for(auto& t : threads) t.join();
return std::accumulate(results.begin(), results.end(), init_val);
}
}//namespace
int main()
{
std::vector<int> v(10000,1);
auto sum = para::parallel_accumulate(v.begin(), v.end(), 0);
std::cout << "sum = " << sum << std::endl;
return 0;
}
<commit_msg>add output modified: ch02/parallel_accumulate.cpp<commit_after>//!
//! @author Yue Wang
//! @date 18.11.2014
//!
//! Disscussion on SO:
//! http://stackoverflow.com/questions/26971625/whats-the-difference-between-functor-and-lambda-when-used-for-constructing-std
//!
//! Based on Listing 2.8, serveral differences.
//!
#include <thread>
#include <algorithm>
#include <vector>
#include <iostream>
namespace para {
template<typename Iter, typename Value>
Value parallel_accumulate(Iter first, Iter last, Value init_val)
{
using std::size_t;
size_t length = std::distance(first, last);
if(length == 0) return init_val; // trivial case
size_t min_per_thread = 25;
size_t max_threads = (length + min_per_thread - 1) / min_per_thread;
size_t hardware_threads = std::thread::hardware_concurrency();
size_t num_threads = std::min((hardware_threads!=0 ? hardware_threads : 2), max_threads);
size_t block_size = length/num_threads;
std::vector<Value> results(num_threads);
std::vector<std::thread> threads{num_threads - 1};
Iter block_start = first;
for(unsigned long idx=0; idx!=(num_threads-1); ++idx )
{
Iter block_end = block_start;
std::advance(block_end, block_size);
Value & result = results[idx];
threads[idx] = std::thread
{
[=,&result]{
result = std::accumulate(block_start, block_end, result);
}
};
block_start = block_end;
}
results.back() = std::accumulate(block_start, last, results.back());
for(auto& t : threads) t.join();
return std::accumulate(results.begin(), results.end(), init_val);
}
}//namespace
int main()
{
std::vector<int> v(10000,1);
auto sum = para::parallel_accumulate(v.begin(), v.end(), 0);
std::cout << "sum = " << sum << std::endl;
return 0;
}
//! output :
//!
//sum = 10000
<|endoftext|> |
<commit_before>/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
map<char, double> table;
void initMap() {
// Mapping between chemical symbols and their molar weights
table['H'] = 1.008;
table['C'] = 12.01;
table['N'] = 14.01;
table['O'] = 16.00;
}
bool isNumeric(char c) {
// Return if the representation of a character is that of a number
return '0' <= c && c <= '9';
}
int main(){
int T;
// Number of Test Cases
string s;
// String containing the read element chain
initMap();
cin >> T;
while(T--) {
cin >> s;
// USE DOUBLE PRECISION SERIOUSLY, WITH FLOAT IT LOSES PRECISION WAY
// TOO FAST, and I can confirm it costed me a submission ;-)
double total = 0;
// Total molar weight of a given molecule
double num = 0;
// The value of the last read element, to apply multipliers into
int mult = 0;
// The multiplier to apply to the chemical element right before it
for(int k = 0; k < s.length(); k++) {
if(isNumeric(s[k])) {
// If we're reading a indice value
if(mult != 0) {
// If we had just read one, it means the previous one is a
// decimal place bigger than the current one, but both are
// part of the same number. I think this allows to exceed
// the bound of two decimal places that the problem has.
mult *= 10;
}
mult += s[k] - '0';
}
else {
// If a chemical symbol is read
if(mult != 0) {
// Check if we had a previously computed index, and apply it to
// the previously found chemical element, if any.
num *= mult;
}
mult = 0;
// Reset the chemical element multiplier
total += num;
// Add the previously found number to the running count of mass
num = table[s[k]];
// Set a new value to possibly apply a multiplying factor later
}
}
// Do the last step again in case we ran out of the string and never
// got to find a new element that would cause the previously found mult
// liplier to apply to the previously found element and add it into the
// running total of mole mass for the given molecule.
if(mult != 0) {
num *= mult;
}
total += num;
printf("%.3lf\n", total);
// Print with 3 decimal places
}
}<commit_msg>Added second batch from Summer Training, 2014<commit_after>/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
map<char, double> table;
void initMap() {
// Mapping between chemical symbols and their molar weights
table['H'] = 1.008;
table['C'] = 12.01;
table['N'] = 14.01;
table['O'] = 16.00;
}
bool isNumeric(char c) {
// Return if the representation of a character is that of a number
return '0' <= c && c <= '9';
}
int main() {
int T;
// Number of Test Cases
string s;
// String containing the read element chain
initMap();
cin >> T;
while(T--) {
cin >> s;
// USE DOUBLE PRECISION SERIOUSLY, WITH FLOAT IT LOSES PRECISION WAY
// TOO FAST, and I can confirm it costed me a submission ;-)
double total = 0;
// Total molar weight of a given molecule
double num = 0;
// The value of the last read element, to apply multipliers into
int mult = 0;
// The multiplier to apply to the chemical element right before it
for(int k = 0; k < s.length(); k++) {
if(isNumeric(s[k])) {
// If we're reading a indice value
if(mult != 0) {
// If we had just read one, it means the previous one is a
// decimal place bigger than the current one, but both are
// part of the same number. I think this allows to exceed
// the bound of two decimal places that the problem has.
mult *= 10;
}
mult += s[k] - '0';
}
else {
// If a chemical symbol is read
if(mult != 0) {
// Check if we had a previously computed index, and apply it to
// the previously found chemical element, if any.
num *= mult;
}
mult = 0;
// Reset the chemical element multiplier
total += num;
// Add the previously found number to the running count of mass
num = table[s[k]];
// Set a new value to possibly apply a multiplying factor later
}
}
// Do the last step again in case we ran out of the string and never
// got to find a new element that would cause the previously found mult
// liplier to apply to the previously found element and add it into the
// running total of mole mass for the given molecule.
if(mult != 0) {
num *= mult;
}
total += num;
printf("%.3lf\n", total);
// Print with 3 decimal places
}
}<|endoftext|> |
<commit_before>// Copyright GHI Electronics, LLC
//
// 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 "STM32F4.h"
static TinyCLR_Rtc_Provider rtcProvider;
static TinyCLR_Api_Info timeApi;
const TinyCLR_Api_Info* STM32F4_Rtc_GetApi() {
rtcProvider.Parent = &timeApi;
rtcProvider.Index = 0;
rtcProvider.Acquire = &STM32F4_Rtc_Acquire;
rtcProvider.Release = &STM32F4_Rtc_Release;
rtcProvider.GetNow = &STM32F4_Rtc_GetNow;
rtcProvider.SetNow = &STM32F4_Rtc_SetNow;
timeApi.Author = "GHI Electronics, LLC";
timeApi.Name = "GHIElectronics.TinyCLR.NativeApis.STM32F4.RtcProvider";
timeApi.Type = TinyCLR_Api_Type::RtcProvider;
timeApi.Version = 0;
timeApi.Count = 1;
timeApi.Implementation = &rtcProvider;
return &timeApi;
}
TinyCLR_Result STM32F4_Rtc_Acquire(const TinyCLR_Rtc_Provider* self) {
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F4_Rtc_Release(const TinyCLR_Rtc_Provider* self) {
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F4_Rtc_GetNow(const TinyCLR_Rtc_Provider* self, TinyCLR_Rtc_DateTime& value) {
value.Year = 2010;
value.Month = 2;
value.DayOfYear = 33;
value.DayOfMonth = 2;
value.DayOfWeek = 0;
value.Hour = 13;
value.Minute = 14;
value.Second = 15;
value.Millisecond = 516;
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F4_Rtc_SetNow(const TinyCLR_Rtc_Provider* self, TinyCLR_Rtc_DateTime value) {
return TinyCLR_Result::Success;
}
<commit_msg>Implement RTC for STM32F4<commit_after>// Copyright GHI Electronics, LLC
//
// 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 "STM32F4.h"
#define PWR_OFFSET (PWR_BASE - PERIPH_BASE)
/* --- CR Register ---*/
/* Alias word address of DBP bit */
#define CR_OFFSET (PWR_OFFSET + 0x00)
#define DBP_BitNumber 0x08
#define CR_DBP_BB (PERIPH_BB_BASE + (CR_OFFSET * 32) + (DBP_BitNumber * 4))
/* ------------ RCC registers bit address in the alias region ----------- */
#define RCC_OFFSET (RCC_BASE - PERIPH_BASE)
/* Alias word address of RTCEN bit */
#define BDCR_OFFSET (RCC_OFFSET + 0x70)
#define RTCEN_BitNumber 0x0F
#define BDCR_RTCEN_BB (PERIPH_BB_BASE + (BDCR_OFFSET * 32) + (RTCEN_BitNumber * 4))
/* BDCR register base address */
#define BDCR_ADDRESS (PERIPH_BASE + BDCR_OFFSET)
#define RCC_LSE_OFF ((uint8_t)0x00)
#define RCC_LSE_ON ((uint8_t)0x01)
#define RCC_FLAG_HSIRDY ((uint8_t)0x21)
#define RCC_FLAG_HSERDY ((uint8_t)0x31)
#define RCC_FLAG_PLLRDY ((uint8_t)0x39)
#define RCC_FLAG_PLLI2SRDY ((uint8_t)0x3B)
#define RCC_FLAG_LSERDY ((uint8_t)0x41)
#define RCC_FLAG_LSIRDY ((uint8_t)0x61)
#define RCC_FLAG_BORRST ((uint8_t)0x79)
#define RCC_FLAG_PINRST ((uint8_t)0x7A)
#define RCC_FLAG_PORRST ((uint8_t)0x7B)
#define RCC_FLAG_SFTRST ((uint8_t)0x7C)
#define RCC_FLAG_IWDGRST ((uint8_t)0x7D)
#define RCC_FLAG_WWDGRST ((uint8_t)0x7E)
#define RCC_FLAG_LPWRRST ((uint8_t)0x7F)
#define RCC_FLAG_MASK ((uint8_t)0x1F)
#define RCC_RTCCLKSource_LSE ((uint32_t)0x00000100)
/** @defgroup RTC_Hour_Formats
* @{
*/
#define RTC_HourFormat_24 ((uint32_t)0x00000000)
#define RTC_HourFormat_12 ((uint32_t)0x00000040)
/* Masks Definition */
#define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F)
#define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F)
#define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF)
#define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F)
#define RTC_BKP_DR0 ((uint32_t)0x00000000)
#define RTC_BKP_VALUE 0x32F2
static TinyCLR_Rtc_Provider rtcProvider;
static TinyCLR_Api_Info timeApi;
const TinyCLR_Api_Info* STM32F4_Rtc_GetApi() {
rtcProvider.Parent = &timeApi;
rtcProvider.Index = 0;
rtcProvider.Acquire = &STM32F4_Rtc_Acquire;
rtcProvider.Release = &STM32F4_Rtc_Release;
rtcProvider.GetNow = &STM32F4_Rtc_GetNow;
rtcProvider.SetNow = &STM32F4_Rtc_SetNow;
timeApi.Author = "GHI Electronics, LLC";
timeApi.Name = "GHIElectronics.TinyCLR.NativeApis.STM32F4.RtcProvider";
timeApi.Type = TinyCLR_Api_Type::RtcProvider;
timeApi.Version = 0;
timeApi.Count = 1;
timeApi.Implementation = &rtcProvider;
return &timeApi;
}
uint8_t STM32F4_Rtc_ByteToBcd2(uint8_t value) {
uint8_t bcdhigh = 0;
while (value >= 10) {
bcdhigh++;
value -= 10;
}
return ((uint8_t)(bcdhigh << 4) | value);
}
uint8_t STM32F4_Rtc_Bcd2ToByte(uint8_t value) {
return ((((uint8_t)(value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10) + (value & (uint8_t)0x0F));
}
TinyCLR_Result STM32F4_Rtc_EnterInitializeMode() {
int timeout = 0xFFFFFF;
/* Check if the Initialization mode is set */
if ((RTC->ISR & RTC_ISR_INITF) == 0) {
/* Set the Initialization mode */
RTC->ISR |= RTC_INIT_MASK;
/* Wait till RTC is in INIT state and if Time out is reached exit */
while ((timeout-- > 0) && ((RTC->ISR & RTC_ISR_INITF) == 0));
}
return timeout > 0 ? TinyCLR_Result::Success : TinyCLR_Result::InvalidOperation;
}
TinyCLR_Result STM32F4_Rtc_ExitInitializeMode() {
RTC->ISR &= (uint32_t)~RTC_ISR_INIT;
}
void STM32F4_Rtc_EnableWriteProtection() {
RTC->WPR = 0xFF;
}
void STM32F4_Rtc_DisableWriteProtection() {
RTC->WPR = 0xCA;
RTC->WPR = 0x53;
}
TinyCLR_Result STM32F4_Rtc_WaitForSynchro() {
int32_t timeout = 0xFFFFFF;
/* Disable the write protection for RTC registers */
// RTC->WPR = 0xCA;
// RTC->WPR = 0x53;
STM32F4_Rtc_DisableWriteProtection();
/* Clear RSF flag */
RTC->ISR &= (uint32_t)RTC_RSF_MASK;
/* Wait the registers to be synchronised */
while (((RTC->ISR & RTC_ISR_RSF) == 0) && (timeout-- > 0));
/* Enable the write protection for RTC registers */
//RTC->WPR = 0xFF;
STM32F4_Rtc_EnableWriteProtection();
return timeout > 0 ? TinyCLR_Result::Success : TinyCLR_Result::InvalidOperation;
}
TinyCLR_Result STM32F4_Rtc_Configuration() {
/* Enable the PWR clock */
RCC->APB1ENR |= RCC_APB1ENR_PWREN;
/* Allow access to RTC */
*(reinterpret_cast<uint32_t *>(CR_DBP_BB)) = 1;
/* Enable the LSE OSC */
/* Reset LSEON bit */
*(reinterpret_cast<uint32_t *>(BDCR_ADDRESS)) = RCC_LSE_OFF;
/* Reset LSEBYP bit */
*(reinterpret_cast<uint32_t *>(BDCR_ADDRESS)) = RCC_LSE_OFF;
/* Set LSEON bit */
*(reinterpret_cast<uint32_t *>(BDCR_ADDRESS)) = RCC_LSE_ON;
/* Wait till LSE is ready */
uint32_t flag_mask = RCC_FLAG_LSERDY & RCC_FLAG_MASK;
uint32_t status_reg = RCC->BDCR;
int timeout = 0xFFFFFF;
while ((status_reg & ((uint32_t)1 << flag_mask)) == (uint32_t)RESET && timeout-- > 0) {
status_reg = RCC->BDCR;
}
if (timeout == 0) {
return TinyCLR_Result::InvalidOperation;
}
/* Select the RTC Clock Source */
RCC->BDCR |= (RCC_RTCCLKSource_LSE & 0x00000FFF);
/* Enable the RTC Clock */
*(reinterpret_cast<uint32_t *>(BDCR_RTCEN_BB)) = 1;
/* Wait for RTC APB registers synchronisation */
return STM32F4_Rtc_WaitForSynchro();
}
TinyCLR_Result STM32F4_Rtc_Initialize() {
/* Disable the write protection for RTC registers */
//RTC->WPR = 0xCA;
//RTC->WPR = 0x53;
STM32F4_Rtc_DisableWriteProtection();
if (STM32F4_Rtc_EnterInitializeMode() != TinyCLR_Result::Success)
return TinyCLR_Result::InvalidOperation;
/* Clear RTC CR FMT Bit */
RTC->CR &= ((uint32_t)~(RTC_CR_FMT));
/* Set RTC_CR register */
RTC->CR |= ((uint32_t)(RTC_HourFormat_24));
/* Configure the RTC PRER */
RTC->PRER = (uint32_t)(0xFF);
RTC->PRER |= (uint32_t)(0x7F << 16);
/* Exit Initialization mode */
STM32F4_Rtc_ExitInitializeMode();
/* Enable the write protection for RTC registers */
//RTC->WPR = 0xFF;
STM32F4_Rtc_EnableWriteProtection();
return TinyCLR_Result::Success;
}
uint32_t STM32F4_Rtc_ReadBackupRegister() {
/* Read the specified register */
return (*(reinterpret_cast<uint32_t *>(RTC_BASE + 0x50 + (RTC_BKP_DR0 * 4))));
}
void STM32F4_Rtc_WriteBackupRegister(uint32_t value) {
/* Write the specified register */
*(reinterpret_cast<uint32_t *>(RTC_BASE + 0x50 + (RTC_BKP_DR0 * 4))) = value;
}
TinyCLR_Result STM32F4_Rtc_Acquire(const TinyCLR_Rtc_Provider* self) {
if (STM32F4_Rtc_ReadBackupRegister() == RTC_BKP_VALUE) {
}
if (STM32F4_Rtc_Configuration() != TinyCLR_Result::Success)
return TinyCLR_Result::InvalidOperation;
if (STM32F4_Rtc_Initialize() != TinyCLR_Result::Success)
return TinyCLR_Result::InvalidOperation;
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F4_Rtc_Release(const TinyCLR_Rtc_Provider* self) {
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F4_Rtc_GetNow(const TinyCLR_Rtc_Provider* self, TinyCLR_Rtc_DateTime& value) {
uint32_t time;
uint32_t date;
// value.Year = 2010;
// value.Month = 2;
// value.DayOfYear = 33;
// value.DayOfMonth = 2;
// value.DayOfWeek = 0;
// value.Hour = 13;
// value.Minute = 14;
// value.Second = 15;
// value.Millisecond = 516;
/* Get the RTC_TR register */
time = (uint32_t)(RTC->TR & RTC_TR_RESERVED_MASK);
uint8_t hour = (uint8_t)((time & (RTC_TR_HT | RTC_TR_HU)) >> 16);
uint8_t minute = (uint8_t)((time & (RTC_TR_MNT | RTC_TR_MNU)) >> 8);
uint8_t second = (uint8_t)(time & (RTC_TR_ST | RTC_TR_SU));
value.Hour = (uint8_t)STM32F4_Rtc_Bcd2ToByte(hour);
value.Minute = (uint8_t)STM32F4_Rtc_Bcd2ToByte(minute);
value.Second = (uint8_t)STM32F4_Rtc_Bcd2ToByte(second);
value.Millisecond = 0;
/* Get the RTC_TR register */
date = (uint32_t)(RTC->DR & RTC_DR_RESERVED_MASK);
uint8_t year = (uint8_t)((date & (RTC_DR_YT | RTC_DR_YU)) >> 16);
uint8_t month = (uint8_t)((date & (RTC_DR_MT | RTC_DR_MU)) >> 8);
uint8_t day_of_month = (uint8_t)(date & (RTC_DR_DT | RTC_DR_DU));
uint8_t day_of_week = (uint8_t)((date & (RTC_DR_WDU)) >> 13);
value.Year = (uint8_t)STM32F4_Rtc_Bcd2ToByte(year) + 1980;
value.Month = (uint8_t)STM32F4_Rtc_Bcd2ToByte(month);
value.DayOfMonth = (uint8_t)STM32F4_Rtc_Bcd2ToByte(day_of_month);
value.DayOfWeek = (uint8_t)STM32F4_Rtc_Bcd2ToByte(day_of_week);
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F4_Rtc_SetNow(const TinyCLR_Rtc_Provider* self, TinyCLR_Rtc_DateTime value) {
uint32_t time;
uint32_t date;
time = (uint32_t)(((uint32_t)STM32F4_Rtc_ByteToBcd2(value.Hour) << 16) | \
((uint32_t)STM32F4_Rtc_ByteToBcd2(value.Minute) << 8) | \
((uint32_t)STM32F4_Rtc_ByteToBcd2(value.Second)));
date = (((uint32_t)STM32F4_Rtc_ByteToBcd2(value.Year) << 16) | \
((uint32_t)STM32F4_Rtc_ByteToBcd2(value.Month) << 8) | \
((uint32_t)STM32F4_Rtc_ByteToBcd2(value.DayOfMonth)) | \
((uint32_t)value.DayOfWeek << 13));
/* Disable the write protection for RTC registers */
STM32F4_Rtc_DisableWriteProtection();
/* Set Initialization mode */
if (STM32F4_Rtc_EnterInitializeMode() != TinyCLR_Result::Success)
return TinyCLR_Result::InvalidOperation;
/* Set the RTC_TR register */
RTC->TR = (uint32_t)(time & RTC_TR_RESERVED_MASK);
/* Set the RTC_DR register */
RTC->DR = (uint32_t)(date & RTC_DR_RESERVED_MASK);
STM32F4_Rtc_ExitInitializeMode();
STM32F4_Rtc_WaitForSynchro();
/* Enable the write protection for RTC registers */
STM32F4_Rtc_EnableWriteProtection();
STM32F4_Rtc_WriteBackupRegister(RTC_BKP_VALUE);
return TinyCLR_Result::Success;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbKmzProductWriter.h"
namespace otb
{
namespace Wrapper
{
namespace Functor
{
template< class TScalar >
class ITK_EXPORT LogFunctor
{
public:
LogFunctor(){};
~LogFunctor(){};
TScalar operator() (const TScalar& v) const
{
return vcl_log(v);
}
};
} // end namespace Functor
class KmzExport : public Application
{
public:
/** Standard class typedefs. */
typedef KmzExport Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(KmzExport, otb::Application);
private:
KmzExport()
{
SetName("KmzExport");
SetDescription("Export the input image in a KMZ product.");
// Documentation
SetDocName("Image to KMZ Export Application");
SetDocLongDescription("This application exports the input image in a kmz product that can be display in the Google Earth software. The user can set the size of the product size, a logo and a legend to the product. Furthemore, to obtain a product that fits the relief, a DEM can be used.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Convertion");
SetDocCLExample("otbApplicationLauncherCommandLine KmzExport ${OTB-BIN}/bin --in ${OTB-Data}/Input/qb_RoadExtract.img --out otbKmzExport --logo ${OTB-Data}/Input/cnes.png ${OTB-Data}/Input/otb_big.png");
AddDocTag("KMZ");
AddDocTag("Export");
}
virtual ~KmzExport()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_Filename, "out", "Output .kmz product");
SetParameterDescription("out", "Output Kmz product directory (with .kmz extension)");
AddParameter(ParameterType_Int, "tilesize", "Tile Size");
SetParameterDescription("tilesize", "Size of the tiles in the kmz product, in number of pixels.");
MandatoryOff("tilesize");
AddParameter(ParameterType_InputImage, "logo", "Image logo");
SetParameterDescription("logo", "Path to the image logo to add to the KMZ product.");
MandatoryOff("logo");
AddParameter(ParameterType_InputImage, "legend", "Image legend");
SetParameterDescription("legend", "Path to the image legend to add to the KMZ product.");
MandatoryOff("legend");
AddParameter(ParameterType_Directory, "dem", "DEM directory");
SetParameterDescription("dem", "Path to the directory that contains elevation information.");
MandatoryOff("dem");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
typedef otb::KmzProductWriter<FloatVectorImageType> KmzProductWriterType;
// Second part : Image To Kmz
KmzProductWriterType::Pointer kmzWriter = KmzProductWriterType::New();
kmzWriter->SetInput( this->GetParameterImage("in") );
kmzWriter->SetPath( this->GetParameterString("out") );
// Use DEM if any
if( this->HasValue("dem") )
{
kmzWriter->SetDEMDirectory(this->GetParameterString("dem"));
}
// If the tile size is set
if( this->HasValue("tilesize") )
{
kmzWriter->SetTileSize( this->GetParameterInt("tilesize") );
}
// Add the logo if any
if( this->HasValue("logo") )
{
kmzWriter->SetLogo( this->GetParameterImage("logo") );
}
// Add the legend if any
if( this->HasValue("legend") )
{
kmzWriter->AddLegend( this->GetParameterImage("legend") );
}
// trigger the writing
kmzWriter->Update();
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::KmzExport)
/*
namespace otb
{
int KmzExport::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("KmzExport");
descriptor->SetDescription("Export the input image as Kmz");
descriptor->AddInputImage();
descriptor->AddOption("OutputProductName", "Output Kmz product", "kmz", 1, true,
ApplicationDescriptor::InputImage);
descriptor->AddOption("TileSize", "Set the size of the tiles", "s", 1, false,
ApplicationDescriptor::Integer);
descriptor->AddOption("LogoImage", "Add a logo to the final Kmz", "lo", 1, false,
ApplicationDescriptor::FileName);
descriptor->AddOption("LegendImage", "Add a legend to the image exported", "le", 1,
false, ApplicationDescriptor::FileName);
return EXIT_SUCCESS;
}
int KmzExport::Execute(otb::ApplicationOptionsResult* parseResult)
{
typedef otb::VectorImage<float, 2> ImageType;
typedef otb::KmzProductWriter<ImageType> KmzProductWriterType;
typedef otb::ImageFileReader<ImageType> ReaderType;
// Instanciate reader
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(parseResult->GetInputImage());
reader->UpdateOutputInformation();
// Second part : Image To Kmz
KmzProductWriterType::Pointer kmzWriter = KmzProductWriterType::New();
kmzWriter->SetInput(reader->GetOutput());
kmzWriter->SetPath(parseResult->GetParameterString("OutputProductName"));
// If the tilesize is set
if(parseResult->IsOptionPresent("TileSize"))
{
kmzWriter->SetTileSize(parseResult->GetParameterUInt("TileSize"));
}
// Read the logo if any
if(parseResult->IsOptionPresent("LogoImage"))
{
ReaderType::Pointer logoReader = ReaderType::New();
logoReader->SetFileName(parseResult->GetParameterString("LogoImage"));
logoReader->Update();
kmzWriter->SetLogo(logoReader->GetOutput());
}
// Read the legend if any
if(parseResult->IsOptionPresent("LegendImage"))
{
ReaderType::Pointer legendReader = ReaderType::New();
legendReader->SetFileName(parseResult->GetParameterString("LegendImage"));
legendReader->Update();
kmzWriter->AddLegend("Input Legend", legendReader->GetOutput());
kmzWriter->AddLegend(legendReader->GetOutput());
}
// trigger the writing
kmzWriter->Update();
return EXIT_SUCCESS;
}
}
*/
<commit_msg>STYLE<commit_after>/*=========================================================================
Program: ORFEO Toolbox
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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbKmzProductWriter.h"
namespace otb
{
namespace Wrapper
{
class KmzExport : public Application
{
public:
/** Standard class typedefs. */
typedef KmzExport Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(KmzExport, otb::Application);
private:
KmzExport()
{
SetName("KmzExport");
SetDescription("Export the input image in a KMZ product.");
// Documentation
SetDocName("Image to KMZ Export Application");
SetDocLongDescription("This application exports the input image in a kmz product that can be display in the Google Earth software. The user can set the size of the product size, a logo and a legend to the product. Furthemore, to obtain a product that fits the relief, a DEM can be used.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Convertion");
SetDocCLExample("otbApplicationLauncherCommandLine KmzExport ${OTB-BIN}/bin --in ${OTB-Data}/Input/qb_RoadExtract.img --out otbKmzExport.kmz --logo ${OTB-Data}/Input/cnes.png ${OTB-Data}/Input/otb_big.png");
AddDocTag("KMZ");
AddDocTag("Export");
}
virtual ~KmzExport()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_Filename, "out", "Output .kmz product");
SetParameterDescription("out", "Output Kmz product directory (with .kmz extension)");
AddParameter(ParameterType_Int, "tilesize", "Tile Size");
SetParameterDescription("tilesize", "Size of the tiles in the kmz product, in number of pixels.");
MandatoryOff("tilesize");
AddParameter(ParameterType_InputImage, "logo", "Image logo");
SetParameterDescription("logo", "Path to the image logo to add to the KMZ product.");
MandatoryOff("logo");
AddParameter(ParameterType_InputImage, "legend", "Image legend");
SetParameterDescription("legend", "Path to the image legend to add to the KMZ product.");
MandatoryOff("legend");
AddParameter(ParameterType_Directory, "dem", "DEM directory");
SetParameterDescription("dem", "Path to the directory that contains elevation information.");
MandatoryOff("dem");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
typedef otb::KmzProductWriter<FloatVectorImageType> KmzProductWriterType;
// Second part : Image To Kmz
KmzProductWriterType::Pointer kmzWriter = KmzProductWriterType::New();
kmzWriter->SetInput( this->GetParameterImage("in") );
kmzWriter->SetPath( this->GetParameterString("out") );
// Use DEM if any
if( this->HasValue("dem") )
{
kmzWriter->SetDEMDirectory(this->GetParameterString("dem"));
}
// If the tile size is set
if( this->HasValue("tilesize") )
{
kmzWriter->SetTileSize( this->GetParameterInt("tilesize") );
}
// Add the logo if any
if( this->HasValue("logo") )
{
kmzWriter->SetLogo( this->GetParameterImage("logo") );
}
// Add the legend if any
if( this->HasValue("legend") )
{
kmzWriter->AddLegend( this->GetParameterImage("legend") );
}
// trigger the writing
kmzWriter->Update();
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::KmzExport)
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/breakpad_win.h"
#include <windows.h>
#include <tchar.h>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/file_version_info.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/google_update_client.h"
#include "chrome/app/hard_error_handler_win.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/google_update_settings.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
namespace {
const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
// This is the well known SID for the system principal.
const wchar_t kSystemPrincipalSid[] =L"S-1-5-18";
google_breakpad::ExceptionHandler* g_breakpad = NULL;
std::vector<wchar_t*>* url_chunks = NULL;
// Dumps the current process memory.
extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
if (g_breakpad)
g_breakpad->WriteMinidump();
}
// Returns the custom info structure based on the dll in parameter and the
// process type.
static google_breakpad::CustomClientInfo* custom_info = NULL;
google_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& dll_path,
const std::wstring& type) {
scoped_ptr<FileVersionInfo>
version_info(FileVersionInfo::CreateFileVersionInfo(dll_path));
std::wstring version, product;
if (version_info.get()) {
// Get the information from the file.
product = version_info->product_short_name();
version = version_info->product_version();
if (!version_info->is_official_build())
version.append(L"-devel");
} else {
// No version info found. Make up the values.
product = L"Chrome";
version = L"0.0.0.0-devel";
}
google_breakpad::CustomInfoEntry ver_entry(L"ver", version.c_str());
google_breakpad::CustomInfoEntry prod_entry(L"prod", product.c_str());
google_breakpad::CustomInfoEntry plat_entry(L"plat", L"Win32");
google_breakpad::CustomInfoEntry type_entry(L"ptype", type.c_str());
if (type == L"renderer") {
// If we're a renderer create entries for the URL. Currently we only allow
// each chunk to be 64 characters, which isn't enough for a URL. As a hack
// we create 8 entries and split the URL across the entries.
google_breakpad::CustomInfoEntry url1(L"url-chunk-1", L"");
google_breakpad::CustomInfoEntry url2(L"url-chunk-2", L"");
google_breakpad::CustomInfoEntry url3(L"url-chunk-3", L"");
google_breakpad::CustomInfoEntry url4(L"url-chunk-4", L"");
google_breakpad::CustomInfoEntry url5(L"url-chunk-5", L"");
google_breakpad::CustomInfoEntry url6(L"url-chunk-6", L"");
google_breakpad::CustomInfoEntry url7(L"url-chunk-7", L"");
google_breakpad::CustomInfoEntry url8(L"url-chunk-8", L"");
static google_breakpad::CustomInfoEntry entries[] =
{ ver_entry, prod_entry, plat_entry, type_entry, url1, url2, url3,
url4, url5, url6, url7, url8 };
std::vector<wchar_t*>* tmp_url_chunks = new std::vector<wchar_t*>(8);
for (size_t i = 0; i < 8; ++i)
(*tmp_url_chunks)[i] = entries[4 + i].value;
url_chunks = tmp_url_chunks;
static google_breakpad::CustomClientInfo custom_info = {entries,
arraysize(entries)};
return &custom_info;
}
static google_breakpad::CustomInfoEntry entries[] = {ver_entry,
prod_entry,
plat_entry,
type_entry};
static google_breakpad::CustomClientInfo custom_info = {entries,
arraysize(entries)};
return &custom_info;
}
// Contains the information needed by the worker thread.
struct CrashReporterInfo {
google_breakpad::CustomClientInfo* custom_info;
std::wstring dll_path;
std::wstring process_type;
};
// This callback is executed when the browser process has crashed, after
// the crash dump has been created. We need to minimize the amount of work
// done here since we have potentially corrupted process. Our job is to
// spawn another instance of chrome which will show a 'chrome has crashed'
// dialog. This code needs to live in the exe and thus has no access to
// facilities such as the i18n helpers.
bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
EXCEPTION_POINTERS* ex_info,
MDRawAssertionInfo*, bool) {
// If the exception is because there was a problem loading a delay-loaded
// module, then show the user a dialog explaining the problem and then exit.
if (DelayLoadFailureExceptionMessageBox(ex_info))
return true;
// We set CHROME_CRASHED env var. If the CHROME_RESTART is present.
// This signals the child process to show the 'chrome has crashed' dialog.
if (!::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0))
return true;
::SetEnvironmentVariableW(env_vars::kShowRestart, L"1");
// Now we just start chrome browser with the same command line.
STARTUPINFOW si = {sizeof(si)};
PROCESS_INFORMATION pi;
if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
}
// After this return we will be terminated. The actual return value is
// not used at all.
return true;
}
// Previous unhandled filter. Will be called if not null when we
// intercept a crash.
LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
// Exception filter used when breakpad is not enabled. We just display
// the "Do you want to restart" message and then we call the previous filter.
long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
if (previous_filter)
return previous_filter(info);
return EXCEPTION_EXECUTE_HANDLER;
}
extern "C" void __declspec(dllexport) __cdecl SetActiveRendererURL(
const wchar_t* url_cstring) {
DCHECK(url_cstring);
if (!url_chunks)
return;
std::wstring url(url_cstring);
size_t num_chunks = url_chunks->size();
size_t chunk_index = 0;
size_t url_size = url.size();
// Split the url across all the chunks.
for (size_t url_offset = 0;
chunk_index < num_chunks && url_offset < url_size; ++chunk_index) {
size_t current_chunk_size = std::min(url_size - url_offset,
static_cast<size_t>(
google_breakpad::CustomInfoEntry::kValueMaxLength - 1));
url._Copy_s((*url_chunks)[chunk_index],
google_breakpad::CustomInfoEntry::kValueMaxLength,
current_chunk_size, url_offset);
(*url_chunks)[chunk_index][current_chunk_size] = L'\0';
url_offset += current_chunk_size;
}
// And null terminate any unneeded chunks.
for (; chunk_index < num_chunks; ++chunk_index)
(*url_chunks)[chunk_index][0] = L'\0';
}
} // namespace
// This function is executed by the child process that DumpDoneCallback()
// spawned and basically just shows the 'chrome has crashed' dialog if
// the CHROME_CRASHED environment variable is present.
bool ShowRestartDialogIfCrashed(bool* exit_now) {
if (!::GetEnvironmentVariableW(env_vars::kShowRestart, NULL, 0))
return false;
DWORD len = ::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0);
if (!len)
return true;
// We wrap the call to MessageBoxW with a SEH handler because it some
// machines with CursorXP, PeaDict or with FontExplorer installed it crashes
// uncontrollably here. Being this a best effort deal we better go away.
#pragma warning(push)
#pragma warning(disable:4509) // warning: SEH used but dlg_strings has a dtor.
__try {
wchar_t* restart_data = new wchar_t[len + 1];
::GetEnvironmentVariableW(env_vars::kRestartInfo, restart_data, len);
restart_data[len] = 0;
// The CHROME_RESTART var contains the dialog strings separated by '|'.
// See PrepareRestartOnCrashEnviroment() function for details.
std::vector<std::wstring> dlg_strings;
SplitString(restart_data, L'|', &dlg_strings);
delete[] restart_data;
if (dlg_strings.size() < 3)
return true;
// If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
// flags so that an RTL message box is displayed.
UINT flags = MB_OKCANCEL | MB_ICONWARNING;
if (dlg_strings[2] == env_vars::kRtlLocale)
flags |= MB_RIGHT | MB_RTLREADING;
// Show the dialog now. It is ok if another chrome is started by the
// user since we have not initialized the databases.
*exit_now = (IDOK != ::MessageBoxW(NULL, dlg_strings[1].c_str(),
dlg_strings[0].c_str(), flags));
} __except(EXCEPTION_EXECUTE_HANDLER) {
// Its not safe to continue executing, exit silently here.
::ExitProcess(ResultCodes::RESPAWN_FAILED);
}
#pragma warning(pop)
return true;
}
static DWORD __stdcall InitCrashReporterThread(void* param) {
CrashReporterInfo* info = reinterpret_cast<CrashReporterInfo*>(param);
// GetCustomInfo can take a few milliseconds to get the file information, so
// we do it here so it can run in a separate thread.
info->custom_info = GetCustomInfo(info->dll_path, info->process_type);
const CommandLine& command = *CommandLine::ForCurrentProcess();
bool full_dump = command.HasSwitch(switches::kFullMemoryCrashReport);
bool use_crash_service = command.HasSwitch(switches::kNoErrorDialogs) ||
GetEnvironmentVariable(L"CHROME_HEADLESS", NULL, 0);
google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
if (info->process_type == L"browser") {
// We install the post-dump callback only for the browser process. It
// spawns a new browser process.
callback = &DumpDoneCallback;
}
std::wstring pipe_name;
if (use_crash_service) {
// Crash reporting is done by crash_service.exe.
pipe_name = kChromePipeName;
} else {
// We want to use the Google Update crash reporting. We need to check if the
// user allows it first.
if (!GoogleUpdateSettings::GetCollectStatsConsent()) {
// The user did not allow Google Update to send crashes, we need to use
// our default crash handler instead, but only for the browser process.
if (callback)
InitDefaultCrashCallback();
return 0;
}
// Build the pipe name. It can be either:
// System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
// Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
std::wstring user_sid;
if (InstallUtil::IsPerUserInstall(info->dll_path.c_str())) {
if (!win_util::GetUserSidString(&user_sid)) {
delete info;
return -1;
}
} else {
user_sid = kSystemPrincipalSid;
}
pipe_name = kGoogleUpdatePipeName;
pipe_name += user_sid;
}
// Get the alternate dump directory. We use the temp path.
wchar_t temp_dir[MAX_PATH] = {0};
::GetTempPathW(MAX_PATH, temp_dir);
MINIDUMP_TYPE dump_type = full_dump ? MiniDumpWithFullMemory : MiniDumpNormal;
g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, NULL, callback,
NULL, google_breakpad::ExceptionHandler::HANDLER_ALL,
dump_type, pipe_name.c_str(), info->custom_info);
if (!g_breakpad->IsOutOfProcess()) {
// The out-of-process handler is unavailable.
::SetEnvironmentVariable(env_vars::kNoOOBreakpad,
info->process_type.c_str());
} else {
// Tells breakpad to handle breakpoint and single step exceptions.
// This might break JIT debuggers, but at least it will always
// generate a crashdump for these exceptions.
g_breakpad->set_handle_debug_exceptions(true);
}
delete info;
return 0;
}
void InitDefaultCrashCallback() {
previous_filter = SetUnhandledExceptionFilter(ChromeExceptionFilter);
}
void InitCrashReporterWithDllPath(const std::wstring& dll_path) {
const CommandLine& command = *CommandLine::ForCurrentProcess();
if (!command.HasSwitch(switches::kDisableBreakpad)) {
// Disable the message box for assertions.
_CrtSetReportMode(_CRT_ASSERT, 0);
// Query the custom_info now because if we do it in the thread it's going to
// fail in the sandbox. The thread will delete this object.
CrashReporterInfo* info = new CrashReporterInfo;
info->process_type = command.GetSwitchValue(switches::kProcessType);
if (info->process_type.empty())
info->process_type = L"browser";
info->dll_path = dll_path;
// If this is not the browser, we can't be sure that we will be able to
// initialize the crash_handler in another thread, so we run it right away.
// This is important to keep the thread for the browser process because
// it may take some times to initialize the crash_service process. We use
// the Windows worker pool to make better reuse of the thread.
if (info->process_type != L"browser") {
InitCrashReporterThread(info);
} else {
if (QueueUserWorkItem(
&InitCrashReporterThread, info, WT_EXECUTELONGFUNCTION) == 0) {
// We failed to queue to the worker pool, initialize in this thread.
InitCrashReporterThread(info);
}
}
}
}
<commit_msg>Adding chrome start-up parameters to information passed back in breakpad crash - we collect the first two params : switch-1 and switch-2 - up to 64 chars, then it truncates<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/breakpad_win.h"
#include <windows.h>
#include <shellapi.h>
#include <tchar.h>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/file_version_info.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/google_update_client.h"
#include "chrome/app/hard_error_handler_win.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/google_update_settings.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
namespace {
const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
// This is the well known SID for the system principal.
const wchar_t kSystemPrincipalSid[] =L"S-1-5-18";
google_breakpad::ExceptionHandler* g_breakpad = NULL;
std::vector<wchar_t*>* g_url_chunks = NULL;
// Dumps the current process memory.
extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
if (g_breakpad)
g_breakpad->WriteMinidump();
}
// Reduces the size of the string |str| to a max of 64 chars. Required because
// breakpad's CustomInfoEntry raises an invalid_parameter error if the string
// we want to set is longer.
std::wstring TrimToBreakpadMax(const std::wstring& str) {
std::wstring shorter(str);
return shorter.substr(0,
google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
}
// Returns the custom info structure based on the dll in parameter and the
// process type.
static google_breakpad::CustomClientInfo* custom_info = NULL;
google_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& dll_path,
const std::wstring& type) {
scoped_ptr<FileVersionInfo>
version_info(FileVersionInfo::CreateFileVersionInfo(dll_path));
std::wstring version, product;
if (version_info.get()) {
// Get the information from the file.
product = version_info->product_short_name();
version = version_info->product_version();
if (!version_info->is_official_build())
version.append(L"-devel");
} else {
// No version info found. Make up the values.
product = L"Chrome";
version = L"0.0.0.0-devel";
}
// Common entries.
google_breakpad::CustomInfoEntry ver_entry(L"ver", version.c_str());
google_breakpad::CustomInfoEntry prod_entry(L"prod", product.c_str());
google_breakpad::CustomInfoEntry plat_entry(L"plat", L"Win32");
google_breakpad::CustomInfoEntry type_entry(L"ptype", type.c_str());
if (type == L"renderer") {
// If we're a renderer create entries for the URL. Currently we only allow
// each chunk to be 64 characters, which isn't enough for a URL. As a hack
// we create 8 entries and split the URL across the entries.
google_breakpad::CustomInfoEntry url1(L"url-chunk-1", L"");
google_breakpad::CustomInfoEntry url2(L"url-chunk-2", L"");
google_breakpad::CustomInfoEntry url3(L"url-chunk-3", L"");
google_breakpad::CustomInfoEntry url4(L"url-chunk-4", L"");
google_breakpad::CustomInfoEntry url5(L"url-chunk-5", L"");
google_breakpad::CustomInfoEntry url6(L"url-chunk-6", L"");
google_breakpad::CustomInfoEntry url7(L"url-chunk-7", L"");
google_breakpad::CustomInfoEntry url8(L"url-chunk-8", L"");
static google_breakpad::CustomInfoEntry entries[] =
{ ver_entry, prod_entry, plat_entry, type_entry,
url1, url2, url3, url4, url5, url6, url7, url8 };
std::vector<wchar_t*>* tmp_url_chunks = new std::vector<wchar_t*>(8);
for (size_t i = 0; i < 8; ++i)
(*tmp_url_chunks)[i] = entries[4 + i].value;
g_url_chunks = tmp_url_chunks;
static google_breakpad::CustomClientInfo custom_info_renderer
= {entries, arraysize(entries)};
return &custom_info_renderer;
}
// Browser-specific entries.
google_breakpad::CustomInfoEntry switch1(L"switch-1", L"");
google_breakpad::CustomInfoEntry switch2(L"switch-2", L"");
// Get the first two command line switches if they exist. The CommandLine
// class does not allow to enumerate the switches so we do it by hand.
int num_args = 0;
wchar_t** args = ::CommandLineToArgvW(::GetCommandLineW(), &num_args);
if (args) {
if (num_args > 1)
switch1.set_value(TrimToBreakpadMax(args[1]).c_str());
if (num_args > 2)
switch2.set_value(TrimToBreakpadMax(args[2]).c_str());
}
static google_breakpad::CustomInfoEntry entries[] =
{ver_entry, prod_entry, plat_entry, type_entry, switch1, switch2};
static google_breakpad::CustomClientInfo custom_info_browser =
{entries, arraysize(entries)};
return &custom_info_browser;
}
// Contains the information needed by the worker thread.
struct CrashReporterInfo {
google_breakpad::CustomClientInfo* custom_info;
std::wstring dll_path;
std::wstring process_type;
};
// This callback is executed when the browser process has crashed, after
// the crash dump has been created. We need to minimize the amount of work
// done here since we have potentially corrupted process. Our job is to
// spawn another instance of chrome which will show a 'chrome has crashed'
// dialog. This code needs to live in the exe and thus has no access to
// facilities such as the i18n helpers.
bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
EXCEPTION_POINTERS* ex_info,
MDRawAssertionInfo*, bool) {
// If the exception is because there was a problem loading a delay-loaded
// module, then show the user a dialog explaining the problem and then exit.
if (DelayLoadFailureExceptionMessageBox(ex_info))
return true;
// We set CHROME_CRASHED env var. If the CHROME_RESTART is present.
// This signals the child process to show the 'chrome has crashed' dialog.
if (!::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0))
return true;
::SetEnvironmentVariableW(env_vars::kShowRestart, L"1");
// Now we just start chrome browser with the same command line.
STARTUPINFOW si = {sizeof(si)};
PROCESS_INFORMATION pi;
if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
}
// After this return we will be terminated. The actual return value is
// not used at all.
return true;
}
// Previous unhandled filter. Will be called if not null when we
// intercept a crash.
LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
// Exception filter used when breakpad is not enabled. We just display
// the "Do you want to restart" message and then we call the previous filter.
long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
if (previous_filter)
return previous_filter(info);
return EXCEPTION_EXECUTE_HANDLER;
}
extern "C" void __declspec(dllexport) __cdecl SetActiveRendererURL(
const wchar_t* url_cstring) {
DCHECK(url_cstring);
if (!g_url_chunks)
return;
std::wstring url(url_cstring);
size_t num_chunks = g_url_chunks->size();
size_t chunk_index = 0;
size_t url_size = url.size();
// Split the url across all the chunks.
for (size_t url_offset = 0;
chunk_index < num_chunks && url_offset < url_size; ++chunk_index) {
size_t current_chunk_size = std::min(url_size - url_offset,
static_cast<size_t>(
google_breakpad::CustomInfoEntry::kValueMaxLength - 1));
url._Copy_s((*g_url_chunks)[chunk_index],
google_breakpad::CustomInfoEntry::kValueMaxLength,
current_chunk_size, url_offset);
(*g_url_chunks)[chunk_index][current_chunk_size] = L'\0';
url_offset += current_chunk_size;
}
// And null terminate any unneeded chunks.
for (; chunk_index < num_chunks; ++chunk_index)
(*g_url_chunks)[chunk_index][0] = L'\0';
}
} // namespace
// This function is executed by the child process that DumpDoneCallback()
// spawned and basically just shows the 'chrome has crashed' dialog if
// the CHROME_CRASHED environment variable is present.
bool ShowRestartDialogIfCrashed(bool* exit_now) {
if (!::GetEnvironmentVariableW(env_vars::kShowRestart, NULL, 0))
return false;
DWORD len = ::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0);
if (!len)
return true;
// We wrap the call to MessageBoxW with a SEH handler because it some
// machines with CursorXP, PeaDict or with FontExplorer installed it crashes
// uncontrollably here. Being this a best effort deal we better go away.
#pragma warning(push)
#pragma warning(disable:4509) // warning: SEH used but dlg_strings has a dtor.
__try {
wchar_t* restart_data = new wchar_t[len + 1];
::GetEnvironmentVariableW(env_vars::kRestartInfo, restart_data, len);
restart_data[len] = 0;
// The CHROME_RESTART var contains the dialog strings separated by '|'.
// See PrepareRestartOnCrashEnviroment() function for details.
std::vector<std::wstring> dlg_strings;
SplitString(restart_data, L'|', &dlg_strings);
delete[] restart_data;
if (dlg_strings.size() < 3)
return true;
// If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
// flags so that an RTL message box is displayed.
UINT flags = MB_OKCANCEL | MB_ICONWARNING;
if (dlg_strings[2] == env_vars::kRtlLocale)
flags |= MB_RIGHT | MB_RTLREADING;
// Show the dialog now. It is ok if another chrome is started by the
// user since we have not initialized the databases.
*exit_now = (IDOK != ::MessageBoxW(NULL, dlg_strings[1].c_str(),
dlg_strings[0].c_str(), flags));
} __except(EXCEPTION_EXECUTE_HANDLER) {
// Its not safe to continue executing, exit silently here.
::ExitProcess(ResultCodes::RESPAWN_FAILED);
}
#pragma warning(pop)
return true;
}
static DWORD __stdcall InitCrashReporterThread(void* param) {
CrashReporterInfo* info = reinterpret_cast<CrashReporterInfo*>(param);
// GetCustomInfo can take a few milliseconds to get the file information, so
// we do it here so it can run in a separate thread.
info->custom_info = GetCustomInfo(info->dll_path, info->process_type);
const CommandLine& command = *CommandLine::ForCurrentProcess();
bool full_dump = command.HasSwitch(switches::kFullMemoryCrashReport);
bool use_crash_service = command.HasSwitch(switches::kNoErrorDialogs) ||
GetEnvironmentVariable(L"CHROME_HEADLESS", NULL, 0);
google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
if (info->process_type == L"browser") {
// We install the post-dump callback only for the browser process. It
// spawns a new browser process.
callback = &DumpDoneCallback;
}
std::wstring pipe_name;
if (use_crash_service) {
// Crash reporting is done by crash_service.exe.
pipe_name = kChromePipeName;
} else {
// We want to use the Google Update crash reporting. We need to check if the
// user allows it first.
if (!GoogleUpdateSettings::GetCollectStatsConsent()) {
// The user did not allow Google Update to send crashes, we need to use
// our default crash handler instead, but only for the browser process.
if (callback)
InitDefaultCrashCallback();
return 0;
}
// Build the pipe name. It can be either:
// System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
// Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
std::wstring user_sid;
if (InstallUtil::IsPerUserInstall(info->dll_path.c_str())) {
if (!win_util::GetUserSidString(&user_sid)) {
delete info;
return -1;
}
} else {
user_sid = kSystemPrincipalSid;
}
pipe_name = kGoogleUpdatePipeName;
pipe_name += user_sid;
}
// Get the alternate dump directory. We use the temp path.
wchar_t temp_dir[MAX_PATH] = {0};
::GetTempPathW(MAX_PATH, temp_dir);
MINIDUMP_TYPE dump_type = full_dump ? MiniDumpWithFullMemory : MiniDumpNormal;
g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, NULL, callback,
NULL, google_breakpad::ExceptionHandler::HANDLER_ALL,
dump_type, pipe_name.c_str(), info->custom_info);
if (!g_breakpad->IsOutOfProcess()) {
// The out-of-process handler is unavailable.
::SetEnvironmentVariable(env_vars::kNoOOBreakpad,
info->process_type.c_str());
} else {
// Tells breakpad to handle breakpoint and single step exceptions.
// This might break JIT debuggers, but at least it will always
// generate a crashdump for these exceptions.
g_breakpad->set_handle_debug_exceptions(true);
}
delete info;
return 0;
}
void InitDefaultCrashCallback() {
previous_filter = SetUnhandledExceptionFilter(ChromeExceptionFilter);
}
void InitCrashReporterWithDllPath(const std::wstring& dll_path) {
const CommandLine& command = *CommandLine::ForCurrentProcess();
if (!command.HasSwitch(switches::kDisableBreakpad)) {
// Disable the message box for assertions.
_CrtSetReportMode(_CRT_ASSERT, 0);
// Query the custom_info now because if we do it in the thread it's going to
// fail in the sandbox. The thread will delete this object.
CrashReporterInfo* info = new CrashReporterInfo;
info->process_type = command.GetSwitchValue(switches::kProcessType);
if (info->process_type.empty())
info->process_type = L"browser";
info->dll_path = dll_path;
// If this is not the browser, we can't be sure that we will be able to
// initialize the crash_handler in another thread, so we run it right away.
// This is important to keep the thread for the browser process because
// it may take some times to initialize the crash_service process. We use
// the Windows worker pool to make better reuse of the thread.
if (info->process_type != L"browser") {
InitCrashReporterThread(info);
} else {
if (QueueUserWorkItem(
&InitCrashReporterThread, info, WT_EXECUTELONGFUNCTION) == 0) {
// We failed to queue to the worker pool, initialize in this thread.
InitCrashReporterThread(info);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2013 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/IOConfig.h"
#include "mirtk/BaseImage.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
cout << "\n";
cout << "Usage: " << name << " <input>... <output> [options]\n";
cout << " " << name << " <input>... -output <output> [options]\n";
cout << " " << name << " [options]\n";
cout << "\n";
cout << "Description:\n";
cout << " Concatenate two or more either 2D images to form a 3D volume,\n";
cout << " or 3D volumes to form a 3D+t temporal sequence. All input images\n";
cout << " must have the same image attributes, except in either the third (2D)\n";
cout << " or the third and fourth (3D) image dimension.\n";
cout << "\n";
cout << "Optional arguments:\n";
cout << " -output <output> Output image file. Last positional argument if option missing.\n";
cout << " -image <input> Add one input image. Option can be given multiple times.\n";
cout << " -images <input>... Add one or more input images. Option can be given multiple times.\n";
cout << " -sort [on|off] Automatically determine correct order of input images\n";
cout << " based on the distance along the third or fourth image axis.\n";
cout << " -nosort Disable sorting of input images, same as :option:`-sort` off. (default)\n";
cout << " -start <float> Position of first slice/frame of output volume/sequence.\n";
cout << " -spacing <float> Slice/Temporal spacing of output volume/sequence.\n";
PrintStandardOptions(cout);
cout << "\n";
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
bool CheckOrientation(const ImageAttributes &a, const ImageAttributes &b)
{
if ((a._xaxis[0] * b._xaxis[0] + a._xaxis[1] * b._xaxis[1] + a._xaxis[2] * b._xaxis[2] - 1.0) > .001) return false;
if ((a._yaxis[0] * b._yaxis[0] + a._yaxis[1] * b._yaxis[1] + a._yaxis[2] * b._yaxis[2] - 1.0) > .001) return false;
if ((a._zaxis[0] * b._zaxis[0] + a._zaxis[1] * b._zaxis[1] + a._zaxis[2] * b._zaxis[2] - 1.0) > .001) return false;
return true;
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
// Parse arguments
REQUIRES_POSARGS(0);
Array<const char *> input_names;
for (int i = 1; i <= NUM_POSARGS; ++i) {
input_names.push_back(POSARG(i));
}
const char *output_name = nullptr;
bool sort_input = false;
double spacing = numeric_limits<double>::quiet_NaN();
double start = numeric_limits<double>::quiet_NaN();
for (ALL_OPTIONS) {
if (OPTION("-image")) input_names.push_back(ARGUMENT);
else if (OPTION("-images")) {
do {
input_names.push_back(ARGUMENT);
} while (HAS_ARGUMENT);
}
else if (OPTION("-output")) {
output_name = ARGUMENT;
}
else if (OPTION("-sort")) {
if (HAS_ARGUMENT) PARSE_ARGUMENT(sort_input);
else sort_input = true;
}
else if (OPTION("-nosort")) sort_input = false;
else if (OPTION("-spacing")) PARSE_ARGUMENT(spacing);
else if (OPTION("-start")) PARSE_ARGUMENT(start);
else HANDLE_COMMON_OR_UNKNOWN_OPTION();
}
if (!output_name) {
if (input_names.empty()) {
FatalError("No input images and -output file specified!");
}
output_name = input_names.back();
input_names.pop_back();
}
const int n = static_cast<int>(input_names.size());
if (n < 2) FatalError("Not enough input images given!");
InitializeIOLibrary();
// Get attributes of first input image
UniquePtr<BaseImage> ref(BaseImage::New(input_names[0]));
if (ref->T() > 1) {
FatalError("Input images must be either 2D (nz == 1) or 3D (nz == 1 and nt == 1)!");
}
const bool twod = (ref->Z() == 1);
// Sort input images
//
// Note: Images are not first read all at once into memory to
// not be limited by the amount of memory we have available.
// We better read in the images twice from disk if necessary.
Array<int> pos(n);
for (int i = 0; i < n; ++i) pos[i] = i;
if (sort_input) {
if (verbose) cout << "Sorting input images...", cout.flush();
// Compute distance to axis origin
Point p;
Array<double> origin(n);
if (twod) {
p = ref->GetOrigin();
ref->WorldToImage(p);
origin[0] = p._z;
} else {
origin[0] = ref->GetTOrigin();
}
for (int i = 1; i < n; ++i) {
UniquePtr<BaseImage> image(BaseImage::New(input_names[i]));
p = image->GetOrigin();
if (twod) {
Point p = image->GetOrigin();
ref->WorldToImage(p);
origin[i] = p._z;
} else {
origin[i] = image->GetTOrigin();
}
}
// Determine order of images sorted by ascending distance value
pos = IncreasingOrder(origin);
if (pos[0] != 0) ref.reset(BaseImage::New(input_names[pos[0]]));
if (verbose) cout << " done\n";
}
// Create output image
if (verbose) {
cout << "Making ";
if (twod) cout << "volume";
else cout << "sequence";
cout << " from " << n << " input images...";
}
ImageAttributes out_attr = ref->Attributes();
if (twod) out_attr._z = n; // spacing and origin set later below
else out_attr._t = n;
UniquePtr<BaseImage> output(BaseImage::New(ref->GetDataType()));
output->Initialize(out_attr);
// Concatenate images
double avg_spacing = 0.;
double min_zorigin = ref->GetOrigin()._z;
if (twod) {
avg_spacing = ref->GetZSize();
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, 0, 0, ref->GetAsDouble(i, j));
}
for (int k = 1; k < n; ++k) {
UniquePtr<BaseImage> image(BaseImage::New(input_names[pos[k]]));
if (image->Z() != 1 || image->T() != 1) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " is not 2D!");
}
if (image->X() != ref->X() || image->Y() != ref->Y()) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " has differing number of voxels!");
}
if (!fequal(image->GetXSize(), ref->GetXSize()) ||
!fequal(image->GetYSize(), ref->GetYSize())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " has differing voxel size!");
}
if (!fequal(image->GetTSize(), ref->GetTSize())) {
Warning("Input image " << k+1 << " has differing temporal spacing.");
}
if (!CheckOrientation(image->Attributes(), ref->Attributes())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " has different orientation!");
}
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, k, 0, image->GetAsDouble(i, j));
}
min_zorigin = min(min_zorigin, image->GetOrigin()._z);
avg_spacing += image->GetZSize();
}
} else {
avg_spacing = ref->GetTSize();
for (int k = 0; k < out_attr._z; ++k)
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, k, 0, ref->GetAsDouble(i, j, k));
}
for (int l = 1; l < n; ++l) {
UniquePtr<BaseImage> image(BaseImage::New(input_names[pos[l]]));
if (image->T() != 1) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " is not 3D!");
}
if (image->X() != ref->X() || image->Y() != ref->Y() || image->Z() != ref->Z()) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " has differing number of voxels!");
}
if (!fequal(image->GetXSize(), ref->GetXSize()) ||
!fequal(image->GetYSize(), ref->GetYSize()) ||
!fequal(image->GetZSize(), ref->GetZSize())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " has differing voxel size!");
}
if (!CheckOrientation(image->Attributes(), ref->Attributes())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " has different orientation!");
}
for (int k = 0; k < out_attr._z; ++k)
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, k, l, image->GetAsDouble(i, j, k));
}
avg_spacing += image->GetTSize();
}
}
// Set output spacing to average of input images by default
avg_spacing /= n;
if (IsNaN(spacing)) spacing = avg_spacing;
if (twod) {
if (spacing < .0) { // must be positive
out_attr._zaxis[0] *= -1.0;
out_attr._zaxis[1] *= -1.0;
out_attr._zaxis[2] *= -1.0;
spacing *= -1.0;
}
double dx, dy, dz;
output->GetPixelSize(dx, dy, dz);
output->PutPixelSize(dx, dy, spacing);
} else {
output->PutTSize(spacing); // can be negative
}
// Set output origin
if (twod) {
if (IsNaN(start)) start = min_zorigin;
Point origin = output->GetOrigin();
origin._z = start;
// Move to center of image stack, i.e. translate along z axis
double s = .5 * (n - 1) * output->ZSize();
origin._x += s * output->Attributes()._zaxis[0];
origin._y += s * output->Attributes()._zaxis[1];
origin._z += s * output->Attributes()._zaxis[2];
output->PutOrigin(origin);
} else {
if (!IsNaN(start)) out_attr._torigin = start;
// else torigin is time of first (sorted) input volume
}
if (verbose) cout << " done" << endl;
// Write output image
if (verbose) cout << "Writing concatenated images to " << output_name << "...";
output->Write(output_name);
if (verbose) cout << " done" << endl;
return 0;
}
<commit_msg>enh: combine-images -input option to insert/append slices to volume [Applications]<commit_after>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2017 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2017 Andreas Schuh
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/IOConfig.h"
#include "mirtk/BaseImage.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
cout << "\n";
cout << "Usage: " << name << " <input>... <output> [options]\n";
cout << " " << name << " <input>... -output <output> [options]\n";
cout << " " << name << " -input <volume> -image <slice> -output <volume> [options]\n";
cout << " " << name << " [options]\n";
cout << "\n";
cout << "Description:\n";
cout << " Concatenate two or more either 2D images to form a 3D volume,\n";
cout << " or 3D volumes to form a 3D+t temporal sequence. All input images\n";
cout << " must have the same image attributes, except in either the third (2D)\n";
cout << " or the third and fourth (3D) image dimension.\n";
cout << "\n";
cout << " Moreover, given an :option:`-input` volume (sequence), additional\n";
cout << " slices (volumes) can be appended to it. Note that when :option:`-sort`\n";
cout << " is enabled, the additional slices (volumes) can be interleaved with the\n";
cout << " existing volume (sequence), allowing inserting a slice (volume) anywhere\n";
cout << " not only after the last slice (volume) of the input volume (sequence).\n";
cout << "\n";
cout << " Note that the slice thickness of the output volume when concatenating slices\n";
cout << " is set equal the average slice thickness of the input images, unless it is\n";
cout << " overridden by the :option:`-spacing` value.\n";
cout << "\n";
cout << "Optional arguments:\n";
cout << " -input <file> Read input -images from given volume/sequence.\n";
cout << " -output <path> Output image file path. Last positional argument when option missing.\n";
cout << " -image <file> Add one input image. Option can be given multiple times.\n";
cout << " -images <file>... Add one or more input images. Option can be given multiple times.\n";
cout << " -sort [on|off] Automatically determine correct order of input images\n";
cout << " based on the distance along the third or fourth image axis.\n";
cout << " -nosort Disable sorting of input images, same as :option:`-sort` off. (default)\n";
cout << " -start <float> Position of first slice/frame of output volume/sequence.\n";
cout << " -spacing <float> Slice/Temporal spacing of output volume/sequence.\n";
PrintStandardOptions(cout);
cout << "\n";
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
BaseImage *GetRegion(const UniquePtr<BaseImage> &input, int i)
{
int i1 = 0, i2 = input->X();
int j1 = 0, j2 = input->Y();
int k1 = 0, k2 = input->Z();
int l1 = 0, l2 = 1;
if (input->T() > 1) {
l1 = i;
l2 = i + 1;
} else {
k1 = i;
k2 = i + 1;
}
BaseImage *region = nullptr;
input->GetRegion(region, i1, j1, k1, l1, i2, j2, k2, l2);
return region;
}
// -----------------------------------------------------------------------------
bool CheckOrientation(const ImageAttributes &a, const ImageAttributes &b)
{
if ((a._xaxis[0] * b._xaxis[0] + a._xaxis[1] * b._xaxis[1] + a._xaxis[2] * b._xaxis[2] - 1.0) > .001) return false;
if ((a._yaxis[0] * b._yaxis[0] + a._yaxis[1] * b._yaxis[1] + a._yaxis[2] * b._yaxis[2] - 1.0) > .001) return false;
if ((a._zaxis[0] * b._zaxis[0] + a._zaxis[1] * b._zaxis[1] + a._zaxis[2] * b._zaxis[2] - 1.0) > .001) return false;
return true;
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
// Parse arguments
REQUIRES_POSARGS(0);
Array<const char *> input_names;
for (int i = 1; i <= NUM_POSARGS; ++i) {
input_names.push_back(POSARG(i));
}
const char *input_name = nullptr;
const char *output_name = nullptr;
bool sort_input = false;
double spacing = NaN;
double start = NaN;
for (ALL_OPTIONS) {
if (OPTION("-image")) {
input_names.push_back(ARGUMENT);
}
else if (OPTION("-images")) {
do {
input_names.push_back(ARGUMENT);
} while (HAS_ARGUMENT);
}
else if (OPTION("-input")) {
input_name = ARGUMENT;
}
else if (OPTION("-output")) {
output_name = ARGUMENT;
}
else if (OPTION("-sort")) {
if (HAS_ARGUMENT) PARSE_ARGUMENT(sort_input);
else sort_input = true;
}
else if (OPTION("-nosort")) sort_input = false;
else if (OPTION("-spacing")) PARSE_ARGUMENT(spacing);
else if (OPTION("-start")) PARSE_ARGUMENT(start);
else HANDLE_COMMON_OR_UNKNOWN_OPTION();
}
if (!output_name) {
if (input_names.empty()) {
FatalError("No input images and -output file specified!");
}
output_name = input_names.back();
input_names.pop_back();
}
int twod = -1; // concatenate 0: volumes 1: slices
int m = 0; // sub-images coming from -input image
int n = static_cast<int>(input_names.size());
if (n < 1 || (!input_name && n < 2)) {
FatalError("Not enough input images given!");
}
InitializeIOLibrary();
UniquePtr<BaseImage> input;
if (input_name) {
input.reset(BaseImage::New(input_name));
if (input->T() > 1) {
m = input->T();
twod = 0;
} else {
m = input->Z();
twod = 1;
}
n += m;
}
// Get attributes of first input image
UniquePtr<BaseImage> ref;
if (input) {
ref.reset(GetRegion(input, 0));
} else {
ref.reset(BaseImage::New(input_names[0]));
if (ref->T() > 1) {
FatalError("Input images must be either 2D (nz == 1) or 3D (nz == 1 and nt == 1)!");
}
twod = (ref->Z() == 1 ? 1 : 0);
}
// Sort input images
//
// A negative one-based index is associated with the sub-images of the -input image.
// A positive zero-based index is associated with the (positional) -images.
//
// Note: Images are not first read all at once into memory to
// not be limited by the amount of memory we have available.
// We better read in the images twice from disk if necessary.
Array<int> pos(n);
for (int i = 0; i < m; ++i) pos[i] = - (i + 1);
for (int i = m; i < n; ++i) pos[i] = i - m;
if (sort_input) {
if (verbose) {
cout << "Sorting input images...";
cout.flush();
}
// Compute distance to axis origin
Point p;
Array<double> origin(n);
if (twod) {
p = ref->GetOrigin();
ref->WorldToImage(p);
origin[0] = p._z;
} else {
origin[0] = ref->GetTOrigin();
}
UniquePtr<BaseImage> image;
for (int i = 1; i < n; ++i) {
if (i < m) {
image.reset(GetRegion(input, i));
} else {
image.reset(BaseImage::New(input_names[i]));
}
p = image->GetOrigin();
if (twod) {
Point p = image->GetOrigin();
ref->WorldToImage(p);
origin[i] = p._z;
} else {
origin[i] = image->GetTOrigin();
}
}
image.reset();
// Determine order of images sorted by ascending distance value
const int refpos = pos[0];
pos = IncreasingOrder(origin);
if (pos[0] != refpos) {
if (pos[0] < 0) {
ref.reset(GetRegion(input, -pos[0] - 1));
} else {
ref.reset(BaseImage::New(input_names[pos[0]]));
}
}
if (verbose) {
cout << " done\n";
}
}
// Create output image
if (verbose) {
cout << "Making ";
if (twod) cout << "volume";
else cout << "sequence";
cout << " from " << n << " images";
if (m > 0) {
cout << ", including " << m << " ";
if (twod) cout << "slice";
else cout << "volume";
if (m > 1) cout << "s";
cout << " from input ";
if (twod) cout << "volume";
else cout << "sequence";
}
cout << "...";
cout.flush();
}
ImageAttributes out_attr = ref->Attributes();
if (twod) out_attr._z = n; // spacing and origin set later below
else out_attr._t = n;
UniquePtr<BaseImage> output(BaseImage::New(ref->GetDataType()));
output->Initialize(out_attr);
// Concatenate images
double sum_spacing = 0.;
double min_zorigin = ref->GetOrigin()._z;
if (twod) {
sum_spacing = ref->ZSize();
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, 0, 0, ref->GetAsDouble(i, j));
}
UniquePtr<BaseImage> image;
for (int k = 1; k < n; ++k) {
if (pos[k] < 0) {
image.reset(GetRegion(input, -pos[k] - 1));
} else {
image.reset(BaseImage::New(input_names[pos[k]]));
}
if (image->Z() != 1 || image->T() != 1) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " is not 2D!");
}
if (image->X() != ref->X() || image->Y() != ref->Y()) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " has differing number of voxels!");
}
if (!AreEqual(image->XSize(), ref->XSize()) ||
!AreEqual(image->YSize(), ref->YSize())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " has differing voxel size!");
}
if (!AreEqual(image->TSize(), ref->TSize())) {
Warning("Input image " << k+1 << " has differing temporal spacing.");
}
if (!CheckOrientation(image->Attributes(), ref->Attributes())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << k+1 << " has different orientation!");
}
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, k, 0, image->GetAsDouble(i, j));
}
min_zorigin = min(min_zorigin, image->GetOrigin()._z);
sum_spacing += image->ZSize();
}
} else {
sum_spacing = ref->TSize();
for (int k = 0; k < out_attr._z; ++k)
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, k, 0, ref->GetAsDouble(i, j, k));
}
UniquePtr<BaseImage> image;
for (int l = 1; l < n; ++l) {
if (pos[l] < 0) {
image.reset(GetRegion(input, -pos[l] - 1));
} else {
image.reset(BaseImage::New(input_names[pos[l]]));
}
if (image->T() != 1) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " is not 3D!");
}
if (image->X() != ref->X() || image->Y() != ref->Y() || image->Z() != ref->Z()) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " has differing number of voxels!");
}
if (!AreEqual(image->XSize(), ref->XSize()) ||
!AreEqual(image->YSize(), ref->YSize()) ||
!AreEqual(image->ZSize(), ref->ZSize())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " has differing voxel size!");
}
if (!CheckOrientation(image->Attributes(), ref->Attributes())) {
if (verbose) cout << " failed" << endl;
FatalError("Input image " << l+1 << " has different orientation!");
}
for (int k = 0; k < out_attr._z; ++k)
for (int j = 0; j < out_attr._y; ++j)
for (int i = 0; i < out_attr._x; ++i) {
output->PutAsDouble(i, j, k, l, image->GetAsDouble(i, j, k));
}
sum_spacing += image->TSize();
}
}
// Set output spacing to average of input images by default
if (IsNaN(spacing)) {
spacing = sum_spacing / n;
}
if (twod) {
if (spacing < 0.) { // must be positive
out_attr._zaxis[0] *= -1.;
out_attr._zaxis[1] *= -1.;
out_attr._zaxis[2] *= -1.;
spacing *= -1.;
}
double dx, dy, dz;
output->GetPixelSize(dx, dy, dz);
output->PutPixelSize(dx, dy, spacing);
} else {
output->PutTSize(spacing); // can be negative
}
// Set output origin
if (twod) {
if (IsNaN(start)) {
start = min_zorigin;
}
Point origin = output->GetOrigin();
origin._z = start;
// Move to center of image stack, i.e. translate along z axis
double s = .5 * (n - 1) * output->ZSize();
origin._x += s * output->Attributes()._zaxis[0];
origin._y += s * output->Attributes()._zaxis[1];
origin._z += s * output->Attributes()._zaxis[2];
output->PutOrigin(origin);
} else {
if (!IsNaN(start)) out_attr._torigin = start;
// else torigin is time of first (sorted) input volume
}
if (verbose) cout << " done" << endl;
// Write output image
if (verbose) {
cout << "Writing ";
cout << (sort_input ? "combined" : "concatenated");
cout << " images to " << output_name << "...";
cout.flush();
}
output->Write(output_name);
if (verbose) {
cout << " done" << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** v4l2compress_vp8.cpp
**
** Read YUYV from a V4L2 capture -> compress in VP8 -> write to a V4L2 output device
**
** -------------------------------------------------------------------------*/
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <fstream>
#include "vpx/vpx_encoder.h"
#include "vpx/vp8cx.h"
#include "libyuv.h"
#include "logger.h"
#include "V4l2Device.h"
#include "V4l2Capture.h"
#include "V4l2Output.h"
/* ---------------------------------------------------------------------------
** main
** -------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
int verbose=0;
const char *in_devname = "/dev/video0";
const char *out_devname = "/dev/video1";
int width = 640;
int height = 480;
int fps = 25;
int c = 0;
bool useMmap = true;
while ((c = getopt (argc, argv, "hW:H:P:F:v::r")) != -1)
{
switch (c)
{
case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break;
case 'W': width = atoi(optarg); break;
case 'H': height = atoi(optarg); break;
case 'F': fps = atoi(optarg); break;
case 'r': useMmap = false; break;
case 'h':
{
std::cout << argv[0] << " [-v[v]] [-W width] [-H height] source_device dest_device" << std::endl;
std::cout << "\t -v : verbose " << std::endl;
std::cout << "\t -vv : very verbose " << std::endl;
std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl;
std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl;
std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl;
std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl;
std::cout << "\t source_device : V4L2 capture device (default "<< in_devname << ")" << std::endl;
std::cout << "\t dest_device : V4L2 capture device (default "<< out_devname << ")" << std::endl;
exit(0);
}
}
}
if (optind<argc)
{
in_devname = argv[optind];
optind++;
}
if (optind<argc)
{
out_devname = argv[optind];
optind++;
}
int flags=0;
int frame_cnt=0;
vpx_image_t raw;
if(!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, width, height, 1))
LOG(WARN) << "vpx_img_alloc";
const vpx_codec_iface_t* algo = vpx_codec_vp8_cx();
vpx_codec_enc_cfg_t cfg;
if (vpx_codec_enc_config_default(algo, &cfg, 0) != VPX_CODEC_OK)
LOG(WARN) << "vpx_codec_enc_config_default";
vpx_codec_ctx_t codec;
if(vpx_codec_enc_init(&codec, algo, &cfg, 0))
LOG(WARN) << "vpx_codec_enc_init";
// initialize log4cpp
initLogger(verbose);
// init V4L2 capture interface
int format = V4L2_PIX_FMT_YUYV;
V4L2DeviceParameters param(in_devname,format,width,height,fps,verbose);
V4l2Capture* videoCapture = V4l2DeviceFactory::CreateVideoCapure(param, useMmap);
if (videoCapture == NULL)
{
LOG(WARN) << "Cannot create V4L2 capture interface for device:" << in_devname;
}
else
{
V4L2DeviceParameters outparam(out_devname, V4L2_PIX_FMT_VP8, videoCapture->getWidth(), videoCapture->getHeight(), 0,verbose);
V4l2Output out(outparam);
fd_set fdset;
FD_ZERO(&fdset);
timeval tv;
LOG(NOTICE) << "Start Compressing " << in_devname << " to " << out_devname;
videoCapture->captureStart();
int stop=0;
while (!stop)
{
tv.tv_sec=1;
tv.tv_usec=0;
FD_SET(videoCapture->getFd(), &fdset);
int ret = select(videoCapture->getFd()+1, &fdset, NULL, NULL, &tv);
if (ret == 1)
{
char buffer[videoCapture->getBufferSize()];
int rsize = videoCapture->read(buffer, sizeof(buffer));
ConvertToI420((const uint8*)buffer, rsize,
raw.planes[0], width,
raw.planes[1], width/2,
raw.planes[2], width/2,
0, 0,
width, height,
width, height,
libyuv::kRotate0, libyuv::FOURCC_YUY2);
if(vpx_codec_encode(&codec, &raw, frame_cnt++, 1, flags, VPX_DL_REALTIME))
{
LOG(WARN) << "vpx_codec_encode: " << vpx_codec_error(&codec) << "(" << vpx_codec_error_detail(&codec) << ")";
}
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt;
while( (pkt = vpx_codec_get_cx_data(&codec, &iter)) )
{
if (pkt->kind==VPX_CODEC_CX_FRAME_PKT)
{
int wsize = write(out.getFd(), pkt->data.frame.buf, pkt->data.frame.sz);
LOG(DEBUG) << "Copied " << rsize << " " << wsize;
}
else
{
break;
}
}
}
else if (ret == -1)
{
LOG(NOTICE) << "stop " << strerror(errno);
stop=1;
}
}
videoCapture->captureStop();
delete videoCapture;
}
return 0;
}
<commit_msg>set encoder width/height<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** v4l2compress_vp8.cpp
**
** Read YUYV from a V4L2 capture -> compress in VP8 -> write to a V4L2 output device
**
** -------------------------------------------------------------------------*/
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <fstream>
#include "vpx/vpx_encoder.h"
#include "vpx/vp8cx.h"
#include "libyuv.h"
#include "logger.h"
#include "V4l2Device.h"
#include "V4l2Capture.h"
#include "V4l2Output.h"
/* ---------------------------------------------------------------------------
** main
** -------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
int verbose=0;
const char *in_devname = "/dev/video0";
const char *out_devname = "/dev/video1";
int width = 640;
int height = 480;
int fps = 25;
int c = 0;
bool useMmap = true;
while ((c = getopt (argc, argv, "hW:H:P:F:v::r")) != -1)
{
switch (c)
{
case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break;
case 'W': width = atoi(optarg); break;
case 'H': height = atoi(optarg); break;
case 'F': fps = atoi(optarg); break;
case 'r': useMmap = false; break;
case 'h':
{
std::cout << argv[0] << " [-v[v]] [-W width] [-H height] source_device dest_device" << std::endl;
std::cout << "\t -v : verbose " << std::endl;
std::cout << "\t -vv : very verbose " << std::endl;
std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl;
std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl;
std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl;
std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl;
std::cout << "\t source_device : V4L2 capture device (default "<< in_devname << ")" << std::endl;
std::cout << "\t dest_device : V4L2 capture device (default "<< out_devname << ")" << std::endl;
exit(0);
}
}
}
if (optind<argc)
{
in_devname = argv[optind];
optind++;
}
if (optind<argc)
{
out_devname = argv[optind];
optind++;
}
// initialize log4cpp
initLogger(verbose);
vpx_image_t raw;
if(!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, width, height, 1))
{
LOG(WARN) << "vpx_img_alloc";
}
const vpx_codec_iface_t* algo = vpx_codec_vp8_cx();
vpx_codec_enc_cfg_t cfg;
if (vpx_codec_enc_config_default(algo, &cfg, 0) != VPX_CODEC_OK)
{
LOG(WARN) << "vpx_codec_enc_config_default";
}
cfg.g_w = width;
cfg.g_h = height;
vpx_codec_ctx_t codec;
if(vpx_codec_enc_init(&codec, algo, &cfg, 0))
{
LOG(WARN) << "vpx_codec_enc_init";
}
// init V4L2 capture interface
int format = V4L2_PIX_FMT_YUYV;
V4L2DeviceParameters param(in_devname,format,width,height,fps,verbose);
V4l2Capture* videoCapture = V4l2DeviceFactory::CreateVideoCapure(param, useMmap);
if (videoCapture == NULL)
{
LOG(WARN) << "Cannot create V4L2 capture interface for device:" << in_devname;
}
else
{
V4L2DeviceParameters outparam(out_devname, V4L2_PIX_FMT_VP8, videoCapture->getWidth(), videoCapture->getHeight(), 0,verbose);
V4l2Output out(outparam);
fd_set fdset;
FD_ZERO(&fdset);
timeval tv;
LOG(NOTICE) << "Start Compressing " << in_devname << " to " << out_devname;
videoCapture->captureStart();
int stop=0;
int flags=0;
int frame_cnt=0;
while (!stop)
{
tv.tv_sec=1;
tv.tv_usec=0;
FD_SET(videoCapture->getFd(), &fdset);
int ret = select(videoCapture->getFd()+1, &fdset, NULL, NULL, &tv);
if (ret == 1)
{
char buffer[videoCapture->getBufferSize()];
int rsize = videoCapture->read(buffer, sizeof(buffer));
ConvertToI420((const uint8*)buffer, rsize,
raw.planes[0], width,
raw.planes[1], width/2,
raw.planes[2], width/2,
0, 0,
width, height,
width, height,
libyuv::kRotate0, libyuv::FOURCC_YUY2);
if(vpx_codec_encode(&codec, &raw, frame_cnt++, 1, flags, VPX_DL_REALTIME))
{
LOG(WARN) << "vpx_codec_encode: " << vpx_codec_error(&codec) << "(" << vpx_codec_error_detail(&codec) << ")";
}
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt;
while( (pkt = vpx_codec_get_cx_data(&codec, &iter)) )
{
if (pkt->kind==VPX_CODEC_CX_FRAME_PKT)
{
int wsize = write(out.getFd(), pkt->data.frame.buf, pkt->data.frame.sz);
LOG(DEBUG) << "Copied " << rsize << " " << wsize;
}
else
{
break;
}
}
}
else if (ret == -1)
{
LOG(NOTICE) << "stop " << strerror(errno);
stop=1;
}
}
delete videoCapture;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <eosio/trace_api/trace_api_plugin.hpp>
#include <eosio/trace_api/abi_data_handler.hpp>
#include <eosio/trace_api/request_handler.hpp>
#include <eosio/trace_api/chain_extraction.hpp>
#include <eosio/trace_api/store_provider.hpp>
#include <eosio/trace_api/configuration_utils.hpp>
#include <boost/signals2/connection.hpp>
using namespace eosio::trace_api;
using namespace eosio::trace_api::configuration_utils;
using boost::signals2::scoped_connection;
namespace {
appbase::abstract_plugin& plugin_reg = app().register_plugin<trace_api_plugin>();
const std::string logger_name("trace_api");
fc::logger _log;
std::string to_detail_string(const std::exception_ptr& e) {
try {
std::rethrow_exception(e);
} catch (fc::exception& er) {
return er.to_detail_string();
} catch (const std::exception& e) {
fc::exception fce(
FC_LOG_MESSAGE(warn, "std::exception: ${what}: ", ("what", e.what())),
fc::std_exception_code,
BOOST_CORE_TYPEID(e).name(),
e.what());
return fce.to_detail_string();
} catch (...) {
fc::unhandled_exception ue(
FC_LOG_MESSAGE(warn, "unknown: ",),
std::current_exception());
return ue.to_detail_string();
}
}
void log_exception( const exception_with_context& e, fc::log_level level ) {
if( _log.is_enabled( level ) ) {
auto detail_string = to_detail_string(std::get<0>(e));
auto context = fc::log_context( level, std::get<1>(e), std::get<2>(e), std::get<3>(e) );
_log.log(fc::log_message( context, detail_string ));
}
}
/**
* The exception_handler provided to the extraction sub-system throws `yield_exception` as a signal that
* Something has gone wrong and the extraction process needs to terminate immediately
*
* This templated method is used to wrap signal handlers for `chain_controller` so that the plugin-internal
* `yield_exception` can be translated to a `chain::controller_emit_signal_exception`.
*
* The goal is that the currently applied block will be rolled-back before the shutdown takes effect leaving
* the system in a better state for restart.
*/
template<typename F>
void emit_killer(F&& f) {
try {
f();
} catch (const yield_exception& ) {
EOS_THROW(chain::controller_emit_signal_exception, "Trace API encountered an Error which it cannot recover from. Please resolve the error and relaunch the process")
}
}
template<typename Store>
struct shared_store_provider {
shared_store_provider(const std::shared_ptr<Store>& store)
:store(store)
{}
void append( const block_trace_v0& trace ) {
store->append(trace);
}
void append_lib( uint32_t new_lib ) {
store->append_lib(new_lib);
}
get_block_t get_block(uint32_t height, const yield_function& yield) {
return store->get_block(height, yield);
}
std::shared_ptr<Store> store;
};
}
namespace eosio {
/**
* A common source for information shared between the extraction process and the RPC process
*/
struct trace_api_common_impl {
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-dir", bpo::value<bfs::path>()->default_value("traces"),
"the location of the trace directory (absolute path or relative to application data dir)");
cfg_options("trace-slice-stride", bpo::value<uint32_t>()->default_value(10'000),
"the number of blocks each \"slice\" of trace data will contain on the filesystem");
}
void plugin_initialize(const appbase::variables_map& options) {
auto dir_option = options.at("trace-dir").as<bfs::path>();
if (dir_option.is_relative())
trace_dir = app().data_dir() / dir_option;
else
trace_dir = dir_option;
slice_stride = options.at("trace-slice-stride").as<uint32_t>();
store = std::make_shared<store_provider>(trace_dir, slice_stride);
}
// common configuration paramters
boost::filesystem::path trace_dir;
uint32_t slice_stride = 0;
std::shared_ptr<store_provider> store;
};
/**
* Interface with the RPC process
*/
struct trace_api_rpc_plugin_impl : public std::enable_shared_from_this<trace_api_rpc_plugin_impl>
{
trace_api_rpc_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-rpc-abi", bpo::value<vector<string>>()->composing(),
"ABIs used when decoding trace RPC responses.\n"
"There must be at least one ABI specified OR the flag trace-no-abis must be used.\n"
"ABIs are specified as \"Key=Value\" pairs in the form <account-name>=<abi-def>\n"
"Where <abi-def> can be:\n"
" an absolute path to a file containing a valid JSON-encoded ABI\n"
" a relative path from `data-dir` to a file containing a valid JSON-encoded ABI\n"
);
cfg_options("trace-no-abis",
"Use to indicate that the RPC responses will not use ABIs.\n"
"Failure to specify this option when there are no trace-rpc-abi configuations will result in an Error.\n"
"This option is mutually exclusive with trace-rpc-api"
);
}
void plugin_initialize(const appbase::variables_map& options) {
std::shared_ptr<abi_data_handler> data_handler = std::make_shared<abi_data_handler>([](const exception_with_context& e){
log_exception(e, fc::log_level::debug);
});
if( options.count("trace-rpc-abi") ) {
EOS_ASSERT(options.count("trace-no-abis") == 0, chain::plugin_config_exception,
"Trace API is configured with ABIs however trace-no-abis is set");
const std::vector<std::string> key_value_pairs = options["trace-rpc-abi"].as<std::vector<std::string>>();
for (const auto& entry : key_value_pairs) {
try {
auto kv = parse_kv_pairs(entry);
auto account = chain::name(kv.first);
auto abi = abi_def_from_file(kv.second, app().data_dir());
data_handler->add_abi(account, abi);
} catch (...) {
elog("Malformed trace-rpc-abi provider: \"${val}\"", ("val", entry));
throw;
}
}
} else {
EOS_ASSERT(options.count("trace-no-abis") != 0, chain::plugin_config_exception,
"Trace API is not configured with ABIs and trace-no-abis is not set");
}
request_handler = std::make_shared<request_handler_t>(
shared_store_provider<store_provider>(common->store),
abi_data_handler::shared_provider(data_handler)
);
}
void plugin_startup() {
auto& http = app().get_plugin<http_plugin>();
http.add_handler("/v1/trace_api/get_block", [wthis=weak_from_this()](std::string, std::string body, url_response_callback cb){
auto that = wthis.lock();
if (!that) {
return;
}
auto block_number = ([&body]() -> std::optional<uint32_t> {
if (body.empty()) {
return {};
}
try {
auto input = fc::json::from_string(body);
auto block_num = input.get_object()["block_num"].as_uint64();
if (block_num > std::numeric_limits<uint32_t>::max()) {
return {};
}
return block_num;
} catch (...) {
return {};
}
})();
if (!block_number) {
error_results results{400, "Bad or missing block_num"};
cb( 400, fc::variant( results ));
return;
}
try {
auto resp = that->request_handler->get_block_trace(*block_number);
if (resp.is_null()) {
error_results results{404, "Block trace missing"};
cb( 404, fc::variant( results ));
} else {
cb( 200, resp );
}
} catch (...) {
http_plugin::handle_exception("trace_api", "get_block", body, cb);
}
});
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
using request_handler_t = request_handler<shared_store_provider<store_provider>, abi_data_handler::shared_provider>;
std::shared_ptr<request_handler_t> request_handler;
};
struct trace_api_plugin_impl {
trace_api_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-minimum-irreversible-history-us", bpo::value<uint64_t>()->default_value(-1),
"the minimum amount of history, as defined by time, this node will keep after it becomes irreversible\n"
"this value can be specified as a number of microseconds or\n"
"a value of \"-1\" will disable automatic maintenance of the trace slice files\n"
);
}
void plugin_initialize(const appbase::variables_map& options) {
if( options.count("trace-minimum-irreversible-history-us") ) {
auto value = options.at("trace-minimum-irreversible-history-us").as<uint64_t>();
if ( value == -1 ) {
minimum_irreversible_trace_history = fc::microseconds::maximum();
} else if (value >= 0) {
minimum_irreversible_trace_history = fc::microseconds(value);
} else {
EOS_THROW(chain::plugin_config_exception, "trace-minimum-irreversible-history-us must be either a positive number or -1");
}
}
auto log_exceptions_and_shutdown = [](const exception_with_context& e) {
log_exception(e, fc::log_level::error);
app().quit();
throw yield_exception("shutting down");
};
extraction = std::make_shared<chain_extraction_t>(shared_store_provider<store_provider>(common->store), log_exceptions_and_shutdown);
auto& chain = app().find_plugin<chain_plugin>()->chain();
applied_transaction_connection.emplace(
chain.applied_transaction.connect([this](std::tuple<const chain::transaction_trace_ptr&, const chain::signed_transaction&> t) {
emit_killer([&](){
extraction->signal_applied_transaction(std::get<0>(t), std::get<1>(t));
});
}));
accepted_block_connection.emplace(
chain.accepted_block.connect([this](const chain::block_state_ptr& p) {
emit_killer([&](){
extraction->signal_accepted_block(p);
});
}));
irreversible_block_connection.emplace(
chain.irreversible_block.connect([this](const chain::block_state_ptr& p) {
emit_killer([&](){
extraction->signal_irreversible_block(p);
});
}));
}
void plugin_startup() {
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
fc::microseconds minimum_irreversible_trace_history = fc::microseconds::maximum();
using chain_extraction_t = chain_extraction_impl_type<shared_store_provider<store_provider>>;
std::shared_ptr<chain_extraction_t> extraction;
fc::optional<scoped_connection> applied_transaction_connection;
fc::optional<scoped_connection> accepted_block_connection;
fc::optional<scoped_connection> irreversible_block_connection;
};
trace_api_plugin::trace_api_plugin()
{}
trace_api_plugin::~trace_api_plugin()
{}
void trace_api_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_plugin_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void trace_api_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
my = std::make_shared<trace_api_plugin_impl>(common);
my->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void trace_api_plugin::plugin_startup() {
handle_sighup(); // setup logging
my->plugin_startup();
rpc->plugin_startup();
}
void trace_api_plugin::plugin_shutdown() {
my->plugin_shutdown();
rpc->plugin_shutdown();
}
void trace_api_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
trace_api_rpc_plugin::trace_api_rpc_plugin()
{}
trace_api_rpc_plugin::~trace_api_rpc_plugin()
{}
void trace_api_rpc_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void trace_api_rpc_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void trace_api_rpc_plugin::plugin_startup() {
rpc->plugin_startup();
}
void trace_api_rpc_plugin::plugin_shutdown() {
rpc->plugin_shutdown();
}
void trace_api_rpc_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
}<commit_msg>optimization to avoid deep copy of response variant<commit_after>#include <eosio/trace_api/trace_api_plugin.hpp>
#include <eosio/trace_api/abi_data_handler.hpp>
#include <eosio/trace_api/request_handler.hpp>
#include <eosio/trace_api/chain_extraction.hpp>
#include <eosio/trace_api/store_provider.hpp>
#include <eosio/trace_api/configuration_utils.hpp>
#include <boost/signals2/connection.hpp>
using namespace eosio::trace_api;
using namespace eosio::trace_api::configuration_utils;
using boost::signals2::scoped_connection;
namespace {
appbase::abstract_plugin& plugin_reg = app().register_plugin<trace_api_plugin>();
const std::string logger_name("trace_api");
fc::logger _log;
std::string to_detail_string(const std::exception_ptr& e) {
try {
std::rethrow_exception(e);
} catch (fc::exception& er) {
return er.to_detail_string();
} catch (const std::exception& e) {
fc::exception fce(
FC_LOG_MESSAGE(warn, "std::exception: ${what}: ", ("what", e.what())),
fc::std_exception_code,
BOOST_CORE_TYPEID(e).name(),
e.what());
return fce.to_detail_string();
} catch (...) {
fc::unhandled_exception ue(
FC_LOG_MESSAGE(warn, "unknown: ",),
std::current_exception());
return ue.to_detail_string();
}
}
void log_exception( const exception_with_context& e, fc::log_level level ) {
if( _log.is_enabled( level ) ) {
auto detail_string = to_detail_string(std::get<0>(e));
auto context = fc::log_context( level, std::get<1>(e), std::get<2>(e), std::get<3>(e) );
_log.log(fc::log_message( context, detail_string ));
}
}
/**
* The exception_handler provided to the extraction sub-system throws `yield_exception` as a signal that
* Something has gone wrong and the extraction process needs to terminate immediately
*
* This templated method is used to wrap signal handlers for `chain_controller` so that the plugin-internal
* `yield_exception` can be translated to a `chain::controller_emit_signal_exception`.
*
* The goal is that the currently applied block will be rolled-back before the shutdown takes effect leaving
* the system in a better state for restart.
*/
template<typename F>
void emit_killer(F&& f) {
try {
f();
} catch (const yield_exception& ) {
EOS_THROW(chain::controller_emit_signal_exception, "Trace API encountered an Error which it cannot recover from. Please resolve the error and relaunch the process")
}
}
template<typename Store>
struct shared_store_provider {
shared_store_provider(const std::shared_ptr<Store>& store)
:store(store)
{}
void append( const block_trace_v0& trace ) {
store->append(trace);
}
void append_lib( uint32_t new_lib ) {
store->append_lib(new_lib);
}
get_block_t get_block(uint32_t height, const yield_function& yield) {
return store->get_block(height, yield);
}
std::shared_ptr<Store> store;
};
}
namespace eosio {
/**
* A common source for information shared between the extraction process and the RPC process
*/
struct trace_api_common_impl {
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-dir", bpo::value<bfs::path>()->default_value("traces"),
"the location of the trace directory (absolute path or relative to application data dir)");
cfg_options("trace-slice-stride", bpo::value<uint32_t>()->default_value(10'000),
"the number of blocks each \"slice\" of trace data will contain on the filesystem");
}
void plugin_initialize(const appbase::variables_map& options) {
auto dir_option = options.at("trace-dir").as<bfs::path>();
if (dir_option.is_relative())
trace_dir = app().data_dir() / dir_option;
else
trace_dir = dir_option;
slice_stride = options.at("trace-slice-stride").as<uint32_t>();
store = std::make_shared<store_provider>(trace_dir, slice_stride);
}
// common configuration paramters
boost::filesystem::path trace_dir;
uint32_t slice_stride = 0;
std::shared_ptr<store_provider> store;
};
/**
* Interface with the RPC process
*/
struct trace_api_rpc_plugin_impl : public std::enable_shared_from_this<trace_api_rpc_plugin_impl>
{
trace_api_rpc_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-rpc-abi", bpo::value<vector<string>>()->composing(),
"ABIs used when decoding trace RPC responses.\n"
"There must be at least one ABI specified OR the flag trace-no-abis must be used.\n"
"ABIs are specified as \"Key=Value\" pairs in the form <account-name>=<abi-def>\n"
"Where <abi-def> can be:\n"
" an absolute path to a file containing a valid JSON-encoded ABI\n"
" a relative path from `data-dir` to a file containing a valid JSON-encoded ABI\n"
);
cfg_options("trace-no-abis",
"Use to indicate that the RPC responses will not use ABIs.\n"
"Failure to specify this option when there are no trace-rpc-abi configuations will result in an Error.\n"
"This option is mutually exclusive with trace-rpc-api"
);
}
void plugin_initialize(const appbase::variables_map& options) {
std::shared_ptr<abi_data_handler> data_handler = std::make_shared<abi_data_handler>([](const exception_with_context& e){
log_exception(e, fc::log_level::debug);
});
if( options.count("trace-rpc-abi") ) {
EOS_ASSERT(options.count("trace-no-abis") == 0, chain::plugin_config_exception,
"Trace API is configured with ABIs however trace-no-abis is set");
const std::vector<std::string> key_value_pairs = options["trace-rpc-abi"].as<std::vector<std::string>>();
for (const auto& entry : key_value_pairs) {
try {
auto kv = parse_kv_pairs(entry);
auto account = chain::name(kv.first);
auto abi = abi_def_from_file(kv.second, app().data_dir());
data_handler->add_abi(account, abi);
} catch (...) {
elog("Malformed trace-rpc-abi provider: \"${val}\"", ("val", entry));
throw;
}
}
} else {
EOS_ASSERT(options.count("trace-no-abis") != 0, chain::plugin_config_exception,
"Trace API is not configured with ABIs and trace-no-abis is not set");
}
request_handler = std::make_shared<request_handler_t>(
shared_store_provider<store_provider>(common->store),
abi_data_handler::shared_provider(data_handler)
);
}
void plugin_startup() {
auto& http = app().get_plugin<http_plugin>();
http.add_handler("/v1/trace_api/get_block", [wthis=weak_from_this()](std::string, std::string body, url_response_callback cb){
auto that = wthis.lock();
if (!that) {
return;
}
auto block_number = ([&body]() -> std::optional<uint32_t> {
if (body.empty()) {
return {};
}
try {
auto input = fc::json::from_string(body);
auto block_num = input.get_object()["block_num"].as_uint64();
if (block_num > std::numeric_limits<uint32_t>::max()) {
return {};
}
return block_num;
} catch (...) {
return {};
}
})();
if (!block_number) {
error_results results{400, "Bad or missing block_num"};
cb( 400, fc::variant( results ));
return;
}
try {
auto resp = that->request_handler->get_block_trace(*block_number);
if (resp.is_null()) {
error_results results{404, "Block trace missing"};
cb( 404, fc::variant( results ));
} else {
cb( 200, std::move(resp) );
}
} catch (...) {
http_plugin::handle_exception("trace_api", "get_block", body, cb);
}
});
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
using request_handler_t = request_handler<shared_store_provider<store_provider>, abi_data_handler::shared_provider>;
std::shared_ptr<request_handler_t> request_handler;
};
struct trace_api_plugin_impl {
trace_api_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-minimum-irreversible-history-us", bpo::value<uint64_t>()->default_value(-1),
"the minimum amount of history, as defined by time, this node will keep after it becomes irreversible\n"
"this value can be specified as a number of microseconds or\n"
"a value of \"-1\" will disable automatic maintenance of the trace slice files\n"
);
}
void plugin_initialize(const appbase::variables_map& options) {
if( options.count("trace-minimum-irreversible-history-us") ) {
auto value = options.at("trace-minimum-irreversible-history-us").as<uint64_t>();
if ( value == -1 ) {
minimum_irreversible_trace_history = fc::microseconds::maximum();
} else if (value >= 0) {
minimum_irreversible_trace_history = fc::microseconds(value);
} else {
EOS_THROW(chain::plugin_config_exception, "trace-minimum-irreversible-history-us must be either a positive number or -1");
}
}
auto log_exceptions_and_shutdown = [](const exception_with_context& e) {
log_exception(e, fc::log_level::error);
app().quit();
throw yield_exception("shutting down");
};
extraction = std::make_shared<chain_extraction_t>(shared_store_provider<store_provider>(common->store), log_exceptions_and_shutdown);
auto& chain = app().find_plugin<chain_plugin>()->chain();
applied_transaction_connection.emplace(
chain.applied_transaction.connect([this](std::tuple<const chain::transaction_trace_ptr&, const chain::signed_transaction&> t) {
emit_killer([&](){
extraction->signal_applied_transaction(std::get<0>(t), std::get<1>(t));
});
}));
accepted_block_connection.emplace(
chain.accepted_block.connect([this](const chain::block_state_ptr& p) {
emit_killer([&](){
extraction->signal_accepted_block(p);
});
}));
irreversible_block_connection.emplace(
chain.irreversible_block.connect([this](const chain::block_state_ptr& p) {
emit_killer([&](){
extraction->signal_irreversible_block(p);
});
}));
}
void plugin_startup() {
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
fc::microseconds minimum_irreversible_trace_history = fc::microseconds::maximum();
using chain_extraction_t = chain_extraction_impl_type<shared_store_provider<store_provider>>;
std::shared_ptr<chain_extraction_t> extraction;
fc::optional<scoped_connection> applied_transaction_connection;
fc::optional<scoped_connection> accepted_block_connection;
fc::optional<scoped_connection> irreversible_block_connection;
};
trace_api_plugin::trace_api_plugin()
{}
trace_api_plugin::~trace_api_plugin()
{}
void trace_api_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_plugin_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void trace_api_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
my = std::make_shared<trace_api_plugin_impl>(common);
my->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void trace_api_plugin::plugin_startup() {
handle_sighup(); // setup logging
my->plugin_startup();
rpc->plugin_startup();
}
void trace_api_plugin::plugin_shutdown() {
my->plugin_shutdown();
rpc->plugin_shutdown();
}
void trace_api_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
trace_api_rpc_plugin::trace_api_rpc_plugin()
{}
trace_api_rpc_plugin::~trace_api_rpc_plugin()
{}
void trace_api_rpc_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void trace_api_rpc_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void trace_api_rpc_plugin::plugin_startup() {
rpc->plugin_startup();
}
void trace_api_rpc_plugin::plugin_shutdown() {
rpc->plugin_shutdown();
}
void trace_api_rpc_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
}<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TournamentsAmbiguityNumber {
int scrutinizeTable(vector <string> t) {
const int q = sz();
int c = 0;
fr(i, q) for (int j = i+1; j < q; ++j) for (int k = j+1; k < q; ++k) {
if (t[i][j] == '1' && t[j][k] == '1' && t[k][i] == '1') {
++c;
}
}
return c;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TournamentsAmbiguityNumber *obj;
int answer;
obj = new TournamentsAmbiguityNumber();
clock_t startTime = clock();
answer = obj->scrutinizeTable(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
int p1;
// ----- test 0 -----
disabled = false;
p0 = {"-10","0-1","10-"};
p1 = 3;
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"----","----","----","----"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"-1","0-"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"--1-10-1---1--1-00","--0110000--0---10-","01--00000100-00011","-0---0010-11110100","001--01-00-0001-1-","11111--100--1-1-01","-1110--00110-11-01","0110-01--100110-10","-111111---01--0-01","--0-1100----10011-","--10--011--1--101-","01101-110-0--1-0-1","---010-0-0---00-11","--101-00-1-01-0-0-","0-110001110-11-110","-010-----011--0--0","11010110100-010--0","1-01-0010--00-111-"};
p1 = 198;
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>TournamentsAmbiguityNumber<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TournamentsAmbiguityNumber {
int scrutinizeTable(vector <string> t) {
const int q = sz(t);
int c = 0;
fr(i, q) for (int j = i+1; j < q; ++j) for (int k = j+1; k < q; ++k) {
if (t[i][j] == '1' && t[j][k] == '1' && t[k][i] == '1') {
++c;
}
}
return c;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TournamentsAmbiguityNumber *obj;
int answer;
obj = new TournamentsAmbiguityNumber();
clock_t startTime = clock();
answer = obj->scrutinizeTable(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
int p1;
// ----- test 0 -----
disabled = false;
p0 = {"-10","0-1","10-"};
p1 = 3;
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"----","----","----","----"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"-1","0-"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"--1-10-1---1--1-00","--0110000--0---10-","01--00000100-00011","-0---0010-11110100","001--01-00-0001-1-","11111--100--1-1-01","-1110--00110-11-01","0110-01--100110-10","-111111---01--0-01","--0-1100----10011-","--10--011--1--101-","01101-110-0--1-0-1","---010-0-0---00-11","--101-00-1-01-0-0-","0-110001110-11-110","-010-----011--0--0","11010110100-010--0","1-01-0010--00-111-"};
p1 = 198;
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems
* Copyright 2015 Cloudius Systems
*/
/*
* 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/>.
*/
#pragma once
#include "locator/token_metadata.hh"
#include "streaming/stream_plan.hh"
#include "streaming/stream_state.hh"
#include "gms/inet_address.hh"
#include "gms/i_failure_detector.hh"
#include "range.hh"
#include <seastar/core/distributed.hh>
#include <unordered_map>
#include <memory>
class database;
namespace dht {
/**
* Assists in streaming ranges to a node.
*/
class range_streamer {
public:
using inet_address = gms::inet_address;
using token_metadata = locator::token_metadata;
using stream_plan = streaming::stream_plan;
using stream_state = streaming::stream_state;
using i_failure_detector = gms::i_failure_detector;
static bool use_strict_consistency() {
//FIXME: Boolean.parseBoolean(System.getProperty("cassandra.consistent.rangemovement","true"));
return true;
}
public:
/**
* A filter applied to sources to stream from when constructing a fetch map.
*/
class i_source_filter {
public:
virtual bool should_include(inet_address endpoint) = 0;
};
/**
* Source filter which excludes any endpoints that are not alive according to a
* failure detector.
*/
class failure_detector_source_filter : public i_source_filter {
private:
gms::i_failure_detector& _fd;
public:
failure_detector_source_filter(i_failure_detector& fd) : _fd(fd) { }
virtual bool should_include(inet_address endpoint) override { return _fd.is_alive(endpoint); }
};
#if 0
/**
* Source filter which excludes any endpoints that are not in a specific data center.
*/
public static class SingleDatacenterFilter implements ISourceFilter
{
private final String sourceDc;
private final IEndpointSnitch snitch;
public SingleDatacenterFilter(IEndpointSnitch snitch, String sourceDc)
{
this.sourceDc = sourceDc;
this.snitch = snitch;
}
public boolean shouldInclude(InetAddress endpoint)
{
return snitch.getDatacenter(endpoint).equals(sourceDc);
}
}
#endif
range_streamer(distributed<database>& db, token_metadata& tm, std::unordered_set<token> tokens, inet_address address, sstring description)
: _db(db)
, _metadata(tm)
, _tokens(std::move(tokens))
, _address(address)
, _description(std::move(description))
, _stream_plan(_description, true) {
}
range_streamer(distributed<database>& db, token_metadata& tm, inet_address address, sstring description)
: range_streamer(db, tm, std::unordered_set<token>(), address, description) {
}
void add_source_filter(std::unique_ptr<i_source_filter> filter) {
_source_filters.emplace(std::move(filter));
}
void add_ranges(const sstring& keyspace_name, std::vector<range<token>> ranges);
private:
bool use_strict_sources_for_ranges(const sstring& keyspace_name);
/**
* Get a map of all ranges and their respective sources that are candidates for streaming the given ranges
* to us. For each range, the list of sources is sorted by proximity relative to the given destAddress.
*/
std::unordered_multimap<range<token>, inet_address>
get_all_ranges_with_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges);
/**
* Get a map of all ranges and the source that will be cleaned up once this bootstrapped node is added for the given ranges.
* For each range, the list should only contain a single source. This allows us to consistently migrate data without violating
* consistency.
*/
std::unordered_multimap<range<token>, inet_address>
get_all_ranges_with_strict_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges);
private:
/**
* @param rangesWithSources The ranges we want to fetch (key) and their potential sources (value)
* @param sourceFilters A (possibly empty) collection of source filters to apply. In addition to any filters given
* here, we always exclude ourselves.
* @return
*/
static std::unordered_multimap<inet_address, range<token>>
get_range_fetch_map(const std::unordered_multimap<range<token>, inet_address>& ranges_with_sources,
const std::unordered_set<std::unique_ptr<i_source_filter>>& source_filters,
const sstring& keyspace);
#if 0
public static Multimap<InetAddress, Range<Token>> getWorkMap(Multimap<Range<Token>, InetAddress> rangesWithSourceTarget, String keyspace)
{
return getRangeFetchMap(rangesWithSourceTarget, Collections.<ISourceFilter>singleton(new FailureDetectorSourceFilter(FailureDetector.instance)), keyspace);
}
// For testing purposes
Multimap<String, Map.Entry<InetAddress, Collection<Range<Token>>>> toFetch()
{
return toFetch;
}
#endif
public:
future<streaming::stream_state> fetch_async();
private:
distributed<database>& _db;
token_metadata& _metadata;
std::unordered_set<token> _tokens;
inet_address _address;
sstring _description;
std::unordered_multimap<sstring, std::unordered_map<inet_address, std::vector<range<token>>>> _to_fetch;
std::unordered_set<std::unique_ptr<i_source_filter>> _source_filters;
stream_plan _stream_plan;
};
} // dht
<commit_msg>range_streamer: Introduce single_datacenter_filter<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems
* Copyright 2015 Cloudius Systems
*/
/*
* 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/>.
*/
#pragma once
#include "locator/token_metadata.hh"
#include "locator/snitch_base.hh"
#include "streaming/stream_plan.hh"
#include "streaming/stream_state.hh"
#include "gms/inet_address.hh"
#include "gms/i_failure_detector.hh"
#include "range.hh"
#include <seastar/core/distributed.hh>
#include <unordered_map>
#include <memory>
class database;
namespace dht {
/**
* Assists in streaming ranges to a node.
*/
class range_streamer {
public:
using inet_address = gms::inet_address;
using token_metadata = locator::token_metadata;
using stream_plan = streaming::stream_plan;
using stream_state = streaming::stream_state;
using i_failure_detector = gms::i_failure_detector;
static bool use_strict_consistency() {
//FIXME: Boolean.parseBoolean(System.getProperty("cassandra.consistent.rangemovement","true"));
return true;
}
public:
/**
* A filter applied to sources to stream from when constructing a fetch map.
*/
class i_source_filter {
public:
virtual bool should_include(inet_address endpoint) = 0;
};
/**
* Source filter which excludes any endpoints that are not alive according to a
* failure detector.
*/
class failure_detector_source_filter : public i_source_filter {
private:
gms::i_failure_detector& _fd;
public:
failure_detector_source_filter(i_failure_detector& fd) : _fd(fd) { }
virtual bool should_include(inet_address endpoint) override { return _fd.is_alive(endpoint); }
};
/**
* Source filter which excludes any endpoints that are not in a specific data center.
*/
class single_datacenter_filter : public i_source_filter {
private:
sstring _source_dc;
public:
single_datacenter_filter(const sstring& source_dc)
: _source_dc(source_dc) {
}
virtual bool should_include(inet_address endpoint) override {
auto& snitch_ptr = locator::i_endpoint_snitch::get_local_snitch_ptr();
return snitch_ptr->get_datacenter(endpoint) == _source_dc;
}
};
range_streamer(distributed<database>& db, token_metadata& tm, std::unordered_set<token> tokens, inet_address address, sstring description)
: _db(db)
, _metadata(tm)
, _tokens(std::move(tokens))
, _address(address)
, _description(std::move(description))
, _stream_plan(_description, true) {
}
range_streamer(distributed<database>& db, token_metadata& tm, inet_address address, sstring description)
: range_streamer(db, tm, std::unordered_set<token>(), address, description) {
}
void add_source_filter(std::unique_ptr<i_source_filter> filter) {
_source_filters.emplace(std::move(filter));
}
void add_ranges(const sstring& keyspace_name, std::vector<range<token>> ranges);
private:
bool use_strict_sources_for_ranges(const sstring& keyspace_name);
/**
* Get a map of all ranges and their respective sources that are candidates for streaming the given ranges
* to us. For each range, the list of sources is sorted by proximity relative to the given destAddress.
*/
std::unordered_multimap<range<token>, inet_address>
get_all_ranges_with_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges);
/**
* Get a map of all ranges and the source that will be cleaned up once this bootstrapped node is added for the given ranges.
* For each range, the list should only contain a single source. This allows us to consistently migrate data without violating
* consistency.
*/
std::unordered_multimap<range<token>, inet_address>
get_all_ranges_with_strict_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges);
private:
/**
* @param rangesWithSources The ranges we want to fetch (key) and their potential sources (value)
* @param sourceFilters A (possibly empty) collection of source filters to apply. In addition to any filters given
* here, we always exclude ourselves.
* @return
*/
static std::unordered_multimap<inet_address, range<token>>
get_range_fetch_map(const std::unordered_multimap<range<token>, inet_address>& ranges_with_sources,
const std::unordered_set<std::unique_ptr<i_source_filter>>& source_filters,
const sstring& keyspace);
#if 0
public static Multimap<InetAddress, Range<Token>> getWorkMap(Multimap<Range<Token>, InetAddress> rangesWithSourceTarget, String keyspace)
{
return getRangeFetchMap(rangesWithSourceTarget, Collections.<ISourceFilter>singleton(new FailureDetectorSourceFilter(FailureDetector.instance)), keyspace);
}
// For testing purposes
Multimap<String, Map.Entry<InetAddress, Collection<Range<Token>>>> toFetch()
{
return toFetch;
}
#endif
public:
future<streaming::stream_state> fetch_async();
private:
distributed<database>& _db;
token_metadata& _metadata;
std::unordered_set<token> _tokens;
inet_address _address;
sstring _description;
std::unordered_multimap<sstring, std::unordered_map<inet_address, std::vector<range<token>>>> _to_fetch;
std::unordered_set<std::unique_ptr<i_source_filter>> _source_filters;
stream_plan _stream_plan;
};
} // dht
<|endoftext|> |
<commit_before>#include "defines.h"
#include "Dcx.h"
mIRCLinker::mIRCLinker(void) : m_hFileMap(NULL),
m_pData(NULL),
m_mIRCHWND(NULL),
m_dwVersion(0x0),
m_iMapCnt(0),
m_hSwitchbar(NULL),
m_hToolbar(NULL),
m_hTreebar(NULL),
m_hMDI(NULL),
m_hTreeview(NULL),
m_hTreeFont(NULL),
m_hTreeImages(NULL),
m_sLastError(""),
m_wpmIRCDefaultWndProc(NULL),
m_bDebug(false)
{
}
mIRCLinker::~mIRCLinker(void)
{
}
bool mIRCLinker::isDebug() const
{
return m_bDebug;
}
bool mIRCLinker::isVersion(const WORD main, const WORD sub) const {
return getMainVersion() == main && getSubVersion() == sub;
}
bool mIRCLinker::isOrNewerVersion(const WORD main, const WORD sub) const {
return getMainVersion() > main || (getMainVersion() == main && getSubVersion() >= sub);
}
bool mIRCLinker::isAlias(const char * aliasName)
{
// check if the alias exists
return evalex(NULL, 0, "$isalias(%s)", aliasName);
}
void mIRCLinker::load(LOADINFO * lInfo) {
m_mIRCHWND = lInfo->mHwnd;
m_dwVersion = lInfo->mVersion;
if (LOWORD(m_dwVersion) == 2) { //Fix the problem that mIRC v6.20 reports itself as 6.2
m_dwVersion -= 2;
m_dwVersion += 20; // err how exactly does this fix it?
}
lInfo->mKeep = TRUE;
initMapFile();
// Check if we're in debug mode
TString isDebug;
tsEval(isDebug, "$debug");
m_bDebug = (isDebug.trim().len() > 0);
DCX_DEBUG(debug,"LoadmIRCLink", "Debug mode detected...");
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_Toolbar...");
m_hToolbar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_Toolbar",NULL);
DCX_DEBUG(debug,"LoadmIRCLink", "Finding MDIClient...");
m_hMDI = FindWindowEx(m_mIRCHWND,NULL,"MDIClient",NULL);
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_SwitchBar...");
m_hSwitchbar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_SwitchBar",NULL);
if (isOrNewerVersion(6,30)) { // class renamed for 6.30+
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_TreeBar...");
m_hTreebar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_TreeBar",NULL);
}
else {
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_TreeList...");
m_hTreebar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_TreeList",NULL);
}
if (IsWindow(m_hTreebar)) {
//m_hTreeview = GetWindow(mIRCLink.m_hTreebar,GW_CHILD);
m_hTreeview = FindWindowEx(m_hTreebar,NULL,WC_TREEVIEW,NULL);
if (IsWindow(m_hTreeview))
m_hTreeImages = TreeView_GetImageList(m_hTreeview,TVSIL_NORMAL);
}
}
void mIRCLinker::unload() {
// Reset mIRC's WndProc if changed
resetWindowProc();
UnmapViewOfFile(m_pData);
CloseHandle(m_hFileMap);
// reset the treebars font if it's been changed.
if (Dcx::mIRC.getTreeFont() != NULL) {
HFONT hfont = GetWindowFont(m_hTreeview);
if (hfont != m_hTreeFont) {
SetWindowFont( m_hTreeview, m_hTreeFont, TRUE);
DeleteFont(hfont);
}
}
}
void mIRCLinker::initMapFile() {
int cnt = 0;
if (isOrNewerVersion(6,20)) {
TString map_name;
cnt = 1;
m_hFileMap = NULL;
while ((m_hFileMap == NULL) && (cnt < 256)) {
// create mapfile name.
map_name.sprintf("mIRC%d",cnt);
// create mapfile.
m_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,0,4096,map_name.to_chr());
// if create failed, fall back on old method.
if ((m_hFileMap == NULL) || (m_hFileMap == INVALID_HANDLE_VALUE)) {
cnt = 0;
break;
}
// if mapfile already exists then close & try another name.
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(m_hFileMap);
m_hFileMap = NULL;
}
else
break;
cnt++;
}
if (cnt == 256)
cnt = 0;
}
m_iMapCnt = cnt; // set mapfile counter for SendMessage()'s
// use old method for < mirc 6.2 or when new method fails.
if (cnt == 0) {
m_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, 4096, "mIRC");
}
m_pData = (LPSTR) MapViewOfFile(m_hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
HWND mIRCLinker::getSwitchbar() const
{
return m_hSwitchbar;
}
HWND mIRCLinker::getToolbar() const
{
return m_hToolbar;
}
HWND mIRCLinker::getTreebar() const
{
return m_hTreebar;
}
HWND mIRCLinker::getTreeview() const
{
return m_hTreeview;
}
HIMAGELIST mIRCLinker::getTreeImages() const
{
return m_hTreeImages;
}
HFONT mIRCLinker::getTreeFont() const
{
return m_hTreeFont;
}
HWND mIRCLinker::getMDIClient() const
{
return m_hMDI;
}
HWND mIRCLinker::getHWND() const
{
return this->m_mIRCHWND;
}
DWORD mIRCLinker::getVersion() const {
return m_dwVersion;
}
WORD mIRCLinker::getMainVersion() const {
return LOWORD(m_dwVersion);
}
WORD mIRCLinker::getSubVersion() const {
return HIWORD(m_dwVersion);
}
bool mIRCLinker::setTreeFont(HFONT newFont)
{
HFONT f = GetWindowFont(m_hTreeview);
if (m_hTreeFont == NULL)
m_hTreeFont = f;
SetWindowFont( m_hTreeview, newFont, TRUE);
if (f != m_hTreeFont)
DeleteFont(f);
return true;
}
void mIRCLinker::hookWindowProc(WNDPROC newProc)
{
m_wpmIRCDefaultWndProc = SubclassWindow(m_mIRCHWND, newProc);
}
void mIRCLinker::resetWindowProc(void) {
if (m_wpmIRCDefaultWndProc != NULL)
SubclassWindow(m_mIRCHWND, m_wpmIRCDefaultWndProc);
}
LRESULT mIRCLinker::callDefaultWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
return CallWindowProc(m_wpmIRCDefaultWndProc, hWnd, Msg, wParam, lParam);
}
/*!
* \brief Requests mIRC $identifiers to be evaluated.
*
* Allow sufficient characters to be returned.
*/
bool mIRCLinker::eval(char *res, const int maxlen, const char *data) {
lstrcpy(m_pData, data);
SendMessage(m_mIRCHWND, WM_USER + 201, 0, m_iMapCnt);
if (res != NULL) lstrcpyn(res, m_pData, maxlen);
if (lstrcmp(m_pData, "$false") == 0) return false;
return true;
}
bool mIRCLinker::tsEval(TString &res, const char *data) {
lstrcpy(m_pData, data);
SendMessage(m_mIRCHWND, WM_USER + 201, 0, m_iMapCnt);
res = m_pData;
if (lstrcmp(m_pData, "$false") == 0) return false;
return true;
}
/*!
* \brief Requests mIRC $identifiers to be evaluated.
*
* Allow sufficient characters to be returned.
* Requests mIRC to perform command using vsprintf.
*/
bool mIRCLinker::evalex(char *res, const int maxlen, const char *szFormat, ...)
{
TString line;
va_list args;
va_start(args, szFormat);
line.vprintf(szFormat, &args);
va_end( args );
return eval(res, maxlen, line.to_chr());
}
bool mIRCLinker::tsEvalex(TString &res, const char *szFormat, ...)
{
TString line;
va_list args;
va_start(args, szFormat);
line.vprintf(szFormat, &args);
va_end( args );
return tsEval(res, line.to_chr());
}
bool mIRCLinker::exec(const char *data)
{
lstrcpy(m_pData, data);
SendMessage(m_mIRCHWND, WM_USER + 200, 0, m_iMapCnt);
if (lstrlen(m_pData) == 0) return true;
return false;
}
bool mIRCLinker::execex(const char *szFormat, ...)
{
TString line;
va_list args;
va_start(args, szFormat);
line.vprintf(szFormat, &args);
va_end( args );
return exec(line.to_chr());
}
void mIRCLinker::signal(const char *msg) {
wsprintf(m_pData, "//.signal -n DCX %s", msg);
SendMessage(m_mIRCHWND, WM_USER + 200, 0, m_iMapCnt);
}
/*!
* \brief Sends a signal to mIRC.
*
* This method allows for multiple parameters.
*/
void mIRCLinker::signalex(const bool allow, const char *szFormat, ...) {
if (!allow)
return;
TString msg;
va_list args;
va_start(args, szFormat);
msg.vprintf(szFormat, &args);
va_end(args);
signal(msg.to_chr());
}
/*!
* \brief Sends a debug message to mIRC (with formatting).
*
* This method allows for multiple parameters.
*/
#if DCX_DEBUG_OUTPUT
void mIRCLinker::debug(const char *cmd, const char *msg) {
if (!isDebug()) return;
TString err;
err.sprintf("D_DEBUG %s (%s)", cmd, msg);
echo(err.to_chr());
}
#endif
/*!
* \brief Displays output text to the mIRC status window.
*/
void mIRCLinker::echo(const char *data) {
wsprintf(m_pData, "//echo -s %s", data);
SendMessage(m_mIRCHWND, WM_USER + 200, 0, m_iMapCnt);
}
<commit_msg>[mIRCLinker] removed unneeded setting of m_sLastError to "". Dev Build 11 released to forum.<commit_after>#include "defines.h"
#include "Dcx.h"
mIRCLinker::mIRCLinker(void) : m_hFileMap(NULL),
m_pData(NULL),
m_mIRCHWND(NULL),
m_dwVersion(0x0),
m_iMapCnt(0),
m_hSwitchbar(NULL),
m_hToolbar(NULL),
m_hTreebar(NULL),
m_hMDI(NULL),
m_hTreeview(NULL),
m_hTreeFont(NULL),
m_hTreeImages(NULL),
//m_sLastError(""),
m_wpmIRCDefaultWndProc(NULL),
m_bDebug(false)
{
}
mIRCLinker::~mIRCLinker(void)
{
}
bool mIRCLinker::isDebug() const
{
return m_bDebug;
}
bool mIRCLinker::isVersion(const WORD main, const WORD sub) const {
return getMainVersion() == main && getSubVersion() == sub;
}
bool mIRCLinker::isOrNewerVersion(const WORD main, const WORD sub) const {
return getMainVersion() > main || (getMainVersion() == main && getSubVersion() >= sub);
}
bool mIRCLinker::isAlias(const char * aliasName)
{
// check if the alias exists
return evalex(NULL, 0, "$isalias(%s)", aliasName);
}
void mIRCLinker::load(LOADINFO * lInfo) {
m_mIRCHWND = lInfo->mHwnd;
m_dwVersion = lInfo->mVersion;
if (LOWORD(m_dwVersion) == 2) { //Fix the problem that mIRC v6.20 reports itself as 6.2
m_dwVersion -= 2;
m_dwVersion += 20; // err how exactly does this fix it?
}
lInfo->mKeep = TRUE;
initMapFile();
// Check if we're in debug mode
TString isDebug;
tsEval(isDebug, "$debug");
m_bDebug = (isDebug.trim().len() > 0);
DCX_DEBUG(debug,"LoadmIRCLink", "Debug mode detected...");
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_Toolbar...");
m_hToolbar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_Toolbar",NULL);
DCX_DEBUG(debug,"LoadmIRCLink", "Finding MDIClient...");
m_hMDI = FindWindowEx(m_mIRCHWND,NULL,"MDIClient",NULL);
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_SwitchBar...");
m_hSwitchbar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_SwitchBar",NULL);
if (isOrNewerVersion(6,30)) { // class renamed for 6.30+
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_TreeBar...");
m_hTreebar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_TreeBar",NULL);
}
else {
DCX_DEBUG(debug,"LoadmIRCLink", "Finding mIRC_TreeList...");
m_hTreebar = FindWindowEx(m_mIRCHWND,NULL,"mIRC_TreeList",NULL);
}
if (IsWindow(m_hTreebar)) {
//m_hTreeview = GetWindow(mIRCLink.m_hTreebar,GW_CHILD);
m_hTreeview = FindWindowEx(m_hTreebar,NULL,WC_TREEVIEW,NULL);
if (IsWindow(m_hTreeview))
m_hTreeImages = TreeView_GetImageList(m_hTreeview,TVSIL_NORMAL);
}
}
void mIRCLinker::unload() {
// Reset mIRC's WndProc if changed
resetWindowProc();
UnmapViewOfFile(m_pData);
CloseHandle(m_hFileMap);
// reset the treebars font if it's been changed.
if (Dcx::mIRC.getTreeFont() != NULL) {
HFONT hfont = GetWindowFont(m_hTreeview);
if (hfont != m_hTreeFont) {
SetWindowFont( m_hTreeview, m_hTreeFont, TRUE);
DeleteFont(hfont);
}
}
}
void mIRCLinker::initMapFile() {
int cnt = 0;
if (isOrNewerVersion(6,20)) {
TString map_name;
cnt = 1;
m_hFileMap = NULL;
while ((m_hFileMap == NULL) && (cnt < 256)) {
// create mapfile name.
map_name.sprintf("mIRC%d",cnt);
// create mapfile.
m_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,0,4096,map_name.to_chr());
// if create failed, fall back on old method.
if ((m_hFileMap == NULL) || (m_hFileMap == INVALID_HANDLE_VALUE)) {
cnt = 0;
break;
}
// if mapfile already exists then close & try another name.
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(m_hFileMap);
m_hFileMap = NULL;
}
else
break;
cnt++;
}
if (cnt == 256)
cnt = 0;
}
m_iMapCnt = cnt; // set mapfile counter for SendMessage()'s
// use old method for < mirc 6.2 or when new method fails.
if (cnt == 0) {
m_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, 4096, "mIRC");
}
m_pData = (LPSTR) MapViewOfFile(m_hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
HWND mIRCLinker::getSwitchbar() const
{
return m_hSwitchbar;
}
HWND mIRCLinker::getToolbar() const
{
return m_hToolbar;
}
HWND mIRCLinker::getTreebar() const
{
return m_hTreebar;
}
HWND mIRCLinker::getTreeview() const
{
return m_hTreeview;
}
HIMAGELIST mIRCLinker::getTreeImages() const
{
return m_hTreeImages;
}
HFONT mIRCLinker::getTreeFont() const
{
return m_hTreeFont;
}
HWND mIRCLinker::getMDIClient() const
{
return m_hMDI;
}
HWND mIRCLinker::getHWND() const
{
return this->m_mIRCHWND;
}
DWORD mIRCLinker::getVersion() const {
return m_dwVersion;
}
WORD mIRCLinker::getMainVersion() const {
return LOWORD(m_dwVersion);
}
WORD mIRCLinker::getSubVersion() const {
return HIWORD(m_dwVersion);
}
bool mIRCLinker::setTreeFont(HFONT newFont)
{
HFONT f = GetWindowFont(m_hTreeview);
if (m_hTreeFont == NULL)
m_hTreeFont = f;
SetWindowFont( m_hTreeview, newFont, TRUE);
if (f != m_hTreeFont)
DeleteFont(f);
return true;
}
void mIRCLinker::hookWindowProc(WNDPROC newProc)
{
m_wpmIRCDefaultWndProc = SubclassWindow(m_mIRCHWND, newProc);
}
void mIRCLinker::resetWindowProc(void) {
if (m_wpmIRCDefaultWndProc != NULL)
SubclassWindow(m_mIRCHWND, m_wpmIRCDefaultWndProc);
}
LRESULT mIRCLinker::callDefaultWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
return CallWindowProc(m_wpmIRCDefaultWndProc, hWnd, Msg, wParam, lParam);
}
/*!
* \brief Requests mIRC $identifiers to be evaluated.
*
* Allow sufficient characters to be returned.
*/
bool mIRCLinker::eval(char *res, const int maxlen, const char *data) {
lstrcpy(m_pData, data);
SendMessage(m_mIRCHWND, WM_USER + 201, 0, m_iMapCnt);
if (res != NULL) lstrcpyn(res, m_pData, maxlen);
if (lstrcmp(m_pData, "$false") == 0) return false;
return true;
}
bool mIRCLinker::tsEval(TString &res, const char *data) {
lstrcpy(m_pData, data);
SendMessage(m_mIRCHWND, WM_USER + 201, 0, m_iMapCnt);
res = m_pData;
if (lstrcmp(m_pData, "$false") == 0) return false;
return true;
}
/*!
* \brief Requests mIRC $identifiers to be evaluated.
*
* Allow sufficient characters to be returned.
* Requests mIRC to perform command using vsprintf.
*/
bool mIRCLinker::evalex(char *res, const int maxlen, const char *szFormat, ...)
{
TString line;
va_list args;
va_start(args, szFormat);
line.vprintf(szFormat, &args);
va_end( args );
return eval(res, maxlen, line.to_chr());
}
bool mIRCLinker::tsEvalex(TString &res, const char *szFormat, ...)
{
TString line;
va_list args;
va_start(args, szFormat);
line.vprintf(szFormat, &args);
va_end( args );
return tsEval(res, line.to_chr());
}
bool mIRCLinker::exec(const char *data)
{
lstrcpy(m_pData, data);
SendMessage(m_mIRCHWND, WM_USER + 200, 0, m_iMapCnt);
if (lstrlen(m_pData) == 0) return true;
return false;
}
bool mIRCLinker::execex(const char *szFormat, ...)
{
TString line;
va_list args;
va_start(args, szFormat);
line.vprintf(szFormat, &args);
va_end( args );
return exec(line.to_chr());
}
void mIRCLinker::signal(const char *msg) {
wsprintf(m_pData, "//.signal -n DCX %s", msg);
SendMessage(m_mIRCHWND, WM_USER + 200, 0, m_iMapCnt);
}
/*!
* \brief Sends a signal to mIRC.
*
* This method allows for multiple parameters.
*/
void mIRCLinker::signalex(const bool allow, const char *szFormat, ...) {
if (!allow)
return;
TString msg;
va_list args;
va_start(args, szFormat);
msg.vprintf(szFormat, &args);
va_end(args);
signal(msg.to_chr());
}
/*!
* \brief Sends a debug message to mIRC (with formatting).
*
* This method allows for multiple parameters.
*/
#if DCX_DEBUG_OUTPUT
void mIRCLinker::debug(const char *cmd, const char *msg) {
if (!isDebug()) return;
TString err;
err.sprintf("D_DEBUG %s (%s)", cmd, msg);
echo(err.to_chr());
}
#endif
/*!
* \brief Displays output text to the mIRC status window.
*/
void mIRCLinker::echo(const char *data) {
wsprintf(m_pData, "//echo -s %s", data);
SendMessage(m_mIRCHWND, WM_USER + 200, 0, m_iMapCnt);
}
<|endoftext|> |
<commit_before>#include <math.h>
#include <stdio.h>
#include "HalideRuntime.h"
#include "HalideBuffer.h"
#include <assert.h>
#include "tiled_blur.h"
using namespace Halide::Runtime;
const int W = 80, H = 80;
int my_halide_trace(void *user_context, const halide_trace_event_t *ev) {
if (ev->event == halide_trace_begin_realization) {
assert(ev->dimensions == 6);
int min_x = ev->coordinates[0], width = ev->coordinates[1];
int min_y = ev->coordinates[2], height = ev->coordinates[3];
int max_x = min_x + width - 1;
int max_y = min_y + height - 1;
printf("Using %d x %d input tile over [%d - %d] x [%d - %d]\n", width, height, min_x, max_x,
min_y, max_y);
assert(min_x >= 0 && min_y >= 0 && max_x < W && max_y < H);
// The input is large enough that the boundary condition could
// only ever apply on one side.
assert(width == 33 || width == 34);
assert(height == 33 || height == 34);
}
return 0;
}
Buffer<> buffer_factory_planar(halide_type_t t, int w, int h, int c) {
return Buffer<>(t, w, h, c);
}
Buffer<> buffer_factory_interleaved(halide_type_t t, int w, int h, int c) {
return Buffer<>::make_interleaved(t, w, h, c);
}
void test(Buffer<> (*factory)(halide_type_t, int w, int h, int c)) {
Buffer<uint8_t> input = factory(halide_type_of<uint8_t>(), W, H, 3);
input.for_each_element([&](int x, int y, int c) {
input(x, y, c) = (uint8_t)(x + y + c);
});
Buffer<uint8_t> output = factory(halide_type_of<uint8_t>(), W, H, 3);
printf("Evaluating output over %d x %d in tiles of size 32 x 32\n", W, H);
tiled_blur(input, output);
}
int main(int argc, char **argv) {
halide_set_custom_trace(&my_halide_trace);
printf("Testing planar buffer...\n");
test(buffer_factory_planar);
printf("Testing interleaved buffer...\n");
test(buffer_factory_interleaved);
printf("Success!\n");
return 0;
}
<commit_msg>Tweak tiled blur pattern<commit_after>#include <math.h>
#include <stdio.h>
#include "HalideRuntime.h"
#include "HalideBuffer.h"
#include <assert.h>
#include "tiled_blur.h"
using namespace Halide::Runtime;
const int W = 80, H = 80;
int my_halide_trace(void *user_context, const halide_trace_event_t *ev) {
if (ev->event == halide_trace_begin_realization) {
assert(ev->dimensions == 6);
int min_x = ev->coordinates[0], width = ev->coordinates[1];
int min_y = ev->coordinates[2], height = ev->coordinates[3];
int max_x = min_x + width - 1;
int max_y = min_y + height - 1;
printf("Using %d x %d input tile over [%d - %d] x [%d - %d]\n", width, height, min_x, max_x,
min_y, max_y);
assert(min_x >= 0 && min_y >= 0 && max_x < W && max_y < H);
// The input is large enough that the boundary condition could
// only ever apply on one side.
assert(width == 33 || width == 34);
assert(height == 33 || height == 34);
}
return 0;
}
Buffer<> buffer_factory_planar(halide_type_t t, int w, int h, int c) {
return Buffer<>(t, w, h, c);
}
Buffer<> buffer_factory_interleaved(halide_type_t t, int w, int h, int c) {
return Buffer<>::make_interleaved(t, w, h, c);
}
void test(Buffer<> (*factory)(halide_type_t, int w, int h, int c)) {
Buffer<uint8_t> input = factory(halide_type_of<uint8_t>(), W, H, 3);
input.for_each_element([&](int x, int y, int c) {
// Just an arbitrary color pattern with enough variation to notice the brighten + blur
if (c == 0) {
input(x, y, c) = (uint8_t)((x % 7) + (y % 3));
} else if (c == 1) {
input(x, y, c) = (uint8_t)(x + y);
} else {
input(x, y, c) = (uint8_t)((x * 5) + (y * 2));
}
});
Buffer<uint8_t> output = factory(halide_type_of<uint8_t>(), W, H, 3);
printf("Evaluating output over %d x %d in tiles of size 32 x 32\n", W, H);
tiled_blur(input, output);
}
int main(int argc, char **argv) {
halide_set_custom_trace(&my_halide_trace);
printf("Testing planar buffer...\n");
test(buffer_factory_planar);
printf("Testing interleaved buffer...\n");
test(buffer_factory_interleaved);
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>//=============================================================================
//
// OpenMesh
// Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen
// www.openmesh.org
//
//-----------------------------------------------------------------------------
//
// License
//
// 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, version 2.1.
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//-----------------------------------------------------------------------------
//
// $Revision: 1.3 $
// $Date: 2008-03-11 09:18:01 $
//
//=============================================================================
#ifdef _MSC_VER
# pragma warning(disable: 4267 4311)
#endif
#include <iostream>
#include <fstream>
#include <getopt.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include "DecimaterViewerWidget.hh"
#ifdef ARCH_DARWIN
#include <glut.h>
#else
#include <GL/glut.h>
#endif
void usage_and_exit(int xcode);
int main(int argc, char **argv)
{
#if defined(OM_USE_OSG) && OM_USE_OSG
osg::osgInit(argc, argv);
#endif
// OpenGL check
QApplication::setColorSpec( QApplication::CustomColor );
QApplication app(argc,argv);
glutInit(&argc,argv);
if ( !QGLFormat::hasOpenGL() ) {
QString msg = "System has no OpenGL support!";
QMessageBox::critical( NULL, "OpenGL", msg + argv[1] );
return -1;
}
int c;
OpenMesh::IO::Options opt;
while ( (c=getopt(argc,argv,"s"))!=-1 )
{
switch(c)
{
case 's': opt += OpenMesh::IO::Options::Swap; break;
case 'h':
usage_and_exit(0);
default:
usage_and_exit(1);
}
}
// create widget
DecimaterViewerWidget w(0, "Viewer");
// app.setMainWidget(&w);
w.resize(400, 400);
w.show();
// load scene
if ( optind < argc )
{
if ( ! w.open_mesh(argv[optind], opt) )
{
QString msg = "Cannot read mesh from file:\n '";
msg += argv[optind];
msg += "'";
QMessageBox::critical( NULL, w.windowTitle(), msg );
return 1;
}
}
if ( ++optind < argc )
{
if ( ! w.open_texture( argv[optind] ) )
{
QString msg = "Cannot load texture image from file:\n '";
msg += argv[optind];
msg += "'\n\nPossible reasons:\n";
msg += "- Mesh file didn't provide texture coordinates\n";
msg += "- Texture file does not exist\n";
msg += "- Texture file is not accessible.\n";
QMessageBox::warning( NULL, w.windowTitle(), msg );
}
}
return app.exec();
}
void usage_and_exit(int xcode)
{
std::cout << "Usage: decimaterviewer [-s] [mesh] [texture]\n" << std::endl;
std::cout << "Options:\n"
<< " -s\n"
<< " Reverse byte order, when reading binary files.\n"
<< std::endl;
exit(xcode);
}
<commit_msg>Fixed Path for getopt<commit_after>//=============================================================================
//
// OpenMesh
// Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen
// www.openmesh.org
//
//-----------------------------------------------------------------------------
//
// License
//
// 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, version 2.1.
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//-----------------------------------------------------------------------------
//
// $Revision: 1.3 $
// $Date: 2008-03-11 09:18:01 $
//
//=============================================================================
#ifdef _MSC_VER
# pragma warning(disable: 4267 4311)
#endif
#include <iostream>
#include <fstream>
#include <OpenMesh/Tools/Utils/getopt.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include "DecimaterViewerWidget.hh"
#ifdef ARCH_DARWIN
#include <glut.h>
#else
#include <GL/glut.h>
#endif
void usage_and_exit(int xcode);
int main(int argc, char **argv)
{
#if defined(OM_USE_OSG) && OM_USE_OSG
osg::osgInit(argc, argv);
#endif
// OpenGL check
QApplication::setColorSpec( QApplication::CustomColor );
QApplication app(argc,argv);
glutInit(&argc,argv);
if ( !QGLFormat::hasOpenGL() ) {
QString msg = "System has no OpenGL support!";
QMessageBox::critical( NULL, "OpenGL", msg + argv[1] );
return -1;
}
int c;
OpenMesh::IO::Options opt;
while ( (c=getopt(argc,argv,"s"))!=-1 )
{
switch(c)
{
case 's': opt += OpenMesh::IO::Options::Swap; break;
case 'h':
usage_and_exit(0);
default:
usage_and_exit(1);
}
}
// create widget
DecimaterViewerWidget w(0, "Viewer");
// app.setMainWidget(&w);
w.resize(400, 400);
w.show();
// load scene
if ( optind < argc )
{
if ( ! w.open_mesh(argv[optind], opt) )
{
QString msg = "Cannot read mesh from file:\n '";
msg += argv[optind];
msg += "'";
QMessageBox::critical( NULL, w.windowTitle(), msg );
return 1;
}
}
if ( ++optind < argc )
{
if ( ! w.open_texture( argv[optind] ) )
{
QString msg = "Cannot load texture image from file:\n '";
msg += argv[optind];
msg += "'\n\nPossible reasons:\n";
msg += "- Mesh file didn't provide texture coordinates\n";
msg += "- Texture file does not exist\n";
msg += "- Texture file is not accessible.\n";
QMessageBox::warning( NULL, w.windowTitle(), msg );
}
}
return app.exec();
}
void usage_and_exit(int xcode)
{
std::cout << "Usage: decimaterviewer [-s] [mesh] [texture]\n" << std::endl;
std::cout << "Options:\n"
<< " -s\n"
<< " Reverse byte order, when reading binary files.\n"
<< std::endl;
exit(xcode);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: OOXMLDocumentImpl.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: fridrich_strba $ $Date: 2007-05-22 19:40:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include "OOXMLDocumentImpl.hxx"
#include "OOXMLSaxHandler.hxx"
#include <iostream>
namespace ooxml
{
using namespace ::std;
OOXMLDocumentImpl::OOXMLDocumentImpl
(OOXMLStream::Pointer_t pStream)
: mpStream(pStream)
{
}
OOXMLDocumentImpl::~OOXMLDocumentImpl()
{
}
void OOXMLDocumentImpl::resolveSubStream(Stream & rStream,
OOXMLStream::StreamType_t nType)
{
OOXMLStream::Pointer_t pStream
(OOXMLDocumentFactory::createStream(mpStream, nType));
uno::Reference < xml::sax::XParser > oSaxParser =
pStream->getParser();
if (oSaxParser.is())
{
OOXMLSaxHandler * pSaxHandler = new OOXMLSaxHandler(rStream, this);
pSaxHandler->setXNoteId(msXNoteId);
uno::Reference<xml::sax::XDocumentHandler>
xDocumentHandler
(static_cast<cppu::OWeakObject *>
(pSaxHandler), uno::UNO_QUERY);
oSaxParser->setDocumentHandler( xDocumentHandler );
uno::Reference<io::XInputStream> xInputStream =
pStream->getInputStream();
if (xInputStream.is())
{
// uno::Sequence<sal_Int8> aSeq(1024);
// while (xStylesInputStream->readBytes(aSeq, 1024) > 0)
// {
// string tmpStr(reinterpret_cast<char *>(&aSeq[0]));
// clog << tmpStr;
// }
struct xml::sax::InputSource oInputSource;
oInputSource.aInputStream = xInputStream;
oSaxParser->parseStream(oInputSource);
xInputStream->closeInput();
}
}
}
void OOXMLDocumentImpl::setXNoteId(const rtl::OUString & rId)
{
msXNoteId = rId;
}
doctok::Reference<Stream>::Pointer_t
OOXMLDocumentImpl::getSubStream(const rtl::OUString & rId)
{
OOXMLStream::Pointer_t pStream
(OOXMLDocumentFactory::createStream(mpStream, rId));
return doctok::Reference<Stream>::Pointer_t(new OOXMLDocumentImpl(pStream));
}
doctok::Reference<Stream>::Pointer_t
OOXMLDocumentImpl::getXNoteStream(OOXMLStream::StreamType_t nType, const rtl::OUString & /* rId */)
{
OOXMLStream::Pointer_t pStream =
(OOXMLDocumentFactory::createStream(mpStream, nType));
OOXMLDocumentImpl * pDocument = new OOXMLDocumentImpl(pStream);
pDocument->setXNoteId(msXNoteId);
return doctok::Reference<Stream>::Pointer_t(pDocument);
}
void OOXMLDocumentImpl::resolveFootnote(Stream & rStream,
const rtl::OUString & rNoteId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getXNoteStream(OOXMLStream::FOOTNOTES, rNoteId);
rStream.substream(NS_rtf::LN_footnote, pStream);
}
void OOXMLDocumentImpl::resolveEndnote(Stream & rStream,
const rtl::OUString & rNoteId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getXNoteStream(OOXMLStream::ENDNOTES, rNoteId);
rStream.substream(NS_rtf::LN_endnote, pStream);
}
void OOXMLDocumentImpl::resolveHeader(Stream & rStream,
const sal_Int32 type,
const rtl::OUString & rId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getSubStream(rId);
switch (type)
{
case NS_ooxml::LN_Value_ST_HrdFtr_even:
rStream.substream(NS_rtf::LN_headerl, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_default: // here we assume that default is right, but not necessarily true :-(
rStream.substream(NS_rtf::LN_headerr, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_first:
rStream.substream(NS_rtf::LN_headerf, pStream);
break;
default:
break;
}
}
void OOXMLDocumentImpl::resolveFooter(Stream & rStream,
const sal_Int32 type,
const rtl::OUString & rId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getSubStream(rId);
switch (type)
{
case NS_ooxml::LN_Value_ST_HrdFtr_even:
rStream.substream(NS_rtf::LN_footerl, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_default: // here we assume that default is right, but not necessarily true :-(
rStream.substream(NS_rtf::LN_footerr, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_first:
rStream.substream(NS_rtf::LN_footerf, pStream);
break;
default:
break;
}
}
void OOXMLDocumentImpl::resolve(Stream & rStream)
{
{
uno::Reference < xml::sax::XParser > oSaxParser = mpStream->getParser();
if (oSaxParser.is())
{
OOXMLSaxHandler * pSaxHandler = new OOXMLSaxHandler(rStream, this);
pSaxHandler->setXNoteId(msXNoteId);
uno::Reference<xml::sax::XDocumentHandler>
xDocumentHandler
(static_cast<cppu::OWeakObject *>
(pSaxHandler), uno::UNO_QUERY);
oSaxParser->setDocumentHandler( xDocumentHandler );
resolveSubStream(rStream, OOXMLStream::NUMBERING);
resolveSubStream(rStream, OOXMLStream::FONTTABLE);
resolveSubStream(rStream, OOXMLStream::STYLES);
uno::Reference<io::XInputStream> xInputStream
(mpStream->getInputStream());
struct xml::sax::InputSource oInputSource;
oInputSource.aInputStream = xInputStream;
oSaxParser->parseStream(oInputSource);
xInputStream->closeInput();
}
}
}
string OOXMLDocumentImpl::getType() const
{
return "OOXMLDocumentImpl";
}
OOXMLDocument *
OOXMLDocumentFactory::createDocument
(OOXMLStream::Pointer_t pStream)
{
return new OOXMLDocumentImpl(pStream);
}
}
<commit_msg>footnotes and endnotes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: OOXMLDocumentImpl.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hbrinkm $ $Date: 2007-05-23 15:32:05 $
*
* 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 _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include "OOXMLDocumentImpl.hxx"
#include "OOXMLSaxHandler.hxx"
#include <iostream>
namespace ooxml
{
using namespace ::std;
OOXMLDocumentImpl::OOXMLDocumentImpl
(OOXMLStream::Pointer_t pStream)
: mpStream(pStream)
{
}
OOXMLDocumentImpl::~OOXMLDocumentImpl()
{
}
void OOXMLDocumentImpl::resolveSubStream(Stream & rStream,
OOXMLStream::StreamType_t nType)
{
OOXMLStream::Pointer_t pStream
(OOXMLDocumentFactory::createStream(mpStream, nType));
uno::Reference < xml::sax::XParser > oSaxParser =
pStream->getParser();
if (oSaxParser.is())
{
OOXMLSaxHandler * pSaxHandler = new OOXMLSaxHandler(rStream, this);
pSaxHandler->setXNoteId(msXNoteId);
uno::Reference<xml::sax::XDocumentHandler>
xDocumentHandler
(static_cast<cppu::OWeakObject *>
(pSaxHandler), uno::UNO_QUERY);
oSaxParser->setDocumentHandler( xDocumentHandler );
uno::Reference<io::XInputStream> xInputStream =
pStream->getInputStream();
if (xInputStream.is())
{
// uno::Sequence<sal_Int8> aSeq(1024);
// while (xStylesInputStream->readBytes(aSeq, 1024) > 0)
// {
// string tmpStr(reinterpret_cast<char *>(&aSeq[0]));
// clog << tmpStr;
// }
struct xml::sax::InputSource oInputSource;
oInputSource.aInputStream = xInputStream;
oSaxParser->parseStream(oInputSource);
xInputStream->closeInput();
}
}
}
void OOXMLDocumentImpl::setXNoteId(const rtl::OUString & rId)
{
msXNoteId = rId;
}
doctok::Reference<Stream>::Pointer_t
OOXMLDocumentImpl::getSubStream(const rtl::OUString & rId)
{
OOXMLStream::Pointer_t pStream
(OOXMLDocumentFactory::createStream(mpStream, rId));
return doctok::Reference<Stream>::Pointer_t(new OOXMLDocumentImpl(pStream));
}
doctok::Reference<Stream>::Pointer_t
OOXMLDocumentImpl::getXNoteStream(OOXMLStream::StreamType_t nType, const rtl::OUString & rId)
{
OOXMLStream::Pointer_t pStream =
(OOXMLDocumentFactory::createStream(mpStream, nType));
OOXMLDocumentImpl * pDocument = new OOXMLDocumentImpl(pStream);
pDocument->setXNoteId(rId);
return doctok::Reference<Stream>::Pointer_t(pDocument);
}
void OOXMLDocumentImpl::resolveFootnote(Stream & rStream,
const rtl::OUString & rNoteId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getXNoteStream(OOXMLStream::FOOTNOTES, rNoteId);
rStream.substream(NS_rtf::LN_footnote, pStream);
}
void OOXMLDocumentImpl::resolveEndnote(Stream & rStream,
const rtl::OUString & rNoteId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getXNoteStream(OOXMLStream::ENDNOTES, rNoteId);
rStream.substream(NS_rtf::LN_endnote, pStream);
}
void OOXMLDocumentImpl::resolveHeader(Stream & rStream,
const sal_Int32 type,
const rtl::OUString & rId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getSubStream(rId);
switch (type)
{
case NS_ooxml::LN_Value_ST_HrdFtr_even:
rStream.substream(NS_rtf::LN_headerl, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_default: // here we assume that default is right, but not necessarily true :-(
rStream.substream(NS_rtf::LN_headerr, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_first:
rStream.substream(NS_rtf::LN_headerf, pStream);
break;
default:
break;
}
}
void OOXMLDocumentImpl::resolveFooter(Stream & rStream,
const sal_Int32 type,
const rtl::OUString & rId)
{
doctok::Reference<Stream>::Pointer_t pStream =
getSubStream(rId);
switch (type)
{
case NS_ooxml::LN_Value_ST_HrdFtr_even:
rStream.substream(NS_rtf::LN_footerl, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_default: // here we assume that default is right, but not necessarily true :-(
rStream.substream(NS_rtf::LN_footerr, pStream);
break;
case NS_ooxml::LN_Value_ST_HrdFtr_first:
rStream.substream(NS_rtf::LN_footerf, pStream);
break;
default:
break;
}
}
void OOXMLDocumentImpl::resolve(Stream & rStream)
{
uno::Reference < xml::sax::XParser > oSaxParser = mpStream->getParser();
if (oSaxParser.is())
{
OOXMLSaxHandler * pSaxHandler = new OOXMLSaxHandler(rStream, this);
pSaxHandler->setXNoteId(msXNoteId);
uno::Reference<xml::sax::XDocumentHandler>
xDocumentHandler
(static_cast<cppu::OWeakObject *>
(pSaxHandler), uno::UNO_QUERY);
oSaxParser->setDocumentHandler( xDocumentHandler );
resolveSubStream(rStream, OOXMLStream::NUMBERING);
resolveSubStream(rStream, OOXMLStream::FONTTABLE);
resolveSubStream(rStream, OOXMLStream::STYLES);
uno::Reference<io::XInputStream> xInputStream
(mpStream->getInputStream());
struct xml::sax::InputSource oInputSource;
oInputSource.aInputStream = xInputStream;
oSaxParser->parseStream(oInputSource);
xInputStream->closeInput();
}
}
string OOXMLDocumentImpl::getType() const
{
return "OOXMLDocumentImpl";
}
OOXMLDocument *
OOXMLDocumentFactory::createDocument
(OOXMLStream::Pointer_t pStream)
{
return new OOXMLDocumentImpl(pStream);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "volum_group.h"
#include "volum.h"
#include "mounter.h"
#include "protocol/galaxy.pb.h"
#include "agent/volum/volum.h"
#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/operations.hpp"
#include "util/error_code.h"
#include "util/path_tree.h"
#include "boost/lexical_cast/lexical_cast_old.hpp"
#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>
DECLARE_string(mount_templat);
namespace baidu {
namespace galaxy {
namespace volum {
VolumGroup::VolumGroup() :
gc_index_(-1)
{
}
VolumGroup::~VolumGroup()
{
}
void VolumGroup::SetGcIndex(int gc_index)
{
assert(gc_index >= 0);
gc_index_ = gc_index;
}
void VolumGroup::AddDataVolum(const baidu::galaxy::proto::VolumRequired& data_volum)
{
boost::shared_ptr<baidu::galaxy::proto::VolumRequired> volum(new baidu::galaxy::proto::VolumRequired());
volum->CopyFrom(data_volum);
dv_description_.push_back(volum);
}
void VolumGroup::SetWorkspaceVolum(const baidu::galaxy::proto::VolumRequired& ws_volum)
{
ws_description_.reset(new baidu::galaxy::proto::VolumRequired);
ws_description_->CopyFrom(ws_volum);
}
void VolumGroup::SetContainerId(const std::string& container_id)
{
container_id_ = container_id;
}
baidu::galaxy::util::ErrorCode VolumGroup::Construct()
{
workspace_volum_ = Construct(this->ws_description_);
if (NULL == workspace_volum_.get()) {
return ERRORCODE(-1, "workspace volum is empty");
}
baidu::galaxy::util::ErrorCode ec;
for (size_t i = 0; i < dv_description_.size(); i++) {
boost::shared_ptr<Volum> v = Construct(dv_description_[i]);
if (v.get() == NULL) {
ec = ERRORCODE(-1,
"construct volum(%s->%s) failed",
dv_description_[i]->source_path().c_str(),
dv_description_[i]->dest_path().c_str());
break;
}
data_volum_.push_back(v);
}
if (data_volum_.size() != dv_description_.size()) {
for (size_t i = 0; i < data_volum_.size(); i++) {
data_volum_[i]->Destroy();
}
return ec;
}
return ERRORCODE_OK;
}
baidu::galaxy::util::ErrorCode VolumGroup::Destroy()
{
int ret = 0;
for (size_t i = 0; i < data_volum_.size(); i++) {
if (0 != data_volum_[i]->Destroy()) {
return ERRORCODE(-1,
"failed in destroying data volum(%s->%s)",
data_volum_[i]->SourcePath().c_str(),
data_volum_[i]->TargetPath().c_str());
}
}
if (0 != workspace_volum_->Destroy()) {
return ERRORCODE(-1,
"failed in destroying workspace volum");
}
return ERRORCODE_OK;
}
int VolumGroup::ExportEnv(std::map<std::string, std::string>& env)
{
env["baidu_galaxy_container_workspace_path"] = workspace_volum_->Description()->dest_path();
env["baidu_galaxy_container_workspace_abstargetpath"] = workspace_volum_->TargetPath();
env["baidu_galaxy_container_workspace_abssourcepath"] = workspace_volum_->SourcePath();
env["baidu_galaxy_container_workspace_datavolum_size"] = boost::lexical_cast<std::string>(data_volum_.size());
return 0;
}
boost::shared_ptr<google::protobuf::Message> VolumGroup::Report()
{
boost::shared_ptr<google::protobuf::Message> ret;
return ret;
}
boost::shared_ptr<Volum> VolumGroup::Construct(boost::shared_ptr<baidu::galaxy::proto::VolumRequired> dp)
{
assert(NULL != dp.get());
assert(gc_index_ >= 0);
boost::shared_ptr<Volum> volum = Volum::CreateVolum(dp);
if (NULL == volum.get()) {
return volum;
}
volum->SetDescription(dp);
volum->SetContainerId(this->container_id_);
volum->SetGcIndex(gc_index_);
if (0 != volum->Construct()) {
volum.reset();
}
return volum;
}
// FIX: a single class
int VolumGroup::MountRootfs()
{
std::vector<std::string> vm;
boost::split(vm, FLAGS_mount_templat, boost::is_any_of(","));
std::string container_path = baidu::galaxy::path::ContainerRootPath(container_id_);
for (size_t i = 0; i < vm.size(); i++) {
if (vm[i].empty()) {
continue;
}
boost::system::error_code ec;
boost::filesystem::path path(container_path);
path.append(vm[i]);
if (!boost::filesystem::exists(path, ec) && !boost::filesystem::create_directories(path, ec)) {
LOG(WARNING) << "create_directories failed: " << path.string() << ": " << ec.message();
return -1;
}
if (boost::filesystem::is_directory(path, ec)) {
LOG(INFO) << "create_directories sucessfully: " << path.string();
}
if ("/proc" == vm[i]) {
baidu::galaxy::util::ErrorCode errc = MountProc(path.string());
if (0 != errc.Code()) {
LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
return -1;
}
LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
} else {
baidu::galaxy::util::ErrorCode errc = MountDir(vm[i], path.string());
if (0 != errc.Code()) {
LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
return -1;
}
LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
}
}
return 0;
}
}
}
}
<commit_msg>rm unused var<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "volum_group.h"
#include "volum.h"
#include "mounter.h"
#include "protocol/galaxy.pb.h"
#include "agent/volum/volum.h"
#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/operations.hpp"
#include "util/error_code.h"
#include "util/path_tree.h"
#include "boost/lexical_cast/lexical_cast_old.hpp"
#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>
DECLARE_string(mount_templat);
namespace baidu {
namespace galaxy {
namespace volum {
VolumGroup::VolumGroup() :
gc_index_(-1)
{
}
VolumGroup::~VolumGroup()
{
}
void VolumGroup::SetGcIndex(int gc_index)
{
assert(gc_index >= 0);
gc_index_ = gc_index;
}
void VolumGroup::AddDataVolum(const baidu::galaxy::proto::VolumRequired& data_volum)
{
boost::shared_ptr<baidu::galaxy::proto::VolumRequired> volum(new baidu::galaxy::proto::VolumRequired());
volum->CopyFrom(data_volum);
dv_description_.push_back(volum);
}
void VolumGroup::SetWorkspaceVolum(const baidu::galaxy::proto::VolumRequired& ws_volum)
{
ws_description_.reset(new baidu::galaxy::proto::VolumRequired);
ws_description_->CopyFrom(ws_volum);
}
void VolumGroup::SetContainerId(const std::string& container_id)
{
container_id_ = container_id;
}
baidu::galaxy::util::ErrorCode VolumGroup::Construct()
{
workspace_volum_ = Construct(this->ws_description_);
if (NULL == workspace_volum_.get()) {
return ERRORCODE(-1, "workspace volum is empty");
}
baidu::galaxy::util::ErrorCode ec;
for (size_t i = 0; i < dv_description_.size(); i++) {
boost::shared_ptr<Volum> v = Construct(dv_description_[i]);
if (v.get() == NULL) {
ec = ERRORCODE(-1,
"construct volum(%s->%s) failed",
dv_description_[i]->source_path().c_str(),
dv_description_[i]->dest_path().c_str());
break;
}
data_volum_.push_back(v);
}
if (data_volum_.size() != dv_description_.size()) {
for (size_t i = 0; i < data_volum_.size(); i++) {
data_volum_[i]->Destroy();
}
return ec;
}
return ERRORCODE_OK;
}
baidu::galaxy::util::ErrorCode VolumGroup::Destroy()
{
for (size_t i = 0; i < data_volum_.size(); i++) {
if (0 != data_volum_[i]->Destroy()) {
return ERRORCODE(-1,
"failed in destroying data volum(%s->%s)",
data_volum_[i]->SourcePath().c_str(),
data_volum_[i]->TargetPath().c_str());
}
}
if (0 != workspace_volum_->Destroy()) {
return ERRORCODE(-1,
"failed in destroying workspace volum");
}
return ERRORCODE_OK;
}
int VolumGroup::ExportEnv(std::map<std::string, std::string>& env)
{
env["baidu_galaxy_container_workspace_path"] = workspace_volum_->Description()->dest_path();
env["baidu_galaxy_container_workspace_abstargetpath"] = workspace_volum_->TargetPath();
env["baidu_galaxy_container_workspace_abssourcepath"] = workspace_volum_->SourcePath();
env["baidu_galaxy_container_workspace_datavolum_size"] = boost::lexical_cast<std::string>(data_volum_.size());
return 0;
}
boost::shared_ptr<google::protobuf::Message> VolumGroup::Report()
{
boost::shared_ptr<google::protobuf::Message> ret;
return ret;
}
boost::shared_ptr<Volum> VolumGroup::Construct(boost::shared_ptr<baidu::galaxy::proto::VolumRequired> dp)
{
assert(NULL != dp.get());
assert(gc_index_ >= 0);
boost::shared_ptr<Volum> volum = Volum::CreateVolum(dp);
if (NULL == volum.get()) {
return volum;
}
volum->SetDescription(dp);
volum->SetContainerId(this->container_id_);
volum->SetGcIndex(gc_index_);
if (0 != volum->Construct()) {
volum.reset();
}
return volum;
}
// FIX: a single class
int VolumGroup::MountRootfs()
{
std::vector<std::string> vm;
boost::split(vm, FLAGS_mount_templat, boost::is_any_of(","));
std::string container_path = baidu::galaxy::path::ContainerRootPath(container_id_);
for (size_t i = 0; i < vm.size(); i++) {
if (vm[i].empty()) {
continue;
}
boost::system::error_code ec;
boost::filesystem::path path(container_path);
path.append(vm[i]);
if (!boost::filesystem::exists(path, ec) && !boost::filesystem::create_directories(path, ec)) {
LOG(WARNING) << "create_directories failed: " << path.string() << ": " << ec.message();
return -1;
}
if (boost::filesystem::is_directory(path, ec)) {
LOG(INFO) << "create_directories sucessfully: " << path.string();
}
if ("/proc" == vm[i]) {
baidu::galaxy::util::ErrorCode errc = MountProc(path.string());
if (0 != errc.Code()) {
LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
return -1;
}
LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
} else {
baidu::galaxy::util::ErrorCode errc = MountDir(vm[i], path.string());
if (0 != errc.Code()) {
LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
return -1;
}
LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
}
}
return 0;
}
}
}
}
<|endoftext|> |
<commit_before>/*
This file is part of the clang-lazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
Author: Sérgio Martins <sergio.martins@kdab.com>
Copyright (C) 2015 Sergio Martins <smartins@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "reservecandidates.h"
#include "Utils.h"
#include "checkmanager.h"
#include "StringUtils.h"
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/Lex/Lexer.h>
#include <vector>
using namespace clang;
using namespace std;
ReserveCandidates::ReserveCandidates(const std::string &name)
: CheckBase(name)
{
}
static bool isAReserveClass(CXXRecordDecl *recordDecl)
{
if (!recordDecl)
return false;
static const std::vector<std::string> classes = {"QVector", "vector", "QList", "QSet", "QVarLengthArray"};
for (auto it = classes.cbegin(), end = classes.cend(); it != end; ++it) {
if (Utils::descendsFrom(recordDecl, *it))
return true;
}
return false;
}
static bool paramIsSameTypeAs(const Type *paramType, CXXRecordDecl *classDecl)
{
if (!paramType || !classDecl)
return false;
if (paramType->getAsCXXRecordDecl() == classDecl)
return true;
const CXXRecordDecl *paramClassDecl = paramType->getPointeeCXXRecordDecl();
return paramClassDecl && paramClassDecl == classDecl;
}
static bool isCandidateMethod(CXXMethodDecl *methodDecl)
{
if (!methodDecl)
return false;
CXXRecordDecl *classDecl = methodDecl->getParent();
if (!classDecl)
return false;
auto methodName = methodDecl->getNameAsString();
if (methodName != "append" && methodName != "push_back" && methodName != "push" /*&& methodName != "insert"*/)
return false;
if (!isAReserveClass(classDecl))
return false;
// Catch cases like: QList<T>::append(const QList<T> &), which don't make sense to reserve.
// In this case, the parameter has the same type of the class
ParmVarDecl *parm = methodDecl->getParamDecl(0);
if (paramIsSameTypeAs(parm->getType().getTypePtrOrNull(), classDecl))
return false;
return true;
}
static bool isCandidateOperator(CXXOperatorCallExpr *oper)
{
if (!oper)
return false;
auto calleeDecl = dyn_cast_or_null<CXXMethodDecl>(oper->getDirectCallee());
if (!calleeDecl)
return false;
const std::string operatorName = calleeDecl->getNameAsString();
if (operatorName != "operator<<" && operatorName != "operator+=")
return false;
CXXRecordDecl *recordDecl = calleeDecl->getParent();
if (!isAReserveClass(recordDecl))
return false;
// Catch cases like: QList<T>::append(const QList<T> &), which don't make sense to reserve.
// In this case, the parameter has the same type of the class
ParmVarDecl *parm = calleeDecl->getParamDecl(0);
if (paramIsSameTypeAs(parm->getType().getTypePtrOrNull(), recordDecl))
return false;
return true;
}
bool ReserveCandidates::containerWasReserved(clang::ValueDecl *valueDecl) const
{
if (!valueDecl)
return false;
return std::find(m_foundReserves.cbegin(), m_foundReserves.cend(), valueDecl) != m_foundReserves.cend();
}
bool ReserveCandidates::acceptsValueDecl(ValueDecl *valueDecl) const
{
// Rules:
// 1. The container variable must have been defined inside a function. Too many false positives otherwise.
// free to comment that out and go through the results, maybe you'll find something.
// 2. If we found at least one reserve call, lets not warn about it.
if (!valueDecl || isa<ParmVarDecl>(valueDecl) || containerWasReserved(valueDecl))
return false;
if (Utils::isValueDeclInFunctionContext(valueDecl))
return true;
// Actually, lets allow for some member variables containers if they are being used inside CTORs or DTORs
// Those functions are only called once, so it's OK. For other member functions it's dangerous and needs
// human inspection, if such member function would be called in a loop we would be constantly calling reserve
// and in that case the built-in exponential growth is better.
if (!m_lastMethodDecl || !(isa<CXXConstructorDecl>(m_lastMethodDecl) || isa<CXXDestructorDecl>(m_lastMethodDecl)))
return false;
CXXRecordDecl *record = Utils::isMemberVariable(valueDecl);
if (record && m_lastMethodDecl->getParent() == record)
return true;
return false;
}
void ReserveCandidates::printWarning(const SourceLocation &loc)
{
emitWarning(loc, "Reserve candidate");
}
bool ReserveCandidates::isReserveCandidate(ValueDecl *valueDecl, Stmt *loopBody, CallExpr *callExpr) const
{
if (!acceptsValueDecl(valueDecl))
return false;
const bool isMemberVariable = Utils::isMemberVariable(valueDecl);
// We only want containers defined outside of the loop we're examining
if (!isMemberVariable && m_ci.getSourceManager().isBeforeInSLocAddrSpace(loopBody->getLocStart(), valueDecl->getLocStart()))
return false;
if (isInComplexLoop(callExpr, valueDecl->getLocStart(), isMemberVariable))
return false;
if (Utils::loopCanBeInterrupted(loopBody, m_ci, callExpr->getLocStart()))
return false;
return true;
}
void ReserveCandidates::VisitStmt(clang::Stmt *stm)
{
checkIfReserveStatement(stm);
auto body = Utils::bodyFromLoop(stm);
if (!body || isa<IfStmt>(body) || isa<DoStmt>(body) || isa<WhileStmt>(body))
return;
vector<CXXMemberCallExpr*> callExprs;
vector<CXXOperatorCallExpr*> operatorCalls;
// Get the list of member calls and operator<< that are direct childs of the loop statements
// If it's inside an if statement we don't care.
Utils::getChilds<CXXMemberCallExpr>(body, callExprs);
Utils::getChilds<CXXOperatorCallExpr>(body, operatorCalls); // For operator<<
for (CXXMemberCallExpr *callExpr : callExprs) {
if (!isCandidateMethod(callExpr->getMethodDecl()))
continue;
ValueDecl *valueDecl = Utils::valueDeclForMemberCall(callExpr);
if (isReserveCandidate(valueDecl, body, callExpr))
printWarning(callExpr->getLocStart());
}
for (CXXOperatorCallExpr *callExpr : operatorCalls) {
if (!isCandidateOperator(callExpr))
continue;
ValueDecl *valueDecl = Utils::valueDeclForOperatorCall(callExpr);
if (isReserveCandidate(valueDecl, body, callExpr))
printWarning(callExpr->getLocStart());
}
}
// Catch existing reserves
void ReserveCandidates::checkIfReserveStatement(Stmt *stm)
{
auto memberCall = dyn_cast<CXXMemberCallExpr>(stm);
if (!memberCall)
return;
CXXMethodDecl *methodDecl = memberCall->getMethodDecl();
if (!methodDecl || methodDecl->getNameAsString() != "reserve")
return;
CXXRecordDecl *decl = methodDecl->getParent();
if (!isAReserveClass(decl))
return;
ValueDecl *valueDecl = Utils::valueDeclForMemberCall(memberCall);
if (!valueDecl)
return;
if (std::find(m_foundReserves.cbegin(), m_foundReserves.cend(), valueDecl) == m_foundReserves.cend()) {
m_foundReserves.push_back(valueDecl);
}
}
bool ReserveCandidates::expressionIsTooComplex(clang::Expr *expr) const
{
if (!expr)
return false;
vector<CallExpr*> callExprs;
Utils::getChilds2<CallExpr>(expr, callExprs);
for (CallExpr *callExpr : callExprs) {
QualType qt = callExpr->getType();
const Type *t = qt.getTypePtrOrNull();
if (t && (!t->isIntegerType() || t->isBooleanType()))
return true;
}
vector<ArraySubscriptExpr*> subscriptExprs;
Utils::getChilds2<ArraySubscriptExpr>(expr, subscriptExprs);
if (!subscriptExprs.empty())
return true;
BinaryOperator* binary = dyn_cast<BinaryOperator>(expr);
if (binary && binary->isAssignmentOp()) { // Filter things like for ( ...; ...; next = node->next)
Expr *rhs = binary->getRHS();
if (isa<MemberExpr>(rhs) || (isa<ImplicitCastExpr>(rhs) && dyn_cast_or_null<MemberExpr>(Utils::getFirstChildAtDepth(rhs, 1))))
return true;
}
// llvm::errs() << expr->getStmtClassName() << "\n";
return false;
}
bool ReserveCandidates::loopIsTooComplex(clang::Stmt *stm, bool &isLoop) const
{
isLoop = false;
auto forstm = dyn_cast<ForStmt>(stm);
if (forstm) {
isLoop = true;
return forstm->getInc() == nullptr || expressionIsTooComplex(forstm->getCond()) || expressionIsTooComplex(forstm->getInc());
}
auto whilestm = dyn_cast<WhileStmt>(stm);
if (whilestm) {
isLoop = true;
return expressionIsTooComplex(whilestm->getCond());
}
auto dostm = dyn_cast<DoStmt>(stm);
if (dostm) {
isLoop = true;
return expressionIsTooComplex(dostm->getCond());
}
return false;
}
bool ReserveCandidates::isInComplexLoop(clang::Stmt *s, SourceLocation declLocation, bool isMemberVariable) const
{
if (!s || declLocation.isInvalid())
return false;
int loopCount = 0;
int foreachCount = 0;
static vector<uint> nonComplexOnesCache;
static vector<uint> complexOnesCache;
auto rawLoc = s->getLocStart().getRawEncoding();
// For some reason we generate two warnings on some foreaches, so cache the ones we processed
// and return true so we don't trigger a warning
if (find(nonComplexOnesCache.cbegin(), nonComplexOnesCache.cend(), rawLoc) != nonComplexOnesCache.cend())
return true;
if (find(complexOnesCache.cbegin(), complexOnesCache.cend(), rawLoc) != complexOnesCache.cend())
return true;
Stmt *it = s;
PresumedLoc lastForeachForStm;
while (Stmt *parent = Utils::parent(m_parentMap, it)) {
if (!isMemberVariable && m_ci.getSourceManager().isBeforeInSLocAddrSpace(parent->getLocStart(), declLocation)) {
nonComplexOnesCache.push_back(rawLoc);
return false;
}
bool isLoop = false;
if (loopIsTooComplex(parent, isLoop)) {
complexOnesCache.push_back(rawLoc);
return true;
}
if (isLoop)
loopCount++;
auto macro = Lexer::getImmediateMacroName(parent->getLocStart(), m_ci.getSourceManager(), m_ci.getLangOpts());
if (macro == string("Q_FOREACH")) {
auto ploc = m_ci.getSourceManager().getPresumedLoc(parent->getLocStart());
if (Utils::presumedLocationsEqual(ploc, lastForeachForStm)) {
// Q_FOREACH comes in pairs, because each has two for statements inside, so ignore one when counting
} else {
foreachCount++;
lastForeachForStm = ploc;
}
}
if (foreachCount > 1) { // two foreaches are almost always a false-positve
complexOnesCache.push_back(rawLoc);
return true;
}
if (loopCount >= 4) {
complexOnesCache.push_back(rawLoc);
return true;
}
it = parent;
}
nonComplexOnesCache.push_back(rawLoc);
return false;
}
REGISTER_CHECK("reserve-candidates", ReserveCandidates)
<commit_msg>reserve-candidates: tiddy<commit_after>/*
This file is part of the clang-lazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
Author: Sérgio Martins <sergio.martins@kdab.com>
Copyright (C) 2015 Sergio Martins <smartins@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "reservecandidates.h"
#include "Utils.h"
#include "checkmanager.h"
#include "StringUtils.h"
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/Lex/Lexer.h>
#include <vector>
using namespace clang;
using namespace std;
ReserveCandidates::ReserveCandidates(const std::string &name)
: CheckBase(name)
{
}
static bool isAReserveClass(CXXRecordDecl *recordDecl)
{
if (!recordDecl)
return false;
static const std::vector<std::string> classes = {"QVector", "vector", "QList", "QSet", "QVarLengthArray"};
for (auto it = classes.cbegin(), end = classes.cend(); it != end; ++it) {
if (Utils::descendsFrom(recordDecl, *it))
return true;
}
return false;
}
static bool paramIsSameTypeAs(const Type *paramType, CXXRecordDecl *classDecl)
{
if (!paramType || !classDecl)
return false;
if (paramType->getAsCXXRecordDecl() == classDecl)
return true;
const CXXRecordDecl *paramClassDecl = paramType->getPointeeCXXRecordDecl();
return paramClassDecl && paramClassDecl == classDecl;
}
static bool isCandidateMethod(CXXMethodDecl *methodDecl)
{
if (!methodDecl)
return false;
CXXRecordDecl *classDecl = methodDecl->getParent();
if (!classDecl)
return false;
auto methodName = methodDecl->getNameAsString();
if (methodName != "append" && methodName != "push_back" && methodName != "push" /*&& methodName != "insert"*/)
return false;
if (!isAReserveClass(classDecl))
return false;
// Catch cases like: QList<T>::append(const QList<T> &), which don't make sense to reserve.
// In this case, the parameter has the same type of the class
ParmVarDecl *parm = methodDecl->getParamDecl(0);
if (paramIsSameTypeAs(parm->getType().getTypePtrOrNull(), classDecl))
return false;
return true;
}
static bool isCandidateOperator(CXXOperatorCallExpr *oper)
{
if (!oper)
return false;
auto calleeDecl = dyn_cast_or_null<CXXMethodDecl>(oper->getDirectCallee());
if (!calleeDecl)
return false;
const std::string operatorName = calleeDecl->getNameAsString();
if (operatorName != "operator<<" && operatorName != "operator+=")
return false;
CXXRecordDecl *recordDecl = calleeDecl->getParent();
if (!isAReserveClass(recordDecl))
return false;
// Catch cases like: QList<T>::append(const QList<T> &), which don't make sense to reserve.
// In this case, the parameter has the same type of the class
ParmVarDecl *parm = calleeDecl->getParamDecl(0);
if (paramIsSameTypeAs(parm->getType().getTypePtrOrNull(), recordDecl))
return false;
return true;
}
bool ReserveCandidates::containerWasReserved(clang::ValueDecl *valueDecl) const
{
if (!valueDecl)
return false;
return std::find(m_foundReserves.cbegin(), m_foundReserves.cend(), valueDecl) != m_foundReserves.cend();
}
bool ReserveCandidates::acceptsValueDecl(ValueDecl *valueDecl) const
{
// Rules:
// 1. The container variable must have been defined inside a function. Too many false positives otherwise.
// free to comment that out and go through the results, maybe you'll find something.
// 2. If we found at least one reserve call, lets not warn about it.
if (!valueDecl || isa<ParmVarDecl>(valueDecl) || containerWasReserved(valueDecl))
return false;
if (Utils::isValueDeclInFunctionContext(valueDecl))
return true;
// Actually, lets allow for some member variables containers if they are being used inside CTORs or DTORs
// Those functions are only called once, so it's OK. For other member functions it's dangerous and needs
// human inspection, if such member function would be called in a loop we would be constantly calling reserve
// and in that case the built-in exponential growth is better.
if (!m_lastMethodDecl || !(isa<CXXConstructorDecl>(m_lastMethodDecl) || isa<CXXDestructorDecl>(m_lastMethodDecl)))
return false;
CXXRecordDecl *record = Utils::isMemberVariable(valueDecl);
if (record && m_lastMethodDecl->getParent() == record)
return true;
return false;
}
void ReserveCandidates::printWarning(const SourceLocation &loc)
{
emitWarning(loc, "Reserve candidate");
}
bool ReserveCandidates::isReserveCandidate(ValueDecl *valueDecl, Stmt *loopBody, CallExpr *callExpr) const
{
if (!acceptsValueDecl(valueDecl))
return false;
const bool isMemberVariable = Utils::isMemberVariable(valueDecl);
// We only want containers defined outside of the loop we're examining
if (!isMemberVariable && m_ci.getSourceManager().isBeforeInSLocAddrSpace(loopBody->getLocStart(), valueDecl->getLocStart()))
return false;
if (isInComplexLoop(callExpr, valueDecl->getLocStart(), isMemberVariable))
return false;
if (Utils::loopCanBeInterrupted(loopBody, m_ci, callExpr->getLocStart()))
return false;
return true;
}
void ReserveCandidates::VisitStmt(clang::Stmt *stm)
{
checkIfReserveStatement(stm);
auto body = Utils::bodyFromLoop(stm);
if (!body)
return;
auto macro = Lexer::getImmediateMacroName(stm->getLocStart(), m_ci.getSourceManager(), m_ci.getLangOpts());
const bool isForeach = macro == "Q_FOREACH";
// If the body is another loop, we have nesting, ignore it now since the inner loops will be visited soon.
if (isa<DoStmt>(body) || isa<WhileStmt>(body) || (!isForeach && isa<ForStmt>(body)))
return;
// TODO: Search in both branches of the if statement
if (isa<IfStmt>(body))
return;
vector<CXXMemberCallExpr*> callExprs;
vector<CXXOperatorCallExpr*> operatorCalls;
// Get the list of member calls and operator<< that are direct childs of the loop statements
// If it's inside an if statement we don't care.
Utils::getChilds<CXXMemberCallExpr>(body, callExprs);
Utils::getChilds<CXXOperatorCallExpr>(body, operatorCalls); // For operator<<
for (CXXMemberCallExpr *callExpr : callExprs) {
if (!isCandidateMethod(callExpr->getMethodDecl()))
continue;
ValueDecl *valueDecl = Utils::valueDeclForMemberCall(callExpr);
if (isReserveCandidate(valueDecl, body, callExpr))
printWarning(callExpr->getLocStart());
}
for (CXXOperatorCallExpr *callExpr : operatorCalls) {
if (!isCandidateOperator(callExpr))
continue;
ValueDecl *valueDecl = Utils::valueDeclForOperatorCall(callExpr);
if (isReserveCandidate(valueDecl, body, callExpr))
printWarning(callExpr->getLocStart());
}
}
// Catch existing reserves
void ReserveCandidates::checkIfReserveStatement(Stmt *stm)
{
auto memberCall = dyn_cast<CXXMemberCallExpr>(stm);
if (!memberCall)
return;
CXXMethodDecl *methodDecl = memberCall->getMethodDecl();
if (!methodDecl || methodDecl->getNameAsString() != "reserve")
return;
CXXRecordDecl *decl = methodDecl->getParent();
if (!isAReserveClass(decl))
return;
ValueDecl *valueDecl = Utils::valueDeclForMemberCall(memberCall);
if (!valueDecl)
return;
if (std::find(m_foundReserves.cbegin(), m_foundReserves.cend(), valueDecl) == m_foundReserves.cend()) {
m_foundReserves.push_back(valueDecl);
}
}
bool ReserveCandidates::expressionIsTooComplex(clang::Expr *expr) const
{
if (!expr)
return false;
vector<CallExpr*> callExprs;
Utils::getChilds2<CallExpr>(expr, callExprs);
for (CallExpr *callExpr : callExprs) {
QualType qt = callExpr->getType();
const Type *t = qt.getTypePtrOrNull();
if (t && (!t->isIntegerType() || t->isBooleanType()))
return true;
}
vector<ArraySubscriptExpr*> subscriptExprs;
Utils::getChilds2<ArraySubscriptExpr>(expr, subscriptExprs);
if (!subscriptExprs.empty())
return true;
BinaryOperator* binary = dyn_cast<BinaryOperator>(expr);
if (binary && binary->isAssignmentOp()) { // Filter things like for ( ...; ...; next = node->next)
Expr *rhs = binary->getRHS();
if (isa<MemberExpr>(rhs) || (isa<ImplicitCastExpr>(rhs) && dyn_cast_or_null<MemberExpr>(Utils::getFirstChildAtDepth(rhs, 1))))
return true;
}
// llvm::errs() << expr->getStmtClassName() << "\n";
return false;
}
bool ReserveCandidates::loopIsTooComplex(clang::Stmt *stm, bool &isLoop) const
{
isLoop = false;
auto forstm = dyn_cast<ForStmt>(stm);
if (forstm) {
isLoop = true;
return forstm->getInc() == nullptr || expressionIsTooComplex(forstm->getCond()) || expressionIsTooComplex(forstm->getInc());
}
auto whilestm = dyn_cast<WhileStmt>(stm);
if (whilestm) {
isLoop = true;
return expressionIsTooComplex(whilestm->getCond());
}
auto dostm = dyn_cast<DoStmt>(stm);
if (dostm) {
isLoop = true;
return expressionIsTooComplex(dostm->getCond());
}
return false;
}
bool ReserveCandidates::isInComplexLoop(clang::Stmt *s, SourceLocation declLocation, bool isMemberVariable) const
{
if (!s || declLocation.isInvalid())
return false;
int loopCount = 0;
int foreachCount = 0;
static vector<uint> nonComplexOnesCache;
static vector<uint> complexOnesCache;
auto rawLoc = s->getLocStart().getRawEncoding();
// For some reason we generate two warnings on some foreaches, so cache the ones we processed
// and return true so we don't trigger a warning
if (find(nonComplexOnesCache.cbegin(), nonComplexOnesCache.cend(), rawLoc) != nonComplexOnesCache.cend())
return true;
if (find(complexOnesCache.cbegin(), complexOnesCache.cend(), rawLoc) != complexOnesCache.cend())
return true;
Stmt *it = s;
PresumedLoc lastForeachForStm;
while (Stmt *parent = Utils::parent(m_parentMap, it)) {
if (!isMemberVariable && m_ci.getSourceManager().isBeforeInSLocAddrSpace(parent->getLocStart(), declLocation)) {
nonComplexOnesCache.push_back(rawLoc);
return false;
}
bool isLoop = false;
if (loopIsTooComplex(parent, isLoop)) {
complexOnesCache.push_back(rawLoc);
return true;
}
if (isLoop)
loopCount++;
auto macro = Lexer::getImmediateMacroName(parent->getLocStart(), m_ci.getSourceManager(), m_ci.getLangOpts());
if (macro == string("Q_FOREACH")) {
auto ploc = m_ci.getSourceManager().getPresumedLoc(parent->getLocStart());
if (Utils::presumedLocationsEqual(ploc, lastForeachForStm)) {
// Q_FOREACH comes in pairs, because each has two for statements inside, so ignore one when counting
} else {
foreachCount++;
lastForeachForStm = ploc;
}
}
if (foreachCount > 1) { // two foreaches are almost always a false-positve
complexOnesCache.push_back(rawLoc);
return true;
}
if (loopCount >= 4) {
complexOnesCache.push_back(rawLoc);
return true;
}
it = parent;
}
nonComplexOnesCache.push_back(rawLoc);
return false;
}
REGISTER_CHECK("reserve-candidates", ReserveCandidates)
<|endoftext|> |
<commit_before>#include <iostream>
#include <complex>
#include <cmath>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "../sequence.h"
#include "../parallel.h"
#include "../run.h"
class SequenceTest : testing::Test { };
TEST(SequenceTest, Test1)
{
struct control_flow
{
bool code;
operator bool() const
{
return code;
}
};
control_flow flow = {true};
auto task = asyncply::sequence(flow,
[](control_flow flow) {
std::cout << "code 1" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 2" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 3" << std::endl;
flow.code = false;
return flow;
},
[](control_flow flow) {
std::cout << "code 4" << std::endl;
return flow;
}
);
flow = task->get();
ASSERT_FALSE(flow.code);
}
<commit_msg>Update test_sequence.cpp<commit_after>#include <iostream>
#include <complex>
#include <cmath>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "../sequence.h"
#include "../parallel.h"
#include "../run.h"
class SequenceTest : testing::Test { };
TEST(SequenceTest, DISABLED_Test1)
{
struct control_flow
{
bool code;
operator bool() const
{
return code;
}
};
control_flow flow = {true};
auto task = asyncply::sequence(flow,
[](control_flow flow) {
std::cout << "code 1" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 2" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 3" << std::endl;
flow.code = false;
return flow;
},
[](control_flow flow) {
std::cout << "code 4" << std::endl;
return flow;
}
);
flow = task->get();
ASSERT_FALSE(flow.code);
}
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2008-2014 Vaclav Slavik
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "attentionbar.h"
#include "utility.h"
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/artprov.h>
#include <wx/bmpbuttn.h>
#include <wx/stattext.h>
#include <wx/statbmp.h>
#include <wx/config.h>
#include <wx/dcclient.h>
#include "customcontrols.h"
#ifdef __WXOSX__
#include "osx_helpers.h"
#endif
#ifdef __WXOSX__
#define SMALL_BORDER 7
#define BUTTONS_SPACE 10
#else
#define SMALL_BORDER 3
#define BUTTONS_SPACE 5
#endif
BEGIN_EVENT_TABLE(AttentionBar, wxPanel)
EVT_BUTTON(wxID_CLOSE, AttentionBar::OnClose)
EVT_BUTTON(wxID_ANY, AttentionBar::OnAction)
END_EVENT_TABLE()
AttentionBar::AttentionBar(wxWindow *parent)
: wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxTAB_TRAVERSAL | wxBORDER_NONE)
{
#ifdef __WXMSW__
SetBackgroundColour("#FFF499"); // match Visual Studio 2012+'s aesthetics
#endif
#ifdef __WXOSX__
SetBackgroundColour("#FCDE59");
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
#ifndef __WXGTK__
m_icon = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap);
#endif
m_label = new wxStaticText(this, wxID_ANY, "");
m_explanation = new AutoWrappingText(this, "");
m_explanation->SetForegroundColour(GetBackgroundColour().ChangeLightness(40));
m_buttons = new wxBoxSizer(wxHORIZONTAL);
wxButton *btnClose =
new wxBitmapButton
(
this, wxID_CLOSE,
wxArtProvider::GetBitmap("window-close", wxART_MENU),
wxDefaultPosition, wxDefaultSize,
wxNO_BORDER
);
btnClose->SetToolTip(_("Hide this notification message"));
#ifdef __WXMSW__
btnClose->SetBackgroundColour(GetBackgroundColour());
#endif
#if defined(__WXOSX__) || defined(__WXMSW__)
wxFont boldFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
boldFont.SetWeight(wxFONTWEIGHT_BOLD);
m_label->SetFont(boldFont);
#endif
Bind(wxEVT_PAINT, &AttentionBar::OnPaint, this);
wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->AddSpacer(wxSizerFlags::GetDefaultBorder());
#ifndef __WXGTK__
sizer->Add(m_icon, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER));
#endif
auto labelSizer = new wxBoxSizer(wxVERTICAL);
labelSizer->Add(m_label, wxSizerFlags().Expand());
labelSizer->Add(m_explanation, wxSizerFlags().Expand().Border(wxTOP|wxRIGHT, 4));
sizer->Add(labelSizer, wxSizerFlags(1).Center().DoubleBorder(wxALL));
sizer->AddSpacer(20);
sizer->Add(m_buttons, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER));
sizer->Add(btnClose, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER));
SetSizer(sizer);
// the bar should be initially hidden
Show(false);
}
void AttentionBar::OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
wxRect rect(dc.GetSize());
auto bg = GetBackgroundColour();
dc.SetBrush(*wxTRANSPARENT_BRUSH);
dc.SetPen(bg.ChangeLightness(90));
#ifndef __WXOSX__
dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
#endif
dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
}
void AttentionBar::ShowMessage(const AttentionMessage& msg)
{
if ( msg.IsBlacklisted() )
return;
#ifdef __WXGTK__
switch ( msg.m_kind )
{
case AttentionMessage::Info:
SetBackgroundColour(wxColour(252,252,189));
break;
case AttentionMessage::Warning:
SetBackgroundColour(wxColour(250,173,61));
break;
case AttentionMessage::Question:
SetBackgroundColour(wxColour(138,173,212));
break;
case AttentionMessage::Error:
SetBackgroundColour(wxColour(237,54,54));
break;
}
#else
wxString iconName;
switch ( msg.m_kind )
{
case AttentionMessage::Info:
iconName = wxART_INFORMATION;
break;
case AttentionMessage::Warning:
iconName = wxART_WARNING;
break;
case AttentionMessage::Question:
iconName = wxART_QUESTION;
break;
case AttentionMessage::Error:
iconName = wxART_ERROR;
break;
}
m_icon->SetBitmap(wxArtProvider::GetBitmap(iconName, wxART_MENU, wxSize(16, 16)));
#endif
m_label->SetLabelText(msg.m_text);
m_explanation->SetAndWrapLabel(msg.m_explanation);
m_explanation->GetContainingSizer()->Show(m_explanation, !msg.m_explanation.empty());
m_buttons->Clear(true/*delete_windows*/);
m_actions.clear();
for ( AttentionMessage::Actions::const_iterator i = msg.m_actions.begin();
i != msg.m_actions.end(); ++i )
{
wxButton *b = new wxButton(this, wxID_ANY, i->first);
#ifdef __WXOSX__
MakeButtonRounded(b->GetHandle());
#endif
m_buttons->Add(b, wxSizerFlags().Center().Border(wxRIGHT, BUTTONS_SPACE));
m_actions[b] = i->second;
}
// we need to size the control correctly _and_ lay out the controls if this
// is the first time it's being shown, otherwise we can get garbled look:
SetSize(GetParent()->GetClientSize().x,
GetBestSize().y);
Layout();
Refresh();
Show();
GetParent()->Layout();
}
void AttentionBar::HideMessage()
{
Hide();
GetParent()->Layout();
}
void AttentionBar::OnClose(wxCommandEvent& WXUNUSED(event))
{
HideMessage();
}
void AttentionBar::OnAction(wxCommandEvent& event)
{
ActionsMap::const_iterator i = m_actions.find(event.GetEventObject());
if ( i == m_actions.end() )
{
event.Skip();
return;
}
// first perform the action...
i->second();
// ...then hide the message
HideMessage();
}
/* static */
void AttentionMessage::AddToBlacklist(const wxString& id)
{
wxConfig::Get()->Write
(
wxString::Format("/messages/dont_show/%s", id.c_str()),
(long)true
);
}
/* static */
bool AttentionMessage::IsBlacklisted(const wxString& id)
{
return wxConfig::Get()->ReadBool
(
wxString::Format("/messages/dont_show/%s", id.c_str()),
false
);
}
void AttentionMessage::AddDontShowAgain()
{
AddAction(
MSW_OR_OTHER(_("Don't show again"), _("Don't Show Again")), [=]{
AddToBlacklist(m_id);
});
}
<commit_msg>Slight tweaks to AttentionBar close button spacing<commit_after>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2008-2014 Vaclav Slavik
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "attentionbar.h"
#include "utility.h"
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/artprov.h>
#include <wx/bmpbuttn.h>
#include <wx/stattext.h>
#include <wx/statbmp.h>
#include <wx/config.h>
#include <wx/dcclient.h>
#include "customcontrols.h"
#ifdef __WXOSX__
#include "osx_helpers.h"
#endif
#ifdef __WXOSX__
#define SMALL_BORDER 7
#define BUTTONS_SPACE 10
#else
#define SMALL_BORDER 3
#define BUTTONS_SPACE 5
#endif
BEGIN_EVENT_TABLE(AttentionBar, wxPanel)
EVT_BUTTON(wxID_CLOSE, AttentionBar::OnClose)
EVT_BUTTON(wxID_ANY, AttentionBar::OnAction)
END_EVENT_TABLE()
AttentionBar::AttentionBar(wxWindow *parent)
: wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxTAB_TRAVERSAL | wxBORDER_NONE)
{
#ifdef __WXMSW__
SetBackgroundColour("#FFF499"); // match Visual Studio 2012+'s aesthetics
#endif
#ifdef __WXOSX__
SetBackgroundColour("#FCDE59");
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
#ifndef __WXGTK__
m_icon = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap);
#endif
m_label = new wxStaticText(this, wxID_ANY, "");
m_explanation = new AutoWrappingText(this, "");
m_explanation->SetForegroundColour(GetBackgroundColour().ChangeLightness(40));
m_buttons = new wxBoxSizer(wxHORIZONTAL);
wxButton *btnClose =
new wxBitmapButton
(
this, wxID_CLOSE,
wxArtProvider::GetBitmap("window-close", wxART_MENU),
wxDefaultPosition, wxDefaultSize,
wxNO_BORDER
);
btnClose->SetToolTip(_("Hide this notification message"));
#ifdef __WXMSW__
btnClose->SetBackgroundColour(GetBackgroundColour());
#endif
#if defined(__WXOSX__) || defined(__WXMSW__)
wxFont boldFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
boldFont.SetWeight(wxFONTWEIGHT_BOLD);
m_label->SetFont(boldFont);
#endif
Bind(wxEVT_PAINT, &AttentionBar::OnPaint, this);
wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->AddSpacer(wxSizerFlags::GetDefaultBorder());
#ifndef __WXGTK__
sizer->Add(m_icon, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER));
#endif
auto labelSizer = new wxBoxSizer(wxVERTICAL);
labelSizer->Add(m_label, wxSizerFlags().Expand());
labelSizer->Add(m_explanation, wxSizerFlags().Expand().Border(wxTOP|wxRIGHT, 4));
sizer->Add(labelSizer, wxSizerFlags(1).Center().DoubleBorder(wxALL));
sizer->AddSpacer(20);
sizer->Add(m_buttons, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER));
sizer->Add(btnClose, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER));
#ifdef __WXMSW__
sizer->AddSpacer(4);
#endif
SetSizer(sizer);
// the bar should be initially hidden
Show(false);
}
void AttentionBar::OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
wxRect rect(dc.GetSize());
auto bg = GetBackgroundColour();
dc.SetBrush(*wxTRANSPARENT_BRUSH);
dc.SetPen(bg.ChangeLightness(90));
#ifndef __WXOSX__
dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
#endif
dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
}
void AttentionBar::ShowMessage(const AttentionMessage& msg)
{
if ( msg.IsBlacklisted() )
return;
#ifdef __WXGTK__
switch ( msg.m_kind )
{
case AttentionMessage::Info:
SetBackgroundColour(wxColour(252,252,189));
break;
case AttentionMessage::Warning:
SetBackgroundColour(wxColour(250,173,61));
break;
case AttentionMessage::Question:
SetBackgroundColour(wxColour(138,173,212));
break;
case AttentionMessage::Error:
SetBackgroundColour(wxColour(237,54,54));
break;
}
#else
wxString iconName;
switch ( msg.m_kind )
{
case AttentionMessage::Info:
iconName = wxART_INFORMATION;
break;
case AttentionMessage::Warning:
iconName = wxART_WARNING;
break;
case AttentionMessage::Question:
iconName = wxART_QUESTION;
break;
case AttentionMessage::Error:
iconName = wxART_ERROR;
break;
}
m_icon->SetBitmap(wxArtProvider::GetBitmap(iconName, wxART_MENU, wxSize(16, 16)));
#endif
m_label->SetLabelText(msg.m_text);
m_explanation->SetAndWrapLabel(msg.m_explanation);
m_explanation->GetContainingSizer()->Show(m_explanation, !msg.m_explanation.empty());
m_buttons->Clear(true/*delete_windows*/);
m_actions.clear();
for ( AttentionMessage::Actions::const_iterator i = msg.m_actions.begin();
i != msg.m_actions.end(); ++i )
{
wxButton *b = new wxButton(this, wxID_ANY, i->first);
#ifdef __WXOSX__
MakeButtonRounded(b->GetHandle());
#endif
m_buttons->Add(b, wxSizerFlags().Center().Border(wxRIGHT, BUTTONS_SPACE));
m_actions[b] = i->second;
}
// we need to size the control correctly _and_ lay out the controls if this
// is the first time it's being shown, otherwise we can get garbled look:
SetSize(GetParent()->GetClientSize().x, GetBestSize().y);
Layout();
Refresh();
Show();
GetParent()->Layout();
}
void AttentionBar::HideMessage()
{
Hide();
GetParent()->Layout();
}
void AttentionBar::OnClose(wxCommandEvent& WXUNUSED(event))
{
HideMessage();
}
void AttentionBar::OnAction(wxCommandEvent& event)
{
ActionsMap::const_iterator i = m_actions.find(event.GetEventObject());
if ( i == m_actions.end() )
{
event.Skip();
return;
}
// first perform the action...
i->second();
// ...then hide the message
HideMessage();
}
/* static */
void AttentionMessage::AddToBlacklist(const wxString& id)
{
wxConfig::Get()->Write
(
wxString::Format("/messages/dont_show/%s", id.c_str()),
(long)true
);
}
/* static */
bool AttentionMessage::IsBlacklisted(const wxString& id)
{
return wxConfig::Get()->ReadBool
(
wxString::Format("/messages/dont_show/%s", id.c_str()),
false
);
}
void AttentionMessage::AddDontShowAgain()
{
AddAction(
MSW_OR_OTHER(_("Don't show again"), _("Don't Show Again")), [=]{
AddToBlacklist(m_id);
});
}
<|endoftext|> |
<commit_before><commit_msg>Attempt to fix the official Google Chrome build on Linux. Review URL: http://codereview.chromium.org/155261<commit_after><|endoftext|> |
<commit_before>#ifndef __CHILDPROCESSPLAYER_HPP__
#define __CHILDPROCESSPLAYER_HPP__
#include "Player.hpp"
#include <Windows.h>
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
// Template takes an unsigned int as a uniquification id for each spawned process.
//
// RECOMMENDED USAGE:
//
// STEP 1:
// In Tournament.cpp, create a type for each external player:
// typedef ChildProcessPlayer<0> PythonicPlayer;
// typedef ChildProcessPlayer<2> CygwinBashPlayer;
//
// STEP 2:
// Use the above typedef for the Pool::newPlayer's make_unique calls.
//
// STEP 3:
// In Tournament.cpp in main, before running the tournament, bind each incarnation to a process:
// PythonicPlayer::module() = "python pythonic.py";
// CygwinBashPlayer::module() = "C:\\cygwin\\bin\\bash -c bashplayer.sh"
// Optionally, if a particular external player prefers a nl style, configure it as well:
// CygwinBashPlayer::nlstyle(CygwinBashPlayer::NLS_LF);
// =========
//
// STRICT ENTRY RULES:
//
// There's a fixed requirement for all entries on how to do I/O, since both stdin and stdout
// are connected to the tournament driver. Violating this could lead to a deadlock.
// All entries MUST follow this exact algorithm (in pseudocode):
//
// LOOP FOREVER
// READ LINE INTO L
// IF (LEFT(L,1) == 'I')
// INITIALIZE ROUND
// // i.e., set your/opponent ammo to 0, if tracking them
// // Note: The entire line at this point is a unique id per opponnent;
// // optionally track this as well.
// CONTINUE LOOP
// ELSE IF (LEFT(L,1) == 'F')
// WRITELN F // where F is your move
// ELSE IF (LEFT(L,1) == 'P')
// PROCESS MID(L,2,1) // optional
// END IF
// CONTINUE LOOP
//
// Here, F is one of '0', '1', '2', '-', or '=' for load/bullet/plasma/metal/thermal.
//
// PROCESS means to optionally respond to what your opponent did (including tracking
// your opponent's ammo if you're doing this). Note that the opponent's action is
// also one of '0', '1', '2', '-', or '=', and is in the second character.
template <unsigned id>
class ChildProcessPlayer final : public Player
{
public:
// Both a setter and getter of the module used for this player type
static const char*& module()
{
static const char* x = 0; return x;
}
// New line styles
enum NewLineStyle {
NLS_CURRENT,
NLS_LF, // LF only (*NIX style)
NLS_CRLF, // CR-LF (Windows style)
NLS_CR // CR only (MAC style)
};
// Optionally set this for a ChildProcessPlayer if they are expecting
// different newline conventions.
static const char* newline(NewLineStyle nls = NLS_CURRENT) {
static NewLineStyle style = NLS_CRLF;
if (nls == NLS_CURRENT) nls = style;
switch (nls) {
default:
case NLS_CRLF: return "\r\n";
case NLS_LF: return "\n";
case NLS_CR: return "\r"; // not sure if we'll need this unless _proxying_ macs via child or something
}
}
static STARTUPINFO& si() { static STARTUPINFO x = {sizeof(STARTUPINFO)}; return x; }
static PROCESS_INFORMATION& pi() { static PROCESS_INFORMATION x = {}; return x; }
static HANDLE& toChildH() { static HANDLE h = INVALID_HANDLE_VALUE; return h; }
static HANDLE& fromChildH() { static HANDLE h = INVALID_HANDLE_VALUE; return h; }
// Both setter and getter for a failure condition
static const char*& failure(const char* set = 0) {
static const char* f = 0;
if (set) {
f = set;
std::cerr << "ChildProcess<" << id << "> failure: " << f << std::endl;
}
return f;
}
// Utility... report on pipe configuration
static void reportPipe(HANDLE p) {
DWORD flags, outBufferSize, inBufferSize, maxInstances;
if (!GetNamedPipeInfo(p, &flags, &outBufferSize, &inBufferSize, &maxInstances)) {
std::cerr << "Report error for pipe: " << GetLastError() << std::endl;
return;
}
std::cerr
<< ((flags & PIPE_SERVER_END) ? "SERVER" : "CLIENT")
<< ((flags & PIPE_TYPE_MESSAGE) ? " MESSAGE" : " BYTE") << " PIPE:"
<< " out buffer " << outBufferSize << ", in buffer " << inBufferSize
<< " max instances " << maxInstances << std::endl;
}
// Wrapper for creating new pipes
static BOOLEAN NewPipe(HANDLE& in, HANDLE& out, unsigned buffer=0) {
SECURITY_ATTRIBUTES saAttr = { sizeof(SECURITY_ATTRIBUTES) };
saAttr.bInheritHandle = TRUE;
BOOLEAN rv = CreatePipe(&in, &out, &saAttr, buffer);
reportPipe(in);
reportPipe(out);
return rv;
}
// Start the process
static void startProcess() {
// Start only the first time; this way we can just blindly call this
// in the ctor.
static bool started = false;
if (started) return;
started = true;
// Handle's we're giving to the child
HANDLE hChildStd_IN_Rd = INVALID_HANDLE_VALUE;
HANDLE hChildStd_OUT_Wr = INVALID_HANDLE_VALUE;
if (!NewPipe(fromChildH(), hChildStd_OUT_Wr, 1))
{
failure("1. Failed to create pipes for child stdout");
return;
}
if (!NewPipe(hChildStd_IN_Rd, toChildH(), 1))
{
failure("2. Failed to create pipes for child stdin");
return;
}
// Tell CreateProcess to use handles from our pipes
// for stdin/stdout
si().hStdOutput = hChildStd_OUT_Wr;
si().hStdInput = hChildStd_IN_Rd;
si().dwFlags |= STARTF_USESTDHANDLES;
// Convert string literal stored in module
// to a volatile nul-terminated char for use by ancient CreateProcess method.
std::string modulestr(module());
std::vector<char> modulebuffer(modulestr.size() + 1);
std::copy(modulestr.begin(), modulestr.end(), modulebuffer.begin());
// Create the child process
BOOL bSuccess =
CreateProcessA(0,
&modulebuffer[0],
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&si(),
&pi());
// Report on failure
if (!bSuccess)
{
failure("3. Failed to spawn this child");
std::cerr << "ERROR CODE: " << GetLastError() << std::endl;
return;
}
CloseHandle(pi().hProcess);
CloseHandle(pi().hThread);
}
// Writes a string to the child process's stdin
static void write(const std::string& value) {
if (toChildH() == INVALID_HANDLE_VALUE) return;
DWORD bytesWritten = 0;
if (!WriteFile(toChildH(), value.c_str(), value.size(), &bytesWritten, 0)) {
failure("Problem writing to child");
std::cerr << "E:" << GetLastError() << std::endl;
CloseHandle(toChildH());
toChildH() = INVALID_HANDLE_VALUE;
}
}
// Writes a line to the child process's stdin using the configured NL style
static void writeln(const std::string& value) {
write(value + newline());
}
// Read a character from the child process's stdout.
static int read() {
if (fromChildH() == INVALID_HANDLE_VALUE) return std::char_traits<char>::eof();
char rv='~';
DWORD bytesRead = 0, bytesAvail=0;
if (!ReadFile(fromChildH(), reinterpret_cast<void*>(&rv), 1, &bytesRead, 0)) {
failure("Problem reading from child");
std::cerr << "E:" << GetLastError() << std::endl;
CloseHandle(fromChildH());
fromChildH() = INVALID_HANDLE_VALUE;
return std::char_traits<char>::eof();
}
if (bytesRead == 0) {
failure("Premature end of file from child");
CloseHandle(fromChildH());
fromChildH() = INVALID_HANDLE_VALUE;
return std::char_traits<char>::eof();
}
return std::char_traits<char>::to_int_type(rv);
}
ChildProcessPlayer(size_t opponent)
: Player(opponent)
{
// Start the child if we haven't already
startProcess();
// Tell the child there's a new round, and which opponent is playing
writeln(std::string("I") + std::to_string(opponent));
}
Action fight() {
size_t response;
// Ask child process to move
writeln("F");
// Read until we see a move
for (;;) {
int i = read();
if (i == std::char_traits<char>::eof()) {
// Create an invalid value to return
// (trip invalid value handling logic)
return static_cast<Player::Action>(5);
}
char c = std::char_traits<char>::to_char_type(i);
static const std::string responses = "012-=";
response = responses.find_first_of(c);
if (response < 5) {
return static_cast<Player::Action>(response);
}
}
}
void perceive(Action a) {
// Tell child process what the opponent did
switch (a) {
case LOAD : writeln("P0"); return;
case BULLET : writeln("P1"); return;
case PLASMA : writeln("P2"); return;
case METAL : writeln("P-"); return;
case THERMAL: writeln("P="); return;
default: writeln("P?");
}
}
};
#endif<commit_msg>Fix newline method when used as setter.<commit_after>#ifndef __CHILDPROCESSPLAYER_HPP__
#define __CHILDPROCESSPLAYER_HPP__
#include "Player.hpp"
#include <Windows.h>
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
// Template takes an unsigned int as a uniquification id for each spawned process.
//
// RECOMMENDED USAGE:
//
// STEP 1:
// In Tournament.cpp, create a type for each external player:
// typedef ChildProcessPlayer<0> PythonicPlayer;
// typedef ChildProcessPlayer<2> CygwinBashPlayer;
//
// STEP 2:
// Use the above typedef for the Pool::newPlayer's make_unique calls.
//
// STEP 3:
// In Tournament.cpp in main, before running the tournament, bind each incarnation to a process:
// PythonicPlayer::module() = "python pythonic.py";
// CygwinBashPlayer::module() = "C:\\cygwin\\bin\\bash -c bashplayer.sh"
// Optionally, if a particular external player prefers a nl style, configure it as well:
// CygwinBashPlayer::nlstyle(CygwinBashPlayer::NLS_LF);
// =========
//
// STRICT ENTRY RULES:
//
// There's a fixed requirement for all entries on how to do I/O, since both stdin and stdout
// are connected to the tournament driver. Violating this could lead to a deadlock.
// All entries MUST follow this exact algorithm (in pseudocode):
//
// LOOP FOREVER
// READ LINE INTO L
// IF (LEFT(L,1) == 'I')
// INITIALIZE ROUND
// // i.e., set your/opponent ammo to 0, if tracking them
// // Note: The entire line at this point is a unique id per opponnent;
// // optionally track this as well.
// CONTINUE LOOP
// ELSE IF (LEFT(L,1) == 'F')
// WRITELN F // where F is your move
// ELSE IF (LEFT(L,1) == 'P')
// PROCESS MID(L,2,1) // optional
// END IF
// CONTINUE LOOP
//
// Here, F is one of '0', '1', '2', '-', or '=' for load/bullet/plasma/metal/thermal.
//
// PROCESS means to optionally respond to what your opponent did (including tracking
// your opponent's ammo if you're doing this). Note that the opponent's action is
// also one of '0', '1', '2', '-', or '=', and is in the second character.
template <unsigned id>
class ChildProcessPlayer final : public Player
{
public:
// Both a setter and getter of the module used for this player type
static const char*& module()
{
static const char* x = 0; return x;
}
// New line styles
enum NewLineStyle {
NLS_CURRENT,
NLS_LF, // LF only (*NIX style)
NLS_CRLF, // CR-LF (Windows style)
NLS_CR // CR only (MAC style)
};
// Optionally set this for a ChildProcessPlayer if they are expecting
// different newline conventions.
static const char* newline(NewLineStyle nls = NLS_CURRENT) {
static NewLineStyle style = NLS_CRLF;
if (nls == NLS_CURRENT) nls = style; else style = nls;
switch (nls) {
default:
case NLS_CRLF: return "\r\n";
case NLS_LF: return "\n";
case NLS_CR: return "\r"; // not sure if we'll need this unless _proxying_ macs via child or something
}
}
static STARTUPINFO& si() { static STARTUPINFO x = {sizeof(STARTUPINFO)}; return x; }
static PROCESS_INFORMATION& pi() { static PROCESS_INFORMATION x = {}; return x; }
static HANDLE& toChildH() { static HANDLE h = INVALID_HANDLE_VALUE; return h; }
static HANDLE& fromChildH() { static HANDLE h = INVALID_HANDLE_VALUE; return h; }
// Both setter and getter for a failure condition
static const char*& failure(const char* set = 0) {
static const char* f = 0;
if (set) {
f = set;
std::cerr << "ChildProcess<" << id << "> failure: " << f << std::endl;
}
return f;
}
// Utility... report on pipe configuration
static void reportPipe(HANDLE p) {
DWORD flags, outBufferSize, inBufferSize, maxInstances;
if (!GetNamedPipeInfo(p, &flags, &outBufferSize, &inBufferSize, &maxInstances)) {
std::cerr << "Report error for pipe: " << GetLastError() << std::endl;
return;
}
std::cerr
<< ((flags & PIPE_SERVER_END) ? "SERVER" : "CLIENT")
<< ((flags & PIPE_TYPE_MESSAGE) ? " MESSAGE" : " BYTE") << " PIPE:"
<< " out buffer " << outBufferSize << ", in buffer " << inBufferSize
<< " max instances " << maxInstances << std::endl;
}
// Wrapper for creating new pipes
static BOOLEAN NewPipe(HANDLE& in, HANDLE& out, unsigned buffer=0) {
SECURITY_ATTRIBUTES saAttr = { sizeof(SECURITY_ATTRIBUTES) };
saAttr.bInheritHandle = TRUE;
BOOLEAN rv = CreatePipe(&in, &out, &saAttr, buffer);
reportPipe(in);
reportPipe(out);
return rv;
}
// Start the process
static void startProcess() {
// Start only the first time; this way we can just blindly call this
// in the ctor.
static bool started = false;
if (started) return;
started = true;
// Handle's we're giving to the child
HANDLE hChildStd_IN_Rd = INVALID_HANDLE_VALUE;
HANDLE hChildStd_OUT_Wr = INVALID_HANDLE_VALUE;
if (!NewPipe(fromChildH(), hChildStd_OUT_Wr, 1))
{
failure("1. Failed to create pipes for child stdout");
return;
}
if (!NewPipe(hChildStd_IN_Rd, toChildH(), 1))
{
failure("2. Failed to create pipes for child stdin");
return;
}
// Tell CreateProcess to use handles from our pipes
// for stdin/stdout
si().hStdOutput = hChildStd_OUT_Wr;
si().hStdInput = hChildStd_IN_Rd;
si().dwFlags |= STARTF_USESTDHANDLES;
// Convert string literal stored in module
// to a volatile nul-terminated char for use by ancient CreateProcess method.
std::string modulestr(module());
std::vector<char> modulebuffer(modulestr.size() + 1);
std::copy(modulestr.begin(), modulestr.end(), modulebuffer.begin());
// Create the child process
BOOL bSuccess =
CreateProcessA(0,
&modulebuffer[0],
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&si(),
&pi());
// Report on failure
if (!bSuccess)
{
failure("3. Failed to spawn this child");
std::cerr << "ERROR CODE: " << GetLastError() << std::endl;
return;
}
CloseHandle(pi().hProcess);
CloseHandle(pi().hThread);
}
// Writes a string to the child process's stdin
static void write(const std::string& value) {
if (toChildH() == INVALID_HANDLE_VALUE) return;
DWORD bytesWritten = 0;
if (!WriteFile(toChildH(), value.c_str(), value.size(), &bytesWritten, 0)) {
failure("Problem writing to child");
std::cerr << "E:" << GetLastError() << std::endl;
CloseHandle(toChildH());
toChildH() = INVALID_HANDLE_VALUE;
}
}
// Writes a line to the child process's stdin using the configured NL style
static void writeln(const std::string& value) {
write(value + newline());
}
// Read a character from the child process's stdout.
static int read() {
if (fromChildH() == INVALID_HANDLE_VALUE) return std::char_traits<char>::eof();
char rv='~';
DWORD bytesRead = 0, bytesAvail=0;
if (!ReadFile(fromChildH(), reinterpret_cast<void*>(&rv), 1, &bytesRead, 0)) {
failure("Problem reading from child");
std::cerr << "E:" << GetLastError() << std::endl;
CloseHandle(fromChildH());
fromChildH() = INVALID_HANDLE_VALUE;
return std::char_traits<char>::eof();
}
if (bytesRead == 0) {
failure("Premature end of file from child");
CloseHandle(fromChildH());
fromChildH() = INVALID_HANDLE_VALUE;
return std::char_traits<char>::eof();
}
return std::char_traits<char>::to_int_type(rv);
}
ChildProcessPlayer(size_t opponent)
: Player(opponent)
{
// Start the child if we haven't already
startProcess();
// Tell the child there's a new round, and which opponent is playing
writeln(std::string("I") + std::to_string(opponent));
}
Action fight() {
size_t response;
// Ask child process to move
writeln("F");
// Read until we see a move
for (;;) {
int i = read();
if (i == std::char_traits<char>::eof()) {
// Create an invalid value to return
// (trip invalid value handling logic)
return static_cast<Player::Action>(5);
}
char c = std::char_traits<char>::to_char_type(i);
static const std::string responses = "012-=";
response = responses.find_first_of(c);
if (response < 5) {
return static_cast<Player::Action>(response);
}
}
}
void perceive(Action a) {
// Tell child process what the opponent did
switch (a) {
case LOAD : writeln("P0"); return;
case BULLET : writeln("P1"); return;
case PLASMA : writeln("P2"); return;
case METAL : writeln("P-"); return;
case THERMAL: writeln("P="); return;
default: writeln("P?");
}
}
};
#endif
<|endoftext|> |
<commit_before>/*!
* \file main.cc
* \brief A simple application using the Sick LMS 1xx driver.
*
* Code by Jason C. Derenick and Christopher R. Mansley.
* Contact jasonder(at)seas(dot)upenn(dot)edu
*
* The Sick LIDAR Matlab/C++ Toolbox
* Copyright (c) 2009, Jason C. Derenick and Christopher R. Mansley
* All rights reserved.
*
* This software is released under a BSD Open-Source License.
* See http://sicktoolbox.sourceforge.net
*/
#include <string>
#include <iostream>
#include <sicklms1xx/SickLMS1xx.hh>
using namespace std;
using namespace SickToolbox;
int main(int argc, char* argv[])
{
/*
* Instantiate an instance
*/
SickLMS1xx sick_lms_1xx;
/*
* Initialize the Sick LMS 2xx
*/
try {
sick_lms_1xx.Initialize();
}
catch(...) {
cerr << "Initialize failed! Are you using the correct IP address?" << endl;
return -1;
}
cout << "Sleeping!" << endl;
sleep(2);
/*
* Uninitialize the device
*/
try {
sick_lms_1xx.Uninitialize();
}
catch(...) {
cerr << "Uninitialize failed!" << endl;
return -1;
}
/* Success! */
return 0;
}
<commit_msg>Adjusted lms1xx example file<commit_after>/*!
* \file main.cc
* \brief A simple application using the Sick LMS 1xx driver.
*
* Code by Jason C. Derenick and Christopher R. Mansley.
* Contact jasonder(at)seas(dot)upenn(dot)edu
*
* The Sick LIDAR Matlab/C++ Toolbox
* Copyright (c) 2009, Jason C. Derenick and Christopher R. Mansley
* All rights reserved.
*
* This software is released under a BSD Open-Source License.
* See http://sicktoolbox.sourceforge.net
*/
#include <string>
#include <iostream>
#include <sicklms1xx/SickLMS1xx.hh>
using namespace std;
using namespace SickToolbox;
int main(int argc, char* argv[])
{
/*
* Instantiate an instance
*/
SickLMS1xx sick_lms_1xx;
/*
* Initialize the Sick LMS 2xx
*/
try {
sick_lms_1xx.Initialize();
}
catch(...) {
cerr << "Initialize failed! Are you using the correct IP address?" << endl;
return -1;
}
try {
sick_lms_1xx.SetSickScanConfig();
}
catch(SickConfigException sick_exception) {
std::cout << sick_exception.what() << std::endl;
}
catch(...) {
cerr << "An Error Occurred!" << endl;
return -1;
}
/*
* Uninitialize the device
*/
try {
sick_lms_1xx.Uninitialize();
}
catch(...) {
cerr << "Uninitialize failed!" << endl;
return -1;
}
/* Success! */
return 0;
}
<|endoftext|> |
<commit_before>#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector>
#include <boost/archive/text_iarchive.hpp>
#include "liblager_connect.h"
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/extensions/XTest.h>
#include <unistd.h>
using namespace boost::interprocess;
using std::cout;
using std::endl;
using std::string;
using std::stringstream;
/* Based on https://bharathisubramanian.wordpress.com/2010/03/14/x11-fake-key-event-generation-using-xtest-ext/ab */
static void SendKey(Display * display, KeySym key_symbol, KeySym mod_symbol) {
KeyCode key_code = 0, mod_code = 0;
key_code = XKeysymToKeycode(display, key_symbol);
if (key_code == 0)
return;
XTestGrabControl(display, True);
/* Generate modkey press */
if (mod_symbol != 0) {
mod_code = XKeysymToKeycode(display, mod_symbol);
XTestFakeKeyEvent(display, mod_code, True, 0);
}
/* Generate regular key press and release */
XTestFakeKeyEvent(display, key_code, True, 0);
XTestFakeKeyEvent(display, key_code, False, 0);
/* Generate modkey release */
if (mod_symbol != 0) {
XTestFakeKeyEvent(display, mod_code, False, 0);
}
XSync(display, False);
XTestGrabControl(display, False);
}
void OpenChrome(Display* display) {
struct timespec sleep_interval = { 0, 750000 }; // microseconds
// Alt + F2 brings up the open application dialog on Ubuntu Unity
SendKey(display, XK_F2, XK_Alt_L);
// Give it time to open
sleep(1);
// Delete any old entries
SendKey(display, XK_BackSpace, 0);
// Enter google-chrome
SendKey(display, XK_G, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_G, 0);
SendKey(display, XK_L, 0);
SendKey(display, XK_E, 0);
SendKey(display, XK_minus, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_H, 0);
SendKey(display, XK_R, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_M, 0);
SendKey(display, XK_E, 0);
// Press Enter
SendKey(display, XK_Return, 0);
// Wait for Chrome to open
sleep(1);
// Alt + Tab to switch to the new window
SendKey(display, XK_Tab, XK_Alt_L);
}
void OpenNewTab(Display* display) {
// Ctrl + T
SendKey(display, XK_T, XK_Control_L);
}
void OpenCnn(Display* display) {
// Type www.cnn.com
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_N, 0);
SendKey(display, XK_N, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_M, 0);
// Press Enter
SendKey(display, XK_Return, 0);
}
void OpenGoogle(Display* display) {
// Type www.google.com
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_G, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_G, 0);
SendKey(display, XK_L, 0);
SendKey(display, XK_E, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_M, 0);
// Press Enter
SendKey(display, XK_Return, 0);
}
void CloseTab(Display* display) {
// Ctrl + W
SendKey(display, XK_W, XK_Control_L);
}
void ZoomIn(Display* display) {
// Ctrl + Plus
SendKey(display, XK_plus, XK_Control_L);
}
void ZoomOut(Display* display) {
// Ctrl + Minus
SendKey(display, XK_minus, XK_Control_L);
}
void RefreshTab(Display* display) {
// F5
SendKey(display, XK_F5, 0);
}
int main() {
Display* display = XOpenDisplay(NULL);
string gesture_name;
string gestures_file_name;
SubscribeToGesturesInFile(string(getenv("HOME")) + "/.lager/injector/gestures.dat");
while (true) {
gesture_name = GetDetectedGestureMessage().get_gesture_name();
cout << "Injector: Received message for gesture \"" << gesture_name << "\""
<< endl;
if (gesture_name.compare("OpenChrome") == 0) {
OpenChrome(display);
} else if (gesture_name.compare("NewTab") == 0) {
OpenNewTab(display);
} else if (gesture_name.compare("OpenCNN") == 0) {
OpenCnn(display);
} else if (gesture_name.compare("OpenGoogle") == 0) {
OpenGoogle(display);
} else if (gesture_name.compare("CloseTab") == 0) {
CloseTab(display);
} else if (gesture_name.compare("ZoomIn") == 0) {
ZoomIn(display);
} else if (gesture_name.compare("ZoomOut") == 0) {
ZoomOut(display);
} else if (gesture_name.compare("RefreshTab") == 0) {
RefreshTab(display);
} else {
cout << "Error: Received unexpected gesture: \"" << gesture_name << "\""
<< endl;
}
}
return 0;
}
<commit_msg>LaGeR Injector: Add Doxygen to the code<commit_after>#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector>
#include <boost/archive/text_iarchive.hpp>
#include "liblager_connect.h"
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/extensions/XTest.h>
#include <unistd.h>
using namespace boost::interprocess;
using std::cout;
using std::endl;
using std::string;
using std::stringstream;
/**
* Takes a key symbol and a modifier key. Sends X Server a press and release
* for the main key. If a modifier is specified, it first sends a press for the
* modifier and sends a release for it at the very end.
*
* Based on code from
* https://bharathisubramanian.wordpress.com/2010/03/14/x11-fake-key-event-generation-using-xtest-ext/ab
*/
static void SendKey(Display * display, KeySym key_symbol, KeySym mod_symbol) {
KeyCode key_code = 0, mod_code = 0;
key_code = XKeysymToKeycode(display, key_symbol);
if (key_code == 0)
return;
XTestGrabControl(display, True);
/* Generate modkey press */
if (mod_symbol != 0) {
mod_code = XKeysymToKeycode(display, mod_symbol);
XTestFakeKeyEvent(display, mod_code, True, 0);
}
/* Generate regular key press and release */
XTestFakeKeyEvent(display, key_code, True, 0);
XTestFakeKeyEvent(display, key_code, False, 0);
/* Generate modkey release */
if (mod_symbol != 0) {
XTestFakeKeyEvent(display, mod_code, False, 0);
}
XSync(display, False);
XTestGrabControl(display, False);
}
/**
* Sends X Server a series of key presses to bring up the open application
* dialog in Unity and start Google Chrome.
*/
void OpenChrome(Display* display) {
struct timespec sleep_interval = { 0, 750000 }; // microseconds
// Alt + F2 brings up the open application dialog on Ubuntu Unity
SendKey(display, XK_F2, XK_Alt_L);
// Give it time to open
sleep(1);
// Delete any old entries
SendKey(display, XK_BackSpace, 0);
// Enter google-chrome
SendKey(display, XK_G, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_G, 0);
SendKey(display, XK_L, 0);
SendKey(display, XK_E, 0);
SendKey(display, XK_minus, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_H, 0);
SendKey(display, XK_R, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_M, 0);
SendKey(display, XK_E, 0);
// Press Enter
SendKey(display, XK_Return, 0);
// Wait for Chrome to open
sleep(1);
// Alt + Tab to switch to the new window
SendKey(display, XK_Tab, XK_Alt_L);
}
/**
* Sends X Server the key presses to open a new tab in Google Chrome.
*/
void OpenNewTab(Display* display) {
// Ctrl + T
SendKey(display, XK_T, XK_Control_L);
}
/**
* Sends X Server the key presses to type the CNN URL and press Enter.
*/
void OpenCnn(Display* display) {
// Type www.cnn.com
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_N, 0);
SendKey(display, XK_N, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_M, 0);
// Press Enter
SendKey(display, XK_Return, 0);
}
/**
* Sends X Server the key presses to type the Google URL and press Enter.
*/
void OpenGoogle(Display* display) {
// Type www.google.com
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_W, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_G, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_G, 0);
SendKey(display, XK_L, 0);
SendKey(display, XK_E, 0);
SendKey(display, XK_period, 0);
SendKey(display, XK_C, 0);
SendKey(display, XK_O, 0);
SendKey(display, XK_M, 0);
// Press Enter
SendKey(display, XK_Return, 0);
}
/**
* Sends X Server the key presses to close a tab in Google Chrome.
*/
void CloseTab(Display* display) {
// Ctrl + W
SendKey(display, XK_W, XK_Control_L);
}
/**
* Sends X Server the key presses to zoom in in Google Chrome.
*/
void ZoomIn(Display* display) {
// Ctrl + Plus
SendKey(display, XK_plus, XK_Control_L);
}
/**
* Sends X Server the key presses to zoom out in Google Chrome.
*/
void ZoomOut(Display* display) {
// Ctrl + Minus
SendKey(display, XK_minus, XK_Control_L);
}
/**
* Sends X Server the key press to refresh a page in Google Chrome.
*/
void RefreshTab(Display* display) {
// F5
SendKey(display, XK_F5, 0);
}
/**
* The main loop of the LaGeR Injector.
*/
int main() {
Display* display = XOpenDisplay(NULL);
string gesture_name;
string gestures_file_name;
SubscribeToGesturesInFile(string(getenv("HOME")) + "/.lager/injector/gestures.dat");
while (true) {
gesture_name = GetDetectedGestureMessage().get_gesture_name();
cout << "Injector: Received message for gesture \"" << gesture_name << "\""
<< endl;
if (gesture_name.compare("OpenChrome") == 0) {
OpenChrome(display);
} else if (gesture_name.compare("NewTab") == 0) {
OpenNewTab(display);
} else if (gesture_name.compare("OpenCNN") == 0) {
OpenCnn(display);
} else if (gesture_name.compare("OpenGoogle") == 0) {
OpenGoogle(display);
} else if (gesture_name.compare("CloseTab") == 0) {
CloseTab(display);
} else if (gesture_name.compare("ZoomIn") == 0) {
ZoomIn(display);
} else if (gesture_name.compare("ZoomOut") == 0) {
ZoomOut(display);
} else if (gesture_name.compare("RefreshTab") == 0) {
RefreshTab(display);
} else {
cout << "Error: Received unexpected gesture: \"" << gesture_name << "\""
<< endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>//
// Created by Harrand on 15/03/2021.
//
#include "test_framework.hpp"
#include "phys/body.hpp"
TZ_TEST_BEGIN(gravity)
tz::phys::Body weight_1kg
{
tz::Vec3{},
tz::Vec3{},
tz::Vec3{},
1.0f
};
tz::phys::World world;
world.add_body(weight_1kg);
// Add gravity of 10 m/s^2
tz::phys::World::UniformForceID grav_id = world.register_uniform_force({0.0f, -10.0f, 0.0f});
topaz_expectf(weight_1kg.position[1] == 0.0f, "A phys::Body was moved within a world before any updates were performed. Expected y-coord to be %g, got %g", 0.0f, weight_1kg.position[1]);
// We ran for 10 seconds.
world.update(10000.0f);
topaz_expectf(weight_1kg.position[1] < 0.0f, "A phys::Body did not move within a world despite a uniform force applied.. Expected y-coord to be over %g, got %g", 0.0f, weight_1kg.position[1]);
// dx = v0t + 0.5 * a * t^2
float expected_change_in_y = 0.5f * 10.0f * (10.0f * 10.0f);
topaz_expectf(weight_1kg.position[1] == -expected_change_in_y, "A phys::Body did not move as expected given a uniform force and known mass. Expected y-coord to be %g or below, but instead it was %g.", -expected_change_in_y, weight_1kg.position[1]);
TZ_TEST_END
int main()
{
tz::test::Unit motion;
motion.add(gravity());
return motion.result();
}<commit_msg>* Fixed broken motion_integration_test due to introduction of transforms within tz::phys::Bodies<commit_after>//
// Created by Harrand on 15/03/2021.
//
#include "test_framework.hpp"
#include "phys/world.hpp"
TZ_TEST_BEGIN(gravity)
tz::gl::Transform trans;
tz::phys::Body weight_1kg
{
trans,
tz::Vec3{},
tz::Vec3{},
1.0f
};
tz::phys::World world;
world.add_body(weight_1kg);
// Add gravity of 10 m/s^2
tz::phys::World::UniformForceID grav_id = world.register_uniform_force({0.0f, -10.0f, 0.0f});
topaz_expectf(weight_1kg.transform.position[1] == 0.0f, "A phys::Body was moved within a world before any updates were performed. Expected y-coord to be %g, got %g", 0.0f, weight_1kg.transform.position[1]);
// We ran for 10 seconds.
world.update(10000.0f);
topaz_expectf(weight_1kg.transform.position[1] < 0.0f, "A phys::Body did not move within a world despite a uniform force applied.. Expected y-coord to be over %g, got %g", 0.0f, weight_1kg.transform.position[1]);
// dx = v0t + 0.5 * a * t^2
float expected_change_in_y = 0.5f * 10.0f * (10.0f * 10.0f);
topaz_expectf(weight_1kg.transform.position[1] == -expected_change_in_y, "A phys::Body did not move as expected given a uniform force and known mass. Expected y-coord to be %g or below, but instead it was %g.", -expected_change_in_y, weight_1kg.transform.position[1]);
TZ_TEST_END
int main()
{
tz::test::Unit motion;
motion.add(gravity());
return motion.result();
}<|endoftext|> |
<commit_before>#include "videosourcefactory.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#endif
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#ifdef USE_LIBVLC
#include "vlc_video_source.h"
#endif
namespace gg
{
VideoSourceFactory VideoSourceFactory::_factory_singleton;
VideoSourceFactory::VideoSourceFactory()
{
for (size_t i = 0; i < NUM_DEVICES; i++)
_devices[i] = nullptr;
}
VideoSourceFactory::~VideoSourceFactory()
{
free_device(DVI2PCIeDuo_DVI);
free_device(DVI2PCIeDuo_SDI);
}
VideoSourceFactory & VideoSourceFactory::get_instance()
{
return _factory_singleton;
}
IVideoSource * VideoSourceFactory::get_device(Device device,
ColourSpace colour)
{
// if already connected, return
if (_devices[(int) device] != nullptr) return _devices[(int) device];
// otherwise, connect
IVideoSource * src = nullptr;
switch (device)
{
// Epiphan DVI2PCIe Duo DVI ========================================
case DVI2PCIeDuo_DVI:
switch (colour)
{
// BGRA ========================================
case BGRA:
#ifdef USE_OPENCV
src = new VideoSourceOpenCV(0);
#else
throw VideoSourceError(
"BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
break;
// I420 ========================================
case I420:
#ifdef USE_LIBVLC
try
{
src = new VideoSourceVLC("v4l2:///dev/video0:chroma=I420");
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_DVI
try
{
src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_DVI,
V2U_GRABFRAME_FORMAT_I420);
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#else
throw DeviceNotFound("Epiphan_DVI2PCIeDuo_DVI macro not defined");
#endif
#else
throw VideoSourceError(
"I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
break;
// unsupported colour space ========================================
default:
throw VideoSourceError("Colour space not supported");
}
break;
// Epiphan DVI2PCIe Duo SDI ========================================
case DVI2PCIeDuo_SDI:
switch (colour)
{
// BGRA ========================================
case BGRA:
#ifdef USE_OPENCV
src = new VideoSourceOpenCV(1);
#else
throw VideoSourceError(
"BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
break;
// I420 ========================================
case I420:
#ifdef USE_LIBVLC
try
{
src = new VideoSourceVLC("v4l2:///dev/video1:chroma=I420");
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_SDI
try
{
src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_SDI,
V2U_GRABFRAME_FORMAT_I420);
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#else
throw DeviceNotFound("Epiphan_DVI2PCIeDuo_SDI macro not defined");
#endif
#else
throw VideoSourceError(
"I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
break;
// unsupported colour space ========================================
default:
throw VideoSourceError("Colour space not supported");
}
break;
// unsupported device ========================================
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(device))
.append(" not recognised");
throw DeviceNotFound(msg);
}
if (src != nullptr)
{
// check querying frame dimensions
int width = -1, height = -1;
if (not src->get_frame_dimensions(width, height))
{
throw DeviceOffline(
"Device connected but does not return frame dimensions");
}
// check meaningful frame dimensions
if (width <= 0 or height <= 0)
{
throw DeviceOffline(
"Device connected but returns meaningless frame dimensions");
}
// check querying frames
VideoFrame frame(colour, true);
if (not src->get_frame(frame))
{
throw DeviceOffline(
"Device connected does not return frames");
}
// if no exception raised up to here, glory be to GIFT-Grab
_devices[(int) device] = src;
}
return _devices[(int) device];
if (_devices[(int) device] == nullptr)
{
_devices[(int) device] = new DummyVideoSource;
_device_colours[(int) device] = colour;
}
else if (_device_colours[(int) device] != colour)
throw DeviceAlreadyConnected(
"Device already connected using another colour space"
);
return _devices[(int) device];
}
void VideoSourceFactory::free_device(Device device)
{
switch (device)
{
case DVI2PCIeDuo_DVI:
case DVI2PCIeDuo_SDI:
break; // everything up to here is recognised
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(device))
.append(" not recognised");
throw DeviceNotFound(msg);
}
if (_devices[(int) device] != nullptr)
delete _devices[(int) device];
_devices[(int) device] = nullptr;
}
}
<commit_msg>Issue #121: amended get_device with device colour check and setting<commit_after>#include "videosourcefactory.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#endif
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#ifdef USE_LIBVLC
#include "vlc_video_source.h"
#endif
namespace gg
{
VideoSourceFactory VideoSourceFactory::_factory_singleton;
VideoSourceFactory::VideoSourceFactory()
{
for (size_t i = 0; i < NUM_DEVICES; i++)
_devices[i] = nullptr;
}
VideoSourceFactory::~VideoSourceFactory()
{
free_device(DVI2PCIeDuo_DVI);
free_device(DVI2PCIeDuo_SDI);
}
VideoSourceFactory & VideoSourceFactory::get_instance()
{
return _factory_singleton;
}
IVideoSource * VideoSourceFactory::get_device(Device device,
ColourSpace colour)
{
// if already connected, return
if (_devices[(int) device] != nullptr)
{
if (_device_colours[(int) device] != colour)
throw DeviceAlreadyConnected(
"Device already connected using another colour space"
);
else
return _devices[(int) device];
}
// otherwise, connect
IVideoSource * src = nullptr;
switch (device)
{
// Epiphan DVI2PCIe Duo DVI ========================================
case DVI2PCIeDuo_DVI:
switch (colour)
{
// BGRA ========================================
case BGRA:
#ifdef USE_OPENCV
src = new VideoSourceOpenCV(0);
#else
throw VideoSourceError(
"BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
break;
// I420 ========================================
case I420:
#ifdef USE_LIBVLC
try
{
src = new VideoSourceVLC("v4l2:///dev/video0:chroma=I420");
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_DVI
try
{
src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_DVI,
V2U_GRABFRAME_FORMAT_I420);
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#else
throw DeviceNotFound("Epiphan_DVI2PCIeDuo_DVI macro not defined");
#endif
#else
throw VideoSourceError(
"I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
break;
// unsupported colour space ========================================
default:
throw VideoSourceError("Colour space not supported");
}
break;
// Epiphan DVI2PCIe Duo SDI ========================================
case DVI2PCIeDuo_SDI:
switch (colour)
{
// BGRA ========================================
case BGRA:
#ifdef USE_OPENCV
src = new VideoSourceOpenCV(1);
#else
throw VideoSourceError(
"BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
break;
// I420 ========================================
case I420:
#ifdef USE_LIBVLC
try
{
src = new VideoSourceVLC("v4l2:///dev/video1:chroma=I420");
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_SDI
try
{
src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_SDI,
V2U_GRABFRAME_FORMAT_I420);
}
catch (VideoSourceError & e)
{
throw DeviceNotFound(e.what());
}
#else
throw DeviceNotFound("Epiphan_DVI2PCIeDuo_SDI macro not defined");
#endif
#else
throw VideoSourceError(
"I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
break;
// unsupported colour space ========================================
default:
throw VideoSourceError("Colour space not supported");
}
break;
// unsupported device ========================================
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(device))
.append(" not recognised");
throw DeviceNotFound(msg);
}
if (src != nullptr)
{
// check querying frame dimensions
int width = -1, height = -1;
if (not src->get_frame_dimensions(width, height))
{
throw DeviceOffline(
"Device connected but does not return frame dimensions");
}
// check meaningful frame dimensions
if (width <= 0 or height <= 0)
{
throw DeviceOffline(
"Device connected but returns meaningless frame dimensions");
}
// check querying frames
VideoFrame frame(colour, true);
if (not src->get_frame(frame))
{
throw DeviceOffline(
"Device connected does not return frames");
}
// if no exception raised up to here, glory be to GIFT-Grab
_devices[(int) device] = src;
_device_colours[(int) device] = colour;
}
return _devices[(int) device];
}
void VideoSourceFactory::free_device(Device device)
{
switch (device)
{
case DVI2PCIeDuo_DVI:
case DVI2PCIeDuo_SDI:
break; // everything up to here is recognised
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(device))
.append(" not recognised");
throw DeviceNotFound(msg);
}
if (_devices[(int) device] != nullptr)
delete _devices[(int) device];
_devices[(int) device] = nullptr;
}
}
<|endoftext|> |
<commit_before>#include "rubymotion.h"
#include "motion-game.h"
/// @class Point < Object
/// A point represents a location in a two-dimensional coordinate system using
/// +x+ and +y+ variables.
///
/// When calling a method that expects a +Point+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
/// node.location = [10, 20]
/// is the same as
/// point = MG::Point.new
/// point.x = 10
/// point.y = 20
/// node.location = point
VALUE rb_cPoint = Qnil;
extern "C"
VALUE
rb_ccvec2_to_obj(cocos2d::Vec2 _vec2)
{
cocos2d::Vec2 *vec2 = new cocos2d::Vec2(_vec2);
// cocos2d::Vec2 does not inherite cocos2d::Ref.
return rb_class_wrap_new(vec2, rb_cPoint);
}
static VALUE
point_alloc(VALUE rcv, SEL sel)
{
return rb_ccvec2_to_obj(cocos2d::Vec2());
}
/// @property #x
/// @return [Float] the x coordinate of the point.
static VALUE
point_x(VALUE rcv, SEL sel)
{
return DBL2NUM(VEC2(rcv)->x);
}
static VALUE
point_x_set(VALUE rcv, SEL sel, VALUE x)
{
VEC2(rcv)->x = NUM2DBL(x);
return x;
}
/// @property #y
/// @return [Float] the y coordinate of the point.
static VALUE
point_y(VALUE rcv, SEL sel)
{
return DBL2NUM(VEC2(rcv)->y);
}
static VALUE
point_y_set(VALUE rcv, SEL sel, VALUE y)
{
VEC2(rcv)->y = NUM2DBL(y);
return y;
}
/// @group Helpers
/// @method #+(point)
/// Adds the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point]
/// @return [Point] A new Point object.
static VALUE
point_plus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccvec2_to_obj(*VEC2(rcv) + rb_any_to_ccvec2(obj));
}
/// @method #-(point)
/// Substracts the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point]
/// @return [Point] A new Point object.
static VALUE
point_minus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccvec2_to_obj(*VEC2(rcv) - rb_any_to_ccvec2(obj));
}
/// @method #distance(point)
/// Calculates the distance between two points.
/// @param point [Point]
/// @return [Float] the distance.
static VALUE
point_distance(VALUE rcv, SEL sel, VALUE obj)
{
return DBL2NUM(VEC2(rcv)->getDistance(rb_any_to_ccvec2(obj)));
}
static VALUE
point_inspect(VALUE rcv, SEL sel)
{
auto vec = VEC2(rcv);
char buf[100];
snprintf(buf, sizeof buf, "[%f, %f]", vec->x, vec->y);
return RSTRING_NEW(buf);
}
/// @class Size < Object
/// A size represents the dimensions of width and height of an object.
///
/// When calling a method that expects a +Size+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
/// node.size = [200, 400]
/// is the same as
/// size = MG::Size.new
/// size.x = 200
/// size.y = 400
/// node.size = size
VALUE rb_cSize = Qnil;
extern "C"
VALUE
rb_ccsize_to_obj(cocos2d::Size _size)
{
cocos2d::Size *size = new cocos2d::Size(_size);
// cocos2d::Size does not inherite cocos2d::Ref.
return rb_class_wrap_new(size, rb_cSize);
}
static VALUE
size_alloc(VALUE rcv, SEL sel)
{
return rb_ccsize_to_obj(cocos2d::Size());
}
/// @property #width
/// @return [Float] the size width.
static VALUE
size_width(VALUE rcv, SEL sel)
{
return DBL2NUM(SIZE(rcv)->width);
}
static VALUE
size_width_set(VALUE rcv, SEL sel, VALUE obj)
{
SIZE(rcv)->width = NUM2DBL(obj);
return obj;
}
/// @property #height
/// @return [Float] the size height.
static VALUE
size_height(VALUE rcv, SEL sel)
{
return DBL2NUM(SIZE(rcv)->height);
}
static VALUE
size_height_set(VALUE rcv, SEL sel, VALUE obj)
{
SIZE(rcv)->height = NUM2DBL(obj);
return obj;
}
/// @group Helpers
/// @method #+(size)
/// Adds the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size]
/// @return [Size] a new Size object.
static VALUE
size_plus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) + rb_any_to_ccsize(obj));
}
/// @method #-(size)
/// Substracts the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size]
/// @return [Size] a new Size object.
static VALUE
size_minus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) - rb_any_to_ccsize(obj));
}
/// @method #/(delta)
/// Divides the dimensions of the receiver with the given number.
/// @param delta [Float] the number to divide the receiver with.
/// @return [Size] a new Size object.
static VALUE
size_div(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) / NUM2DBL(obj));
}
/// @method #*(delta)
/// Multiplies the dimensions of the receiver with the given number.
/// @param delta [Float] the number to multiply the receiver with.
/// @return [Size] a new Size object.
static VALUE
size_mul(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) * NUM2DBL(obj));
}
static VALUE
size_inspect(VALUE rcv, SEL sel)
{
auto vec = SIZE(rcv);
char buf[100];
snprintf(buf, sizeof buf, "[%f, %f]", vec->width, vec->height);
return RSTRING_NEW(buf);
}
/// @class Color < Object
/// A color represents the color, and sometimes opacity (alpha) of an object.
///
/// When calling a method that expects a +Color+ object, a 3-element +Array+
/// (red-green-blue) or 4-element +Array+ (red-green-blue-alpha) can be passed
/// instead, as a convenience shortcut. For example,
/// node.color = [0.2, 0.3, 0.4]
/// is the same as
/// color = MG::Color.new
/// color.red = 0.2
/// color.green = 0.3
/// color.blue = 0.4
/// node.color = color
/// Alternatively, a +Symbol+ corresponding to a basic color name can be
/// provided. For example,
/// node.color = :red
/// is the same as
/// color = MG::Color.new
/// color.red = 1.0
/// color.green = color.blue = 0
/// node.color = color
/// Currently, the following symbols are supported: +:white+, +:black+, +:red+,
/// +:green+ and +:blue+.
/// The +MG::Color.new+ constructor will return the black color.
VALUE rb_cColor = Qnil;
extern "C"
VALUE
rb_cccolor4_to_obj(cocos2d::Color4B _color)
{
cocos2d::Color4B *color = new cocos2d::Color4B(_color);
// cocos2d::Color4B does not inherite cocos2d::Ref.
return rb_class_wrap_new(color, rb_cColor);
}
static VALUE
color_alloc(VALUE rcv, SEL sel)
{
return rb_cccolor4_to_obj(cocos2d::Color4B::BLACK);
}
/// @property #red
/// @return [Float] the red portion of the color, from +0.0+ to +1.0+.
static VALUE
color_red(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->r);
}
static VALUE
color_red_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->r = NUM2BYTE(val);
return val;
}
/// @property #green
/// @return [Float] the green portion of the color, from +0.0+ to +1.0+.
static VALUE
color_green(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->g);
}
static VALUE
color_green_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->g = NUM2BYTE(val);
return val;
}
/// @property #blue
/// @return [Float] the blue portion of the color, from +0.0+ to +1.0+.
static VALUE
color_blue(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->b);
}
static VALUE
color_blue_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->b = NUM2BYTE(val);
return val;
}
/// @property #alpha
/// @return [Float] the alpha portion of the color, from +0.0+ to +1.0+.
static VALUE
color_alpha(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->a);
}
static VALUE
color_alpha_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->a = NUM2BYTE(val);
return val;
}
static VALUE
color_inspect(VALUE rcv, SEL sel)
{
auto color = COLOR(rcv);
char buf[100];
snprintf(buf, sizeof buf, "#<Color Red:%d Green:%d Blue:%d Alpha:%d>",
color->r, color->g, color->b, color->a);
return RSTRING_NEW(buf);
}
extern "C"
void
Init_Types(void)
{
rb_cPoint = rb_define_class_under(rb_mMC, "Point", rb_cObject);
rb_define_singleton_method(rb_cPoint, "alloc", point_alloc, 0);
rb_define_method(rb_cPoint, "x", point_x, 0);
rb_define_method(rb_cPoint, "x=", point_x_set, 1);
rb_define_method(rb_cPoint, "y", point_y, 0);
rb_define_method(rb_cPoint, "y=", point_y_set, 1);
rb_define_method(rb_cPoint, "+", point_plus, 1);
rb_define_method(rb_cPoint, "-", point_minus, 1);
rb_define_method(rb_cPoint, "distance", point_distance, 1);
rb_define_method(rb_cPoint, "inspect", point_inspect, 0);
rb_cSize = rb_define_class_under(rb_mMC, "Size", rb_cObject);
rb_define_singleton_method(rb_cSize, "alloc", size_alloc, 0);
rb_define_method(rb_cSize, "width", size_width, 0);
rb_define_method(rb_cSize, "width=", size_width_set, 1);
rb_define_method(rb_cSize, "height", size_height, 0);
rb_define_method(rb_cSize, "height=", size_height_set, 1);
rb_define_method(rb_cSize, "+", size_plus, 1);
rb_define_method(rb_cSize, "-", size_minus, 1);
rb_define_method(rb_cSize, "/", size_div, 1);
rb_define_method(rb_cSize, "*", size_mul, 1);
rb_define_method(rb_cSize, "inspect", size_inspect, 0);
rb_cColor = rb_define_class_under(rb_mMC, "Color", rb_cObject);
rb_define_singleton_method(rb_cColor, "alloc", color_alloc, 0);
rb_define_method(rb_cColor, "red", color_red, 0);
rb_define_method(rb_cColor, "red=", color_red_set, 1);
rb_define_method(rb_cColor, "green", color_green, 0);
rb_define_method(rb_cColor, "green=", color_green_set, 1);
rb_define_method(rb_cColor, "blue", color_blue, 0);
rb_define_method(rb_cColor, "blue=", color_blue_set, 1);
rb_define_method(rb_cColor, "alpha", color_alpha, 0);
rb_define_method(rb_cColor, "alpha=", color_alpha_set, 1);
rb_define_method(rb_cColor, "inspect", color_inspect, 0);
}
<commit_msg>fix documents<commit_after>#include "rubymotion.h"
#include "motion-game.h"
/// @class Point < Object
/// A point represents a location in a two-dimensional coordinate system using
/// +x+ and +y+ variables.
///
/// When calling a method that expects a +Point+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
/// node.location = [10, 20]
/// is the same as
/// point = MG::Point.new
/// point.x = 10
/// point.y = 20
/// node.location = point
VALUE rb_cPoint = Qnil;
extern "C"
VALUE
rb_ccvec2_to_obj(cocos2d::Vec2 _vec2)
{
cocos2d::Vec2 *vec2 = new cocos2d::Vec2(_vec2);
// cocos2d::Vec2 does not inherite cocos2d::Ref.
return rb_class_wrap_new(vec2, rb_cPoint);
}
static VALUE
point_alloc(VALUE rcv, SEL sel)
{
return rb_ccvec2_to_obj(cocos2d::Vec2());
}
/// @property #x
/// @return [Float] the x coordinate of the point.
static VALUE
point_x(VALUE rcv, SEL sel)
{
return DBL2NUM(VEC2(rcv)->x);
}
static VALUE
point_x_set(VALUE rcv, SEL sel, VALUE x)
{
VEC2(rcv)->x = NUM2DBL(x);
return x;
}
/// @property #y
/// @return [Float] the y coordinate of the point.
static VALUE
point_y(VALUE rcv, SEL sel)
{
return DBL2NUM(VEC2(rcv)->y);
}
static VALUE
point_y_set(VALUE rcv, SEL sel, VALUE y)
{
VEC2(rcv)->y = NUM2DBL(y);
return y;
}
/// @group Helpers
/// @method #+(point)
/// Adds the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point] A coordinate.
/// @return [Point] A new Point object.
static VALUE
point_plus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccvec2_to_obj(*VEC2(rcv) + rb_any_to_ccvec2(obj));
}
/// @method #-(point)
/// Substracts the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point] A coordinate.
/// @return [Point] A new Point object.
static VALUE
point_minus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccvec2_to_obj(*VEC2(rcv) - rb_any_to_ccvec2(obj));
}
/// @method #distance(point)
/// Calculates the distance between two points.
/// @param point [Point] A point to calculate the distance.
/// @return [Float] the distance.
static VALUE
point_distance(VALUE rcv, SEL sel, VALUE obj)
{
return DBL2NUM(VEC2(rcv)->getDistance(rb_any_to_ccvec2(obj)));
}
static VALUE
point_inspect(VALUE rcv, SEL sel)
{
auto vec = VEC2(rcv);
char buf[100];
snprintf(buf, sizeof buf, "[%f, %f]", vec->x, vec->y);
return RSTRING_NEW(buf);
}
/// @class Size < Object
/// A size represents the dimensions of width and height of an object.
///
/// When calling a method that expects a +Size+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
/// node.size = [200, 400]
/// is the same as
/// size = MG::Size.new
/// size.x = 200
/// size.y = 400
/// node.size = size
VALUE rb_cSize = Qnil;
extern "C"
VALUE
rb_ccsize_to_obj(cocos2d::Size _size)
{
cocos2d::Size *size = new cocos2d::Size(_size);
// cocos2d::Size does not inherite cocos2d::Ref.
return rb_class_wrap_new(size, rb_cSize);
}
static VALUE
size_alloc(VALUE rcv, SEL sel)
{
return rb_ccsize_to_obj(cocos2d::Size());
}
/// @property #width
/// @return [Float] the size width.
static VALUE
size_width(VALUE rcv, SEL sel)
{
return DBL2NUM(SIZE(rcv)->width);
}
static VALUE
size_width_set(VALUE rcv, SEL sel, VALUE obj)
{
SIZE(rcv)->width = NUM2DBL(obj);
return obj;
}
/// @property #height
/// @return [Float] the size height.
static VALUE
size_height(VALUE rcv, SEL sel)
{
return DBL2NUM(SIZE(rcv)->height);
}
static VALUE
size_height_set(VALUE rcv, SEL sel, VALUE obj)
{
SIZE(rcv)->height = NUM2DBL(obj);
return obj;
}
/// @group Helpers
/// @method #+(size)
/// Adds the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size] A dimensios.
/// @return [Size] a new Size object.
static VALUE
size_plus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) + rb_any_to_ccsize(obj));
}
/// @method #-(size)
/// Substracts the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size] A dimensios.
/// @return [Size] a new Size object.
static VALUE
size_minus(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) - rb_any_to_ccsize(obj));
}
/// @method #/(delta)
/// Divides the dimensions of the receiver with the given number.
/// @param delta [Float] the number to divide the receiver with.
/// @return [Size] a new Size object.
static VALUE
size_div(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) / NUM2DBL(obj));
}
/// @method #*(delta)
/// Multiplies the dimensions of the receiver with the given number.
/// @param delta [Float] the number to multiply the receiver with.
/// @return [Size] a new Size object.
static VALUE
size_mul(VALUE rcv, SEL sel, VALUE obj)
{
return rb_ccsize_to_obj(*SIZE(rcv) * NUM2DBL(obj));
}
static VALUE
size_inspect(VALUE rcv, SEL sel)
{
auto vec = SIZE(rcv);
char buf[100];
snprintf(buf, sizeof buf, "[%f, %f]", vec->width, vec->height);
return RSTRING_NEW(buf);
}
/// @class Color < Object
/// A color represents the color, and sometimes opacity (alpha) of an object.
///
/// When calling a method that expects a +Color+ object, a 3-element +Array+
/// (red-green-blue) or 4-element +Array+ (red-green-blue-alpha) can be passed
/// instead, as a convenience shortcut. For example,
/// node.color = [0.2, 0.3, 0.4]
/// is the same as
/// color = MG::Color.new
/// color.red = 0.2
/// color.green = 0.3
/// color.blue = 0.4
/// node.color = color
/// Alternatively, a +Symbol+ corresponding to a basic color name can be
/// provided. For example,
/// node.color = :red
/// is the same as
/// color = MG::Color.new
/// color.red = 1.0
/// color.green = color.blue = 0
/// node.color = color
/// Currently, the following symbols are supported: +:white+, +:black+, +:red+,
/// +:green+ and +:blue+.
/// The +MG::Color.new+ constructor will return the black color.
VALUE rb_cColor = Qnil;
extern "C"
VALUE
rb_cccolor4_to_obj(cocos2d::Color4B _color)
{
cocos2d::Color4B *color = new cocos2d::Color4B(_color);
// cocos2d::Color4B does not inherite cocos2d::Ref.
return rb_class_wrap_new(color, rb_cColor);
}
static VALUE
color_alloc(VALUE rcv, SEL sel)
{
return rb_cccolor4_to_obj(cocos2d::Color4B::BLACK);
}
/// @property #red
/// @return [Float] the red portion of the color, from +0.0+ to +1.0+.
static VALUE
color_red(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->r);
}
static VALUE
color_red_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->r = NUM2BYTE(val);
return val;
}
/// @property #green
/// @return [Float] the green portion of the color, from +0.0+ to +1.0+.
static VALUE
color_green(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->g);
}
static VALUE
color_green_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->g = NUM2BYTE(val);
return val;
}
/// @property #blue
/// @return [Float] the blue portion of the color, from +0.0+ to +1.0+.
static VALUE
color_blue(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->b);
}
static VALUE
color_blue_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->b = NUM2BYTE(val);
return val;
}
/// @property #alpha
/// @return [Float] the alpha portion of the color, from +0.0+ to +1.0+.
static VALUE
color_alpha(VALUE rcv, SEL sel)
{
return BYTE2NUM(COLOR(rcv)->a);
}
static VALUE
color_alpha_set(VALUE rcv, SEL sel, VALUE val)
{
COLOR(rcv)->a = NUM2BYTE(val);
return val;
}
static VALUE
color_inspect(VALUE rcv, SEL sel)
{
auto color = COLOR(rcv);
char buf[100];
snprintf(buf, sizeof buf, "#<Color Red:%d Green:%d Blue:%d Alpha:%d>",
color->r, color->g, color->b, color->a);
return RSTRING_NEW(buf);
}
extern "C"
void
Init_Types(void)
{
rb_cPoint = rb_define_class_under(rb_mMC, "Point", rb_cObject);
rb_define_singleton_method(rb_cPoint, "alloc", point_alloc, 0);
rb_define_method(rb_cPoint, "x", point_x, 0);
rb_define_method(rb_cPoint, "x=", point_x_set, 1);
rb_define_method(rb_cPoint, "y", point_y, 0);
rb_define_method(rb_cPoint, "y=", point_y_set, 1);
rb_define_method(rb_cPoint, "+", point_plus, 1);
rb_define_method(rb_cPoint, "-", point_minus, 1);
rb_define_method(rb_cPoint, "distance", point_distance, 1);
rb_define_method(rb_cPoint, "inspect", point_inspect, 0);
rb_cSize = rb_define_class_under(rb_mMC, "Size", rb_cObject);
rb_define_singleton_method(rb_cSize, "alloc", size_alloc, 0);
rb_define_method(rb_cSize, "width", size_width, 0);
rb_define_method(rb_cSize, "width=", size_width_set, 1);
rb_define_method(rb_cSize, "height", size_height, 0);
rb_define_method(rb_cSize, "height=", size_height_set, 1);
rb_define_method(rb_cSize, "+", size_plus, 1);
rb_define_method(rb_cSize, "-", size_minus, 1);
rb_define_method(rb_cSize, "/", size_div, 1);
rb_define_method(rb_cSize, "*", size_mul, 1);
rb_define_method(rb_cSize, "inspect", size_inspect, 0);
rb_cColor = rb_define_class_under(rb_mMC, "Color", rb_cObject);
rb_define_singleton_method(rb_cColor, "alloc", color_alloc, 0);
rb_define_method(rb_cColor, "red", color_red, 0);
rb_define_method(rb_cColor, "red=", color_red_set, 1);
rb_define_method(rb_cColor, "green", color_green, 0);
rb_define_method(rb_cColor, "green=", color_green_set, 1);
rb_define_method(rb_cColor, "blue", color_blue, 0);
rb_define_method(rb_cColor, "blue=", color_blue_set, 1);
rb_define_method(rb_cColor, "alpha", color_alpha, 0);
rb_define_method(rb_cColor, "alpha=", color_alpha_set, 1);
rb_define_method(rb_cColor, "inspect", color_inspect, 0);
}
<|endoftext|> |
<commit_before>#include "include/udata.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
namespace amici {
UserData::UserData(int np, int nk, int nx) : np(np), nk(nk), nx(nx) {}
UserData::UserData() : np(0), nk(0), nx(0) {}
UserData::UserData(const UserData &other) : UserData(other.np, other.nk, other.nx)
{
nmaxevent = other.nmaxevent;
qpositivex = other.qpositivex;
if(other.plist) {
plist = new int[nplist];
std::copy(other.plist, other.plist + other.nplist, plist);
}
nplist = other.nplist;
nt = other.nt;
if(other.p) {
p = new double[np];
std::copy(other.p, other.p + other.np, p);
}
if(other.k) {
k = new double[nk];
std::copy(other.k, other.k + other.nk, k);
}
pscale = other.pscale;
tstart = other.tstart;
if(other.ts) {
ts = new double[nt];
std::copy(other.ts, other.ts + other.nt, ts);
}
if(other.pbar) {
pbar = new double[nplist];
std::copy(other.pbar, other.pbar + other.nplist, pbar);
}
if(other.xbar) {
xbar = new double[nx];
std::copy(other.xbar, other.xbar + other.nx, xbar);
}
sensi = other.sensi;
atol = other.atol;
rtol = other.rtol;
maxsteps = other.maxsteps;
newton_maxsteps = other.newton_maxsteps;
newton_maxlinsteps = other.newton_maxlinsteps;
newton_preeq = other.newton_preeq;
newton_precon = other.newton_precon;
ism = other.ism;
sensi_meth = other.sensi_meth;
linsol = other.linsol;
interpType = other.interpType;
lmm = other.lmm;
iter = other.iter;
stldet = other.stldet;
if(other.x0data) {
x0data = new double[nx];
std::copy(other.x0data, other.x0data + other.nx, x0data);
}
if(other.sx0data) {
sx0data = new double[nx];
std::copy(other.sx0data, other.sx0data + other.nx * other.nplist, sx0data);
}
ordering = other.ordering;
newton_precon = other.newton_precon;
ism = other.ism;
}
int UserData::unscaleParameters(double *bufferUnscaled) const {
/**
* unscaleParameters removes parameter scaling according to the parameter
* scaling in pscale
*
* @param[out] bufferUnscaled unscaled parameters are written to the array
* @type double
*
* @return status flag indicating success of execution @type int
*/
switch (pscale) {
case AMICI_SCALING_LOG10:
for (int ip = 0; ip < np; ++ip) {
bufferUnscaled[ip] = pow(10, p[ip]);
}
break;
case AMICI_SCALING_LN:
for (int ip = 0; ip < np; ++ip)
bufferUnscaled[ip] = exp(p[ip]);
break;
case AMICI_SCALING_NONE:
for (int ip = 0; ip < np; ++ip)
bufferUnscaled[ip] = p[ip];
break;
}
return AMICI_SUCCESS;
}
void UserData::setTimepoints(const double *timepoints, int numTimepoints) {
if (ts) {
delete[] ts;
}
nt = numTimepoints;
ts = new double[nt];
memcpy(ts, timepoints, sizeof(double) * nt);
}
void UserData::setParameters(const double *parameters) {
if (p) {
delete[] p;
}
p = new double[np];
memcpy(p, parameters, sizeof(double) * np);
}
void UserData::setConstants(const double *constants) {
if (k) {
delete[] k;
}
k = new double[nk];
memcpy(k, constants, sizeof(double) * nk);
}
void UserData::setPlist(const double *plist, int nplist) {
if (this->plist) {
delete[] this->plist;
}
this->nplist = nplist;
this->plist = new int[nplist];
for (int ip = 0; ip < nplist; ip++) {
this->plist[ip] = (int)plist[ip];
}
}
void UserData::setPlist(const int *plist, int nplist) {
if (this->plist) {
delete[] this->plist;
}
this->nplist = nplist;
this->plist = new int[nplist];
memcpy(this->plist, plist, sizeof(int) * nplist);
}
void UserData::requireSensitivitiesForAllParameters()
{
nplist = np;
plist = new int[nplist];
for (int i = 0; i < nplist; ++i)
plist[i] = i;
}
void UserData::setPbar(const double *parameterScaling) {
if (pbar) {
delete[] pbar;
}
if(parameterScaling) {
pbar = new double[nplist];
memcpy(pbar, parameterScaling, sizeof(double) * nplist);
} else {
pbar = nullptr;
}
}
void UserData::setStateInitialization(const double *stateInitialization) {
if (x0data) {
delete[] x0data;
}
if(stateInitialization) {
x0data = new double[nx];
memcpy(x0data, stateInitialization, sizeof(double) * nx);
} else {
x0data = nullptr;
}
}
void UserData::setSensitivityInitialization(
const double *sensitivityInitialization) {
if (sx0data) {
delete[] sx0data;
}
if(sensitivityInitialization) {
sx0data = new double[nx * nplist];
memcpy(sx0data, sensitivityInitialization, sizeof(double) * nx * nplist);
} else {
sx0data = nullptr;
}
}
UserData::~UserData() {
if (qpositivex)
delete[] qpositivex;
if (p)
delete[] p;
if (k)
delete[] k;
if (ts)
delete[] ts;
if (pbar)
delete[] pbar;
if (xbar)
delete[] xbar;
if (x0data)
delete[] x0data;
if (sx0data)
delete[] sx0data;
if (plist)
delete[] plist;
}
void UserData::print() const {
printf("qpositivex: %p\n", qpositivex);
printf("plist: %p\n", plist);
printf("nplist: %d\n", nplist);
printf("nt: %d\n", nt);
printf("nmaxevent: %d\n", nmaxevent);
printf("p: %p\n", p);
printf("k: %p\n", k);
printf("tstart: %e\n", tstart);
printf("ts: %p\n", ts);
printf("pbar: %p\n", pbar);
printf("xbar: %p\n", xbar);
printf("sensi: %d\n", sensi);
printf("atol: %e\n", atol);
printf("rtol: %e\n", rtol);
printf("maxsteps: %d\n", maxsteps);
printf("newton_maxsteps: %d\n", newton_maxsteps);
printf("newton_maxlinsteps: %d\n", newton_maxlinsteps);
printf("ism: %d\n", ism);
printf("sensi_meth: %d\n", sensi_meth);
printf("linsol: %d\n", linsol);
printf("interpType: %d\n", interpType);
printf("lmm: %d\n", lmm);
printf("iter: %d\n", iter);
printf("stldet: %d\n", stldet);
printf("x0data: %p\n", x0data);
printf("sx0data: %p\n", sx0data);
printf("ordering: %d\n", ordering);
}
} // namespace amici
<commit_msg>Fix array dimensions<commit_after>#include "include/udata.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
namespace amici {
UserData::UserData(int np, int nk, int nx) : np(np), nk(nk), nx(nx) {}
UserData::UserData() : np(0), nk(0), nx(0) {}
UserData::UserData(const UserData &other) : UserData(other.np, other.nk, other.nx)
{
nmaxevent = other.nmaxevent;
qpositivex = other.qpositivex;
if(other.plist) {
plist = new int[other.nplist];
std::copy(other.plist, other.plist + other.nplist, plist);
}
nplist = other.nplist;
nt = other.nt;
if(other.p) {
p = new double[other.np];
std::copy(other.p, other.p + other.np, p);
}
if(other.k) {
k = new double[other.nk];
std::copy(other.k, other.k + other.nk, k);
}
pscale = other.pscale;
tstart = other.tstart;
if(other.ts) {
ts = new double[other.nt];
std::copy(other.ts, other.ts + other.nt, ts);
}
if(other.pbar) {
pbar = new double[other.nplist];
std::copy(other.pbar, other.pbar + other.nplist, pbar);
}
if(other.xbar) {
xbar = new double[other.nx];
std::copy(other.xbar, other.xbar + other.nx, xbar);
}
sensi = other.sensi;
atol = other.atol;
rtol = other.rtol;
maxsteps = other.maxsteps;
newton_maxsteps = other.newton_maxsteps;
newton_maxlinsteps = other.newton_maxlinsteps;
newton_preeq = other.newton_preeq;
newton_precon = other.newton_precon;
ism = other.ism;
sensi_meth = other.sensi_meth;
linsol = other.linsol;
interpType = other.interpType;
lmm = other.lmm;
iter = other.iter;
stldet = other.stldet;
if(other.x0data) {
x0data = new double[other.nx];
std::copy(other.x0data, other.x0data + other.nx, x0data);
}
if(other.sx0data) {
sx0data = new double[other.nx];
std::copy(other.sx0data, other.sx0data + other.nx * other.nplist, sx0data);
}
ordering = other.ordering;
newton_precon = other.newton_precon;
ism = other.ism;
}
int UserData::unscaleParameters(double *bufferUnscaled) const {
/**
* unscaleParameters removes parameter scaling according to the parameter
* scaling in pscale
*
* @param[out] bufferUnscaled unscaled parameters are written to the array
* @type double
*
* @return status flag indicating success of execution @type int
*/
switch (pscale) {
case AMICI_SCALING_LOG10:
for (int ip = 0; ip < np; ++ip) {
bufferUnscaled[ip] = pow(10, p[ip]);
}
break;
case AMICI_SCALING_LN:
for (int ip = 0; ip < np; ++ip)
bufferUnscaled[ip] = exp(p[ip]);
break;
case AMICI_SCALING_NONE:
for (int ip = 0; ip < np; ++ip)
bufferUnscaled[ip] = p[ip];
break;
}
return AMICI_SUCCESS;
}
void UserData::setTimepoints(const double *timepoints, int numTimepoints) {
if (ts) {
delete[] ts;
}
nt = numTimepoints;
ts = new double[nt];
memcpy(ts, timepoints, sizeof(double) * nt);
}
void UserData::setParameters(const double *parameters) {
if (p) {
delete[] p;
}
p = new double[np];
memcpy(p, parameters, sizeof(double) * np);
}
void UserData::setConstants(const double *constants) {
if (k) {
delete[] k;
}
k = new double[nk];
memcpy(k, constants, sizeof(double) * nk);
}
void UserData::setPlist(const double *plist, int nplist) {
if (this->plist) {
delete[] this->plist;
}
this->nplist = nplist;
this->plist = new int[nplist];
for (int ip = 0; ip < nplist; ip++) {
this->plist[ip] = (int)plist[ip];
}
}
void UserData::setPlist(const int *plist, int nplist) {
if (this->plist) {
delete[] this->plist;
}
this->nplist = nplist;
this->plist = new int[nplist];
memcpy(this->plist, plist, sizeof(int) * nplist);
}
void UserData::requireSensitivitiesForAllParameters()
{
nplist = np;
plist = new int[nplist];
for (int i = 0; i < nplist; ++i)
plist[i] = i;
}
void UserData::setPbar(const double *parameterScaling) {
if (pbar) {
delete[] pbar;
}
if(parameterScaling) {
pbar = new double[nplist];
memcpy(pbar, parameterScaling, sizeof(double) * nplist);
} else {
pbar = nullptr;
}
}
void UserData::setStateInitialization(const double *stateInitialization) {
if (x0data) {
delete[] x0data;
}
if(stateInitialization) {
x0data = new double[nx];
memcpy(x0data, stateInitialization, sizeof(double) * nx);
} else {
x0data = nullptr;
}
}
void UserData::setSensitivityInitialization(
const double *sensitivityInitialization) {
if (sx0data) {
delete[] sx0data;
}
if(sensitivityInitialization) {
sx0data = new double[nx * nplist];
memcpy(sx0data, sensitivityInitialization, sizeof(double) * nx * nplist);
} else {
sx0data = nullptr;
}
}
UserData::~UserData() {
if (qpositivex)
delete[] qpositivex;
if (p)
delete[] p;
if (k)
delete[] k;
if (ts)
delete[] ts;
if (pbar)
delete[] pbar;
if (xbar)
delete[] xbar;
if (x0data)
delete[] x0data;
if (sx0data)
delete[] sx0data;
if (plist)
delete[] plist;
}
void UserData::print() const {
printf("qpositivex: %p\n", qpositivex);
printf("plist: %p\n", plist);
printf("nplist: %d\n", nplist);
printf("nt: %d\n", nt);
printf("nmaxevent: %d\n", nmaxevent);
printf("p: %p\n", p);
printf("k: %p\n", k);
printf("tstart: %e\n", tstart);
printf("ts: %p\n", ts);
printf("pbar: %p\n", pbar);
printf("xbar: %p\n", xbar);
printf("sensi: %d\n", sensi);
printf("atol: %e\n", atol);
printf("rtol: %e\n", rtol);
printf("maxsteps: %d\n", maxsteps);
printf("newton_maxsteps: %d\n", newton_maxsteps);
printf("newton_maxlinsteps: %d\n", newton_maxlinsteps);
printf("ism: %d\n", ism);
printf("sensi_meth: %d\n", sensi_meth);
printf("linsol: %d\n", linsol);
printf("interpType: %d\n", interpType);
printf("lmm: %d\n", lmm);
printf("iter: %d\n", iter);
printf("stldet: %d\n", stldet);
printf("x0data: %p\n", x0data);
printf("sx0data: %p\n", sx0data);
printf("ordering: %d\n", ordering);
}
} // namespace amici
<|endoftext|> |
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <solver/solver.hh>
#include <graph/graph.hh>
#include <graph/file_formats.hh>
#include <graph/power.hh>
#include <graph/complement.hh>
#include <graph/is_clique.hh>
#include <graph/is_club.hh>
#include <graph/orders.hh>
#include <max_clique/algorithms.hh>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <exception>
#include <cstdlib>
#include <chrono>
#include <thread>
using namespace parasols;
namespace po = boost::program_options;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
namespace
{
auto run_with_power(MaxCliqueResult func(const Graph &, const MaxCliqueParams &)) ->
std::function<MaxCliqueResult (const Graph &, MaxCliqueParams &, bool &, int)>
{
return run_this_wrapped<MaxCliqueResult, MaxCliqueParams, Graph>(
[func] (const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult {
if (params.power > 1) {
auto power_start_time = steady_clock::now();
auto power_graph = power(graph, params.power);
auto power_time = duration_cast<milliseconds>(steady_clock::now() - power_start_time);
auto result = func(power_graph, params);
result.times.insert(next(result.times.begin()), power_time);
return result;
}
else
return func(graph, params);
});
}
}
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
("threads", po::value<int>(), "Number of threads to use (where relevant)")
("stop-after-finding", po::value<int>(), "Stop after finding a clique of this size")
("initial-bound", po::value<int>(), "Specify an initial bound")
("enumerate", "Enumerate solutions (use with bmcsa1 --initial-bound=omega-1 --print-incumbents)")
("print-incumbents", "Print new incumbents as they are found")
("split-depth", po::value<int>(), "Specify the depth at which to perform splitting (where relevant)")
("work-donation", "Enable work donation (where relevant)")
("timeout", po::value<int>(), "Abort after this many seconds")
("complement", "Take the complement of the graph (to solve independent set)")
("power", po::value<int>(), "Raise the graph to this power (to solve s-clique)")
("verify", "Verify that we have found a valid result (for sanity checking changes)")
("check-club", "Check whether our s-clique is also an s-club")
("format", po::value<std::string>(), "Specify the format of the input")
;
po::options_description all_options{ "All options" };
all_options.add_options()
("algorithm", "Specify which algorithm to use")
("order", "Specify the initial vertex order")
("input-file", po::value<std::vector<std::string> >(),
"Specify the input file (DIMACS format, unless --format is specified). May be specified multiple times.")
;
all_options.add(display_options);
po::positional_options_description positional_options;
positional_options
.add("algorithm", 1)
.add("order", 1)
.add("input-file", -1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] algorithm order file[...]" << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No algorithm or no input file specified? Show a message and exit. */
if (! options_vars.count("algorithm") || options_vars.count("input-file") < 1) {
std::cout << "Usage: " << argv[0] << " [options] algorithm order file[...]" << std::endl;
return EXIT_FAILURE;
}
/* Turn an algorithm string name into a runnable function. */
auto algorithm = max_clique_algorithms.begin(), algorithm_end = max_clique_algorithms.end();
for ( ; algorithm != algorithm_end ; ++algorithm)
if (std::get<0>(*algorithm) == options_vars["algorithm"].as<std::string>())
break;
/* Unknown algorithm? Show a message and exit. */
if (algorithm == algorithm_end) {
std::cerr << "Unknown algorithm " << options_vars["algorithm"].as<std::string>() << ", choose from:";
for (auto a : max_clique_algorithms)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* Turn an order string name into a runnable function. */
MaxCliqueOrderFunction order_function;
for (auto order = orders.begin() ; order != orders.end() ; ++order)
if (std::get<0>(*order) == options_vars["order"].as<std::string>()) {
order_function = std::get<1>(*order);
break;
}
/* Unknown algorithm? Show a message and exit. */
if (! order_function) {
std::cerr << "Unknown order " << options_vars["order"].as<std::string>() << ", choose from:";
for (auto a : orders)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* For each input file... */
auto input_files = options_vars["input-file"].as<std::vector<std::string> >();
bool first = true;
for (auto & input_file : input_files) {
if (first)
first = false;
else
std::cout << "--" << std::endl;
/* Figure out what our options should be. */
MaxCliqueParams params;
params.order_function = order_function;
if (options_vars.count("threads"))
params.n_threads = options_vars["threads"].as<int>();
else
params.n_threads = std::thread::hardware_concurrency();
if (options_vars.count("stop-after-finding"))
params.stop_after_finding = options_vars["stop-after-finding"].as<int>();
if (options_vars.count("initial-bound"))
params.initial_bound = options_vars["initial-bound"].as<int>();
if (options_vars.count("enumerate"))
params.enumerate = true;
if (options_vars.count("print-incumbents"))
params.print_incumbents = true;
if (options_vars.count("check-club"))
params.check_clubs = true;
if (options_vars.count("split-depth"))
params.split_depth = options_vars["split-depth"].as<int>();
if (options_vars.count("work-donation"))
params.work_donation = true;
if (options_vars.count("power"))
params.power = options_vars["power"].as<int>();
/* Turn a format name into a runnable function. */
auto format = graph_file_formats.begin(), format_end = graph_file_formats.end();
if (options_vars.count("format"))
for ( ; format != format_end ; ++format)
if (format->first == options_vars["format"].as<std::string>())
break;
/* Unknown format? Show a message and exit. */
if (format == format_end) {
std::cerr << "Unknown format " << options_vars["format"].as<std::string>() << ", choose from:";
for (auto a : graph_file_formats)
std::cerr << " " << a.first;
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* Read in the graph */
auto graph = std::get<1>(*format)(input_file);
if (options_vars.count("complement")) {
graph = complement(graph); // don't time this
params.complement = true;
}
params.original_graph = &graph;
/* Do the actual run. */
bool aborted = false;
auto result = run_with_power(std::get<1>(*algorithm))(
graph,
params,
aborted,
options_vars.count("timeout") ? options_vars["timeout"].as<int>() : 0);
/* Stop the clock. */
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
/* Display the results. */
std::cout << result.size << " " << result.nodes;
if (options_vars.count("enumerate")) {
std::cout << " " << result.result_count;
if (options_vars.count("check-club"))
std::cout << " " << result.result_club_count;
}
if (aborted)
std::cout << " aborted";
std::cout << std::endl;
/* Members, and whether it's a club. */
for (auto v : result.members)
std::cout << graph.vertex_name(v) << " ";
if (options_vars.count("check-club")) {
if (is_club(graph, params.power, std::vector<int>{ result.members.begin(), result.members.end() }))
std::cout << "(club)" << std::endl;
else
std::cout << "(not club)" << std::endl;
}
std::cout << std::endl;
/* Times */
std::cout << overall_time.count();
if (! result.times.empty()) {
for (auto t : result.times)
std::cout << " " << t.count();
}
std::cout << std::endl;
/* Donation */
if (params.work_donation)
std::cout << result.donations << std::endl;
if (options_vars.count("verify")) {
if (params.power > 1) {
if (! is_clique(power(graph, params.power), result.members)) {
std::cerr << "Oops! not a clique" << std::endl;
return EXIT_FAILURE;
}
}
else {
if (! is_clique(graph, result.members)) {
std::cerr << "Oops! not a clique" << std::endl;
return EXIT_FAILURE;
}
}
}
}
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>Put the preprocessing time in a better place<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <solver/solver.hh>
#include <graph/graph.hh>
#include <graph/file_formats.hh>
#include <graph/power.hh>
#include <graph/complement.hh>
#include <graph/is_clique.hh>
#include <graph/is_club.hh>
#include <graph/orders.hh>
#include <max_clique/algorithms.hh>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <exception>
#include <cstdlib>
#include <chrono>
#include <thread>
using namespace parasols;
namespace po = boost::program_options;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
namespace
{
auto run_with_power(MaxCliqueResult func(const Graph &, const MaxCliqueParams &)) ->
std::function<MaxCliqueResult (const Graph &, MaxCliqueParams &, bool &, int)>
{
return run_this_wrapped<MaxCliqueResult, MaxCliqueParams, Graph>(
[func] (const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult {
if (params.power > 1) {
auto power_start_time = steady_clock::now();
auto power_graph = power(graph, params.power);
auto power_time = duration_cast<milliseconds>(steady_clock::now() - power_start_time);
auto result = func(power_graph, params);
result.times.insert(result.times.begin(), power_time);
return result;
}
else
return func(graph, params);
});
}
}
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
("threads", po::value<int>(), "Number of threads to use (where relevant)")
("stop-after-finding", po::value<int>(), "Stop after finding a clique of this size")
("initial-bound", po::value<int>(), "Specify an initial bound")
("enumerate", "Enumerate solutions (use with bmcsa1 --initial-bound=omega-1 --print-incumbents)")
("print-incumbents", "Print new incumbents as they are found")
("split-depth", po::value<int>(), "Specify the depth at which to perform splitting (where relevant)")
("work-donation", "Enable work donation (where relevant)")
("timeout", po::value<int>(), "Abort after this many seconds")
("complement", "Take the complement of the graph (to solve independent set)")
("power", po::value<int>(), "Raise the graph to this power (to solve s-clique)")
("verify", "Verify that we have found a valid result (for sanity checking changes)")
("check-club", "Check whether our s-clique is also an s-club")
("format", po::value<std::string>(), "Specify the format of the input")
;
po::options_description all_options{ "All options" };
all_options.add_options()
("algorithm", "Specify which algorithm to use")
("order", "Specify the initial vertex order")
("input-file", po::value<std::vector<std::string> >(),
"Specify the input file (DIMACS format, unless --format is specified). May be specified multiple times.")
;
all_options.add(display_options);
po::positional_options_description positional_options;
positional_options
.add("algorithm", 1)
.add("order", 1)
.add("input-file", -1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] algorithm order file[...]" << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No algorithm or no input file specified? Show a message and exit. */
if (! options_vars.count("algorithm") || options_vars.count("input-file") < 1) {
std::cout << "Usage: " << argv[0] << " [options] algorithm order file[...]" << std::endl;
return EXIT_FAILURE;
}
/* Turn an algorithm string name into a runnable function. */
auto algorithm = max_clique_algorithms.begin(), algorithm_end = max_clique_algorithms.end();
for ( ; algorithm != algorithm_end ; ++algorithm)
if (std::get<0>(*algorithm) == options_vars["algorithm"].as<std::string>())
break;
/* Unknown algorithm? Show a message and exit. */
if (algorithm == algorithm_end) {
std::cerr << "Unknown algorithm " << options_vars["algorithm"].as<std::string>() << ", choose from:";
for (auto a : max_clique_algorithms)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* Turn an order string name into a runnable function. */
MaxCliqueOrderFunction order_function;
for (auto order = orders.begin() ; order != orders.end() ; ++order)
if (std::get<0>(*order) == options_vars["order"].as<std::string>()) {
order_function = std::get<1>(*order);
break;
}
/* Unknown algorithm? Show a message and exit. */
if (! order_function) {
std::cerr << "Unknown order " << options_vars["order"].as<std::string>() << ", choose from:";
for (auto a : orders)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* For each input file... */
auto input_files = options_vars["input-file"].as<std::vector<std::string> >();
bool first = true;
for (auto & input_file : input_files) {
if (first)
first = false;
else
std::cout << "--" << std::endl;
/* Figure out what our options should be. */
MaxCliqueParams params;
params.order_function = order_function;
if (options_vars.count("threads"))
params.n_threads = options_vars["threads"].as<int>();
else
params.n_threads = std::thread::hardware_concurrency();
if (options_vars.count("stop-after-finding"))
params.stop_after_finding = options_vars["stop-after-finding"].as<int>();
if (options_vars.count("initial-bound"))
params.initial_bound = options_vars["initial-bound"].as<int>();
if (options_vars.count("enumerate"))
params.enumerate = true;
if (options_vars.count("print-incumbents"))
params.print_incumbents = true;
if (options_vars.count("check-club"))
params.check_clubs = true;
if (options_vars.count("split-depth"))
params.split_depth = options_vars["split-depth"].as<int>();
if (options_vars.count("work-donation"))
params.work_donation = true;
if (options_vars.count("power"))
params.power = options_vars["power"].as<int>();
/* Turn a format name into a runnable function. */
auto format = graph_file_formats.begin(), format_end = graph_file_formats.end();
if (options_vars.count("format"))
for ( ; format != format_end ; ++format)
if (format->first == options_vars["format"].as<std::string>())
break;
/* Unknown format? Show a message and exit. */
if (format == format_end) {
std::cerr << "Unknown format " << options_vars["format"].as<std::string>() << ", choose from:";
for (auto a : graph_file_formats)
std::cerr << " " << a.first;
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* Read in the graph */
auto graph = std::get<1>(*format)(input_file);
if (options_vars.count("complement")) {
graph = complement(graph); // don't time this
params.complement = true;
}
params.original_graph = &graph;
/* Do the actual run. */
bool aborted = false;
auto result = run_with_power(std::get<1>(*algorithm))(
graph,
params,
aborted,
options_vars.count("timeout") ? options_vars["timeout"].as<int>() : 0);
/* Stop the clock. */
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
/* Display the results. */
std::cout << result.size << " " << result.nodes;
if (options_vars.count("enumerate")) {
std::cout << " " << result.result_count;
if (options_vars.count("check-club"))
std::cout << " " << result.result_club_count;
}
if (aborted)
std::cout << " aborted";
std::cout << std::endl;
/* Members, and whether it's a club. */
for (auto v : result.members)
std::cout << graph.vertex_name(v) << " ";
if (options_vars.count("check-club")) {
if (is_club(graph, params.power, std::vector<int>{ result.members.begin(), result.members.end() }))
std::cout << "(club)" << std::endl;
else
std::cout << "(not club)" << std::endl;
}
std::cout << std::endl;
/* Times */
std::cout << overall_time.count();
if (! result.times.empty()) {
for (auto t : result.times)
std::cout << " " << t.count();
}
std::cout << std::endl;
/* Donation */
if (params.work_donation)
std::cout << result.donations << std::endl;
if (options_vars.count("verify")) {
if (params.power > 1) {
if (! is_clique(power(graph, params.power), result.members)) {
std::cerr << "Oops! not a clique" << std::endl;
return EXIT_FAILURE;
}
}
else {
if (! is_clique(graph, result.members)) {
std::cerr << "Oops! not a clique" << std::endl;
return EXIT_FAILURE;
}
}
}
}
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/* * Copyright (c) 2016 Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The names of its contributors may not 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.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by:
* (MA) Mike Avery <averym@uci.edu>
* (MB) Michael Beyeler <mbeyeler@uci.edu>,
* (KDC) Kristofor Carlson <kdcarlso@uci.edu>
* (TSC) Ting-Shuo Chou <tingshuc@uci.edu>
* (HK) Hirak J Kashyap <kashyaph@uci.edu>
*
* CARLsim v1.0: JM, MDR
* CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC
* CARLsim3: MB, KDC, TSC
* CARLsim4: TSC, HK
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
* Ver 12/31/2016
*/
// include CARLsim user interface
#include <carlsim.h>
// include stopwatch for timing
#include <stopwatch.h>
int main() {
// keep track of execution time
Stopwatch watch;
// ---------------- CONFIG STATE -------------------
// create a network on GPU
int numGPUs = 1;
int randSeed = 42;
CARLsim sim("hello world", GPU_MODE, USER, numGPUs, randSeed);
// configure the network
// set up a COBA two-layer network with gaussian connectivity
Grid3D gridIn(13,9,1); // pre is on a 13x9 grid
Grid3D gridOut(3,3,1); // post is on a 3x3 grid
int gin=sim.createSpikeGeneratorGroup("input", gridIn, EXCITATORY_NEURON);
int gout=sim.createGroup("output", gridOut, EXCITATORY_NEURON);
sim.setNeuronParameters(gout, 0.02f, 0.2f, -65.0f, 8.0f);
sim.connect(gin, gout, "gaussian", RangeWeight(0.05), 1.0f, RangeDelay(1), RadiusRF(3,3,1));
sim.setConductances(true);
// sim.setIntegrationMethod(FORWARD_EULER, 2);
// ---------------- SETUP STATE -------------------
// build the network
watch.lap("setupNetwork");
sim.setupNetwork();
// set some monitors
sim.setSpikeMonitor(gin,"DEFAULT");
sim.setSpikeMonitor(gout,"DEFAULT");
sim.setConnectionMonitor(gin,gout,"DEFAULT");
//setup some baseline input
PoissonRate in(gridIn.N);
in.setRates(30.0f);
sim.setSpikeRate(gin,&in);
// ---------------- RUN STATE -------------------
watch.lap("runNetwork");
// run for a total of 10 seconds
// at the end of each runNetwork call, SpikeMonitor stats will be printed
for (int i=0; i<10; i++) {
sim.runNetwork(1,0);
}
// print stopwatch summary
watch.stop();
return 0;
}
<commit_msg>update to hello_world<commit_after>/* * Copyright (c) 2016 Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The names of its contributors may not 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.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by:
* (MA) Mike Avery <averym@uci.edu>
* (MB) Michael Beyeler <mbeyeler@uci.edu>,
* (KDC) Kristofor Carlson <kdcarlso@uci.edu>
* (TSC) Ting-Shuo Chou <tingshuc@uci.edu>
* (HK) Hirak J Kashyap <kashyaph@uci.edu>
*
* CARLsim v1.0: JM, MDR
* CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC
* CARLsim3: MB, KDC, TSC
* CARLsim4: TSC, HK
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
* Ver 12/31/2016
*/
// include CARLsim user interface
#include <carlsim.h>
// include stopwatch for timing
#include <stopwatch.h>
int main() {
// keep track of execution time
Stopwatch watch;
// ---------------- CONFIG STATE -------------------
// create a network on GPU
int numGPUs = 1;
int randSeed = 42;
CARLsim sim("hello world", CPU_MODE, USER, numGPUs, randSeed);
// configure the network
// set up a COBA two-layer network with gaussian connectivity
Grid3D gridIn(13,9,1); // pre is on a 13x9 grid
Grid3D gridOut(3,3,1); // post is on a 3x3 grid
int gin=sim.createSpikeGeneratorGroup("input", gridIn, EXCITATORY_NEURON);
int gout=sim.createGroup("output", gridOut, EXCITATORY_NEURON);
sim.setNeuronParameters(gout, 0.02f, 0.2f, -65.0f, 8.0f);
sim.connect(gin, gout, "gaussian", RangeWeight(0.05), 1.0f, RangeDelay(1), RadiusRF(3,3,1));
sim.setConductances(true);
// sim.setIntegrationMethod(FORWARD_EULER, 2);
// ---------------- SETUP STATE -------------------
// build the network
watch.lap("setupNetwork");
sim.setupNetwork();
// set some monitors
sim.setSpikeMonitor(gin,"DEFAULT");
sim.setSpikeMonitor(gout,"DEFAULT");
sim.setConnectionMonitor(gin,gout,"DEFAULT");
//setup some baseline input
PoissonRate in(gridIn.N);
in.setRates(30.0f);
sim.setSpikeRate(gin,&in);
// ---------------- RUN STATE -------------------
watch.lap("runNetwork");
// run for a total of 10 seconds
// at the end of each runNetwork call, SpikeMonitor stats will be printed
for (int i=0; i<10; i++) {
sim.runNetwork(1,0);
}
// print stopwatch summary
watch.stop();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>
#include "platform.h"
void logMsg(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
std::string stringFromResource(const char* _path) {
std::string into;
std::ifstream file;
std::string buffer;
file.open(_path);
if(!file.is_open()) {
return std::string();
}
while(!file.eof()) {
getline(file, buffer);
into += buffer + "\n";
}
file.close();
return into;
}
unsigned char* bytesFromResource(const char* _path, unsigned int* _size) {
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);
}
<commit_msg>Fix missing symbols for RPi<commit_after>#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>
#include "platform.h"
void logMsg(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
void requestRender() {
// TODO: implement non-continuous rendering on RPi
}
void setContinuousRendering(bool _isContinuous) {
// TODO: implement non-continuous rendering on RPi
}
bool isContinuousRendering() {
// TODO: implement non-continuous rendering on RPi
}
std::string stringFromResource(const char* _path) {
std::string into;
std::ifstream file;
std::string buffer;
file.open(_path);
if(!file.is_open()) {
return std::string();
}
while(!file.eof()) {
getline(file, buffer);
into += buffer + "\n";
}
file.close();
return into;
}
unsigned char* bytesFromResource(const char* _path, unsigned int* _size) {
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);
}
<|endoftext|> |
<commit_before>#include "../cutehmi.metadata.hpp"
#include "../cutehmi.dirs.hpp"
#include "cutehmi/daemon/logging.hpp"
#include "cutehmi/daemon/Daemon.hpp"
#include "cutehmi/daemon/EngineThread.hpp"
#include "cutehmi/daemon/CoreData.hpp"
#include "cutehmi/daemon/Exception.hpp"
#include <cutehmi/CuteHMI.hpp>
#include <cutehmi/Singleton.hpp>
#include <QCoreApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QCommandLineParser>
#include <QUrl>
#include <QTranslator>
#include <QLibraryInfo>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QtGlobal>
using namespace cutehmi::daemon;
/**
* Main function.
* @param argc number of arguments passed to the program.
* @param argv list of arguments passed to the program.
* @return return code.
*/
int main(int argc, char * argv[])
{
//<cutehmi_daemon-silent_initialization.principle>
// Output shall remain silent until daemon logging is set up.
//<Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication.assumption>
// "In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the
// platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application
// should make the QApplication be the first created, and last destroyed QObject."
// Set up application.
QCoreApplication::setOrganizationDomain(QString(CUTEHMI_DAEMON_VENDOR).toLower());
QCoreApplication::setApplicationName(CUTEHMI_DAEMON_VENDOR " " CUTEHMI_DAEMON_FRIENDLY_NAME);
QCoreApplication::setApplicationVersion(QString("%1.%2.%3").arg(CUTEHMI_DAEMON_MAJOR).arg(CUTEHMI_DAEMON_MINOR).arg(CUTEHMI_DAEMON_MICRO));
QCoreApplication app(argc, argv);
// Configure command line parser and process arguments.
QJsonDocument metadataJson;
{
QFile metadataFile(":/" CUTEHMI_DAEMON_NAME "/cutehmi.metadata.json");
if (metadataFile.open(QFile::ReadOnly)) {
metadataJson = QJsonDocument::fromJson(metadataFile.readAll());
} else
CUTEHMI_DIE("Could not open ':/" CUTEHMI_DAEMON_NAME "/cutehmi.metadata.json' file.");
}
QCommandLineParser cmd;
cmd.setApplicationDescription(QCoreApplication::applicationName() + "\n" + metadataJson.object().value("description").toString());
cmd.addHelpOption();
cmd.addVersionOption();
CoreData::Options opt {
QCommandLineOption("app", QCoreApplication::translate("main", "Run project in application mode.")),
QCommandLineOption("basedir", QCoreApplication::translate("main", "Set base directory to <dir>."), QCoreApplication::translate("main", "dir")),
QCommandLineOption("lang", QCoreApplication::translate("main", "Choose application <language>."), QCoreApplication::translate("main", "language")),
QCommandLineOption("pidfile", QCoreApplication::translate("main", "PID file <path> (Unix-specific)."), QCoreApplication::translate("main", "path")),
QCommandLineOption({"p", "project"}, QCoreApplication::translate("main", "Load QML project <URL>."), QCoreApplication::translate("main", "URL"))
};
opt.pidfile.setDefaultValue(QString("/var/run/") + CUTEHMI_DAEMON_NAME ".pid");
opt.pidfile.setDescription(opt.pidfile.description() + "\nDefault value: '" + opt.pidfile.defaultValues().at(0) + "'.");
opt.basedir.setDefaultValue(QDir(QCoreApplication::applicationDirPath() + "/..").canonicalPath());
opt.basedir.setDescription(opt.basedir.description() + "\nDefault value: '" + opt.basedir.defaultValues().at(0) + "'.");
cmd.addOption(opt.app);
cmd.addOption(opt.basedir);
cmd.addOption(opt.lang);
cmd.addOption(opt.pidfile);
cmd.addOption(opt.project);
cmd.process(app);
// Prepare program core.
CoreData data;
data.app = & app;
data.cmd = & cmd;
data.opt = & opt;
std::function<int(CoreData &)> core = [](CoreData & data) {
try {
CUTEHMI_DEBUG("Default locale: " << QLocale());
QTranslator qtTranslator;
if (data.cmd->isSet(data.opt->lang))
qtTranslator.load("qt_" + data.cmd->value(data.opt->lang), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
else
qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
data.app->installTranslator(& qtTranslator);
QDir baseDir = data.cmd->value(data.opt->basedir);
QString baseDirPath = baseDir.absolutePath() + "/";
CUTEHMI_DEBUG("Base directory: " << baseDirPath);
CUTEHMI_DEBUG("Library paths: " << QCoreApplication::libraryPaths());
EngineThread engineThread;
std::unique_ptr<QQmlApplicationEngine> engine(new QQmlApplicationEngine);
engine->addImportPath(baseDirPath + CUTEHMI_DIRS_QML_EXTENSION_INSTALL_DIRNAME);
CUTEHMI_DEBUG("QML import paths: " << engine->importPathList());
if (!data.cmd->value(data.opt->project).isNull()) {
CUTEHMI_DEBUG("Project: " << data.cmd->value(data.opt->project));
QUrl projectUrl(data.cmd->value(data.opt->project));
if (projectUrl.isValid()) {
// Assure that URL is not mixing relative path with explicitly specified scheme, which is forbidden. QUrl::isValid() doesn't check this out.
if (!projectUrl.scheme().isEmpty() && QDir::isRelativePath(projectUrl.path()))
throw Exception(QObject::tr("URL '%1' contains relative path along with URL scheme, which is forbidden.").arg(projectUrl.url()));
else {
// If source URL is relative (does not contain scheme), then make absolute URL: file:///baseDirPath/sourceUrl.
if (projectUrl.isRelative())
projectUrl = QUrl::fromLocalFile(baseDirPath).resolved(projectUrl);
// Check if file exists and eventually set context property.
if (projectUrl.isLocalFile() && !QFile::exists(projectUrl.toLocalFile()))
throw Exception(QObject::tr("Project file '%1' does not exist.").arg(projectUrl.url()));
else {
engine->moveToThread(& engineThread);
QObject::connect(& engineThread, & EngineThread::loadRequested, engine.get(), QOverload<const QString &>::of(& QQmlApplicationEngine::load));
QObject::connect(& engineThread, SIGNAL(loadRequested(const QString &)), & engineThread, SLOT(start()));
QObject::connect(data.app, & QCoreApplication::aboutToQuit, & engineThread, & QThread::quit);
// Delegate management of engine to EngineThread, so that it gets deleted after thread finishes execution.
QObject::connect(& engineThread, & QThread::finished, engine.release(), & QObject::deleteLater);
emit engineThread.loadRequested(projectUrl.url());
int result = data.app->exec();
engineThread.wait();
return result;
}
}
} else
throw Exception(QObject::tr("Invalid format of project URL '%1'.").arg(data.cmd->value(data.opt->project)));
} else
throw Exception(QObject::tr("No project file has been specified."));
return EXIT_SUCCESS;
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
} catch (const cutehmi::Dialogist::NoAdvertiserException & e) {
CUTEHMI_CRITICAL("Dialog message: " << e.dialog()->text());
if (!e.dialog()->informativeText().isEmpty())
CUTEHMI_CRITICAL("Informative text: " << e.dialog()->informativeText());
if (!e.dialog()->detailedText().isEmpty())
CUTEHMI_CRITICAL("Detailed text: " << e.dialog()->detailedText());
CUTEHMI_CRITICAL("Available buttons: " << e.dialog()->buttons());
} catch (const std::exception & e) {
CUTEHMI_CRITICAL(e.what());
} catch (...) {
CUTEHMI_CRITICAL("Caught unrecognized exception.");
throw;
}
return EXIT_FAILURE;
};
// Run program core in daemon or application mode.
int exitCode;
if (!cmd.isSet(opt.app)) {
Daemon daemon(& data, core);
// At this point logging should be configured and printing facilities silenced. Not much to say anyways...
//</cutehmi_daemon-silent_initialization.principle>
exitCode = daemon.exitCode();
} else
exitCode = core(data);
// Destroy singleton instances before QCoreApplication. Ignoring the recommendation to connect clean-up code to the
// aboutToQuit() signal, because for daemon it is always violent termination if QCoreApplication::exec() does not exit.
cutehmi::destroySingletonInstances();
return exitCode;
//</Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication.assumption>
}
//(c)MP: Copyright © 2019, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<commit_msg>Fix header includes.<commit_after>#include "../cutehmi.metadata.hpp"
#include "../cutehmi.dirs.hpp"
#include "cutehmi/daemon/logging.hpp"
#include "cutehmi/daemon/Daemon.hpp"
#include "cutehmi/daemon/EngineThread.hpp"
#include "cutehmi/daemon/CoreData.hpp"
#include "cutehmi/daemon/Exception.hpp"
#include <cutehmi/Dialogist.hpp>
#include <cutehmi/Singleton.hpp>
#include <QCoreApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QCommandLineParser>
#include <QUrl>
#include <QTranslator>
#include <QLibraryInfo>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QtGlobal>
using namespace cutehmi::daemon;
/**
* Main function.
* @param argc number of arguments passed to the program.
* @param argv list of arguments passed to the program.
* @return return code.
*/
int main(int argc, char * argv[])
{
//<cutehmi_daemon-silent_initialization.principle>
// Output shall remain silent until daemon logging is set up.
//<Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication.assumption>
// "In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the
// platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application
// should make the QApplication be the first created, and last destroyed QObject."
// Set up application.
QCoreApplication::setOrganizationDomain(QString(CUTEHMI_DAEMON_VENDOR).toLower());
QCoreApplication::setApplicationName(CUTEHMI_DAEMON_VENDOR " " CUTEHMI_DAEMON_FRIENDLY_NAME);
QCoreApplication::setApplicationVersion(QString("%1.%2.%3").arg(CUTEHMI_DAEMON_MAJOR).arg(CUTEHMI_DAEMON_MINOR).arg(CUTEHMI_DAEMON_MICRO));
QCoreApplication app(argc, argv);
// Configure command line parser and process arguments.
QJsonDocument metadataJson;
{
QFile metadataFile(":/" CUTEHMI_DAEMON_NAME "/cutehmi.metadata.json");
if (metadataFile.open(QFile::ReadOnly)) {
metadataJson = QJsonDocument::fromJson(metadataFile.readAll());
} else
CUTEHMI_DIE("Could not open ':/" CUTEHMI_DAEMON_NAME "/cutehmi.metadata.json' file.");
}
QCommandLineParser cmd;
cmd.setApplicationDescription(QCoreApplication::applicationName() + "\n" + metadataJson.object().value("description").toString());
cmd.addHelpOption();
cmd.addVersionOption();
CoreData::Options opt {
QCommandLineOption("app", QCoreApplication::translate("main", "Run project in application mode.")),
QCommandLineOption("basedir", QCoreApplication::translate("main", "Set base directory to <dir>."), QCoreApplication::translate("main", "dir")),
QCommandLineOption("lang", QCoreApplication::translate("main", "Choose application <language>."), QCoreApplication::translate("main", "language")),
QCommandLineOption("pidfile", QCoreApplication::translate("main", "PID file <path> (Unix-specific)."), QCoreApplication::translate("main", "path")),
QCommandLineOption({"p", "project"}, QCoreApplication::translate("main", "Load QML project <URL>."), QCoreApplication::translate("main", "URL"))
};
opt.pidfile.setDefaultValue(QString("/var/run/") + CUTEHMI_DAEMON_NAME ".pid");
opt.pidfile.setDescription(opt.pidfile.description() + "\nDefault value: '" + opt.pidfile.defaultValues().at(0) + "'.");
opt.basedir.setDefaultValue(QDir(QCoreApplication::applicationDirPath() + "/..").canonicalPath());
opt.basedir.setDescription(opt.basedir.description() + "\nDefault value: '" + opt.basedir.defaultValues().at(0) + "'.");
cmd.addOption(opt.app);
cmd.addOption(opt.basedir);
cmd.addOption(opt.lang);
cmd.addOption(opt.pidfile);
cmd.addOption(opt.project);
cmd.process(app);
// Prepare program core.
CoreData data;
data.app = & app;
data.cmd = & cmd;
data.opt = & opt;
std::function<int(CoreData &)> core = [](CoreData & data) {
try {
CUTEHMI_DEBUG("Default locale: " << QLocale());
QTranslator qtTranslator;
if (data.cmd->isSet(data.opt->lang))
qtTranslator.load("qt_" + data.cmd->value(data.opt->lang), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
else
qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
data.app->installTranslator(& qtTranslator);
QDir baseDir = data.cmd->value(data.opt->basedir);
QString baseDirPath = baseDir.absolutePath() + "/";
CUTEHMI_DEBUG("Base directory: " << baseDirPath);
CUTEHMI_DEBUG("Library paths: " << QCoreApplication::libraryPaths());
EngineThread engineThread;
std::unique_ptr<QQmlApplicationEngine> engine(new QQmlApplicationEngine);
engine->addImportPath(baseDirPath + CUTEHMI_DIRS_QML_EXTENSION_INSTALL_DIRNAME);
CUTEHMI_DEBUG("QML import paths: " << engine->importPathList());
if (!data.cmd->value(data.opt->project).isNull()) {
CUTEHMI_DEBUG("Project: " << data.cmd->value(data.opt->project));
QUrl projectUrl(data.cmd->value(data.opt->project));
if (projectUrl.isValid()) {
// Assure that URL is not mixing relative path with explicitly specified scheme, which is forbidden. QUrl::isValid() doesn't check this out.
if (!projectUrl.scheme().isEmpty() && QDir::isRelativePath(projectUrl.path()))
throw Exception(QObject::tr("URL '%1' contains relative path along with URL scheme, which is forbidden.").arg(projectUrl.url()));
else {
// If source URL is relative (does not contain scheme), then make absolute URL: file:///baseDirPath/sourceUrl.
if (projectUrl.isRelative())
projectUrl = QUrl::fromLocalFile(baseDirPath).resolved(projectUrl);
// Check if file exists and eventually set context property.
if (projectUrl.isLocalFile() && !QFile::exists(projectUrl.toLocalFile()))
throw Exception(QObject::tr("Project file '%1' does not exist.").arg(projectUrl.url()));
else {
engine->moveToThread(& engineThread);
QObject::connect(& engineThread, & EngineThread::loadRequested, engine.get(), QOverload<const QString &>::of(& QQmlApplicationEngine::load));
QObject::connect(& engineThread, SIGNAL(loadRequested(const QString &)), & engineThread, SLOT(start()));
QObject::connect(data.app, & QCoreApplication::aboutToQuit, & engineThread, & QThread::quit);
// Delegate management of engine to EngineThread, so that it gets deleted after thread finishes execution.
QObject::connect(& engineThread, & QThread::finished, engine.release(), & QObject::deleteLater);
emit engineThread.loadRequested(projectUrl.url());
int result = data.app->exec();
engineThread.wait();
return result;
}
}
} else
throw Exception(QObject::tr("Invalid format of project URL '%1'.").arg(data.cmd->value(data.opt->project)));
} else
throw Exception(QObject::tr("No project file has been specified."));
return EXIT_SUCCESS;
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
} catch (const cutehmi::Dialogist::NoAdvertiserException & e) {
CUTEHMI_CRITICAL("Dialog message: " << e.dialog()->text());
if (!e.dialog()->informativeText().isEmpty())
CUTEHMI_CRITICAL("Informative text: " << e.dialog()->informativeText());
if (!e.dialog()->detailedText().isEmpty())
CUTEHMI_CRITICAL("Detailed text: " << e.dialog()->detailedText());
CUTEHMI_CRITICAL("Available buttons: " << e.dialog()->buttons());
} catch (const std::exception & e) {
CUTEHMI_CRITICAL(e.what());
} catch (...) {
CUTEHMI_CRITICAL("Caught unrecognized exception.");
throw;
}
return EXIT_FAILURE;
};
// Run program core in daemon or application mode.
int exitCode;
if (!cmd.isSet(opt.app)) {
Daemon daemon(& data, core);
// At this point logging should be configured and printing facilities silenced. Not much to say anyways...
//</cutehmi_daemon-silent_initialization.principle>
exitCode = daemon.exitCode();
} else
exitCode = core(data);
// Destroy singleton instances before QCoreApplication. Ignoring the recommendation to connect clean-up code to the
// aboutToQuit() signal, because for daemon it is always violent termination if QCoreApplication::exec() does not exit.
cutehmi::destroySingletonInstances();
return exitCode;
//</Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication.assumption>
}
//(c)MP: Copyright © 2019, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<|endoftext|> |
<commit_before>// 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/installer/util/wmi.h"
#include <windows.h>
#include "base/basictypes.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_variant.h"
#pragma comment(lib, "wbemuuid.lib")
namespace installer {
namespace {
// Simple class to manage the lifetime of a variant.
// TODO(tommi): Replace this for a more useful class.
class VariantHelper : public VARIANT {
public:
VariantHelper() {
vt = VT_EMPTY;
}
explicit VariantHelper(VARTYPE type) {
vt = type;
}
~VariantHelper() {
::VariantClear(this);
}
private:
DISALLOW_COPY_AND_ASSIGN(VariantHelper);
};
} // namespace
bool WMI::CreateLocalConnection(bool set_blanket,
IWbemServices** wmi_services) {
base::win::ScopedComPtr<IWbemLocator> wmi_locator;
HRESULT hr = wmi_locator.CreateInstance(CLSID_WbemLocator, NULL,
CLSCTX_INPROC_SERVER);
if (FAILED(hr))
return false;
base::win::ScopedComPtr<IWbemServices> wmi_services_r;
hr = wmi_locator->ConnectServer(base::win::ScopedBstr(L"ROOT\\CIMV2"),
NULL, NULL, 0, NULL, 0, 0,
wmi_services_r.Receive());
if (FAILED(hr))
return false;
if (set_blanket) {
hr = ::CoSetProxyBlanket(wmi_services_r,
RPC_C_AUTHN_WINNT,
RPC_C_AUTHZ_NONE,
NULL,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE);
if (FAILED(hr))
return false;
}
*wmi_services = wmi_services_r.Detach();
return true;
}
bool WMI::CreateClassMethodObject(IWbemServices* wmi_services,
const std::wstring& class_name,
const std::wstring& method_name,
IWbemClassObject** class_instance) {
// We attempt to instantiate a COM object that represents a WMI object plus
// a method rolled into one entity.
base::win::ScopedBstr b_class_name(class_name.c_str());
base::win::ScopedBstr b_method_name(method_name.c_str());
base::win::ScopedComPtr<IWbemClassObject> class_object;
HRESULT hr;
hr = wmi_services->GetObject(b_class_name, 0, NULL,
class_object.Receive(), NULL);
if (FAILED(hr))
return false;
base::win::ScopedComPtr<IWbemClassObject> params_def;
hr = class_object->GetMethod(b_method_name, 0, params_def.Receive(), NULL);
if (FAILED(hr))
return false;
if (NULL == params_def) {
// You hit this special case if the WMI class is not a CIM class. MSDN
// sometimes tells you this. Welcome to WMI hell.
return false;
}
hr = params_def->SpawnInstance(0, class_instance);
return(SUCCEEDED(hr));
}
bool SetParameter(IWbemClassObject* class_method,
const std::wstring& parameter_name, VARIANT* parameter) {
HRESULT hr = class_method->Put(parameter_name.c_str(), 0, parameter, 0);
return SUCCEEDED(hr);
}
// The code in Launch() basically calls the Create Method of the Win32_Process
// CIM class is documented here:
// http://msdn2.microsoft.com/en-us/library/aa389388(VS.85).aspx
bool WMIProcess::Launch(const std::wstring& command_line, int* process_id) {
base::win::ScopedComPtr<IWbemServices> wmi_local;
if (!WMI::CreateLocalConnection(true, wmi_local.Receive()))
return false;
const wchar_t class_name[] = L"Win32_Process";
const wchar_t method_name[] = L"Create";
base::win::ScopedComPtr<IWbemClassObject> process_create;
if (!WMI::CreateClassMethodObject(wmi_local, class_name, method_name,
process_create.Receive()))
return false;
VariantHelper b_command_line(VT_BSTR);
b_command_line.bstrVal = ::SysAllocString(command_line.c_str());
if (!SetParameter(process_create, L"CommandLine", &b_command_line))
return false;
base::win::ScopedComPtr<IWbemClassObject> out_params;
HRESULT hr = wmi_local->ExecMethod(base::win::ScopedBstr(class_name),
base::win::ScopedBstr(method_name),
0, NULL, process_create,
out_params.Receive(), NULL);
if (FAILED(hr))
return false;
VariantHelper ret_value;
hr = out_params->Get(L"ReturnValue", 0, &ret_value, NULL, 0);
if (FAILED(hr) || (0 != ret_value.uintVal))
return false;
VariantHelper pid;
hr = out_params->Get(L"ProcessId", 0, &pid, NULL, 0);
if (FAILED(hr) || (0 == pid.intVal))
return false;
if (process_id)
*process_id = pid.intVal;
return true;
}
string16 WMIComputerSystem::GetModel() {
base::win::ScopedComPtr<IWbemServices> services;
if (!WMI::CreateLocalConnection(true, services.Receive()))
return string16();
base::win::ScopedBstr query_language(L"WQL");
base::win::ScopedBstr query(L"SELECT * FROM Win32_ComputerSystem");
base::win::ScopedComPtr<IEnumWbemClassObject> enumerator;
HRESULT hr = services->ExecQuery(
query_language, query,
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL,
enumerator.Receive());
if (FAILED(hr) || !enumerator)
return string16();
base::win::ScopedComPtr<IWbemClassObject> class_object;
ULONG items_returned = 0;
hr = enumerator->Next(WBEM_INFINITE, 1, class_object.Receive(),
&items_returned);
if (!items_returned)
return string16();
base::win::ScopedVariant manufacturer;
class_object->Get(L"Manufacturer", 0, manufacturer.Receive(), 0, 0);
base::win::ScopedVariant model;
class_object->Get(L"Model", 0, model.Receive(), 0, 0);
string16 model_string;
if (manufacturer.type() == VT_BSTR) {
model_string = V_BSTR(&manufacturer);
if (model.type() == VT_BSTR)
model_string += L" ";
}
if (model.type() == VT_BSTR)
model_string += V_BSTR(&model);
return model_string;
}
} // namespace installer
<commit_msg>Take care of an old todo: Use ScopedVariant instead of VariantHelper.<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/installer/util/wmi.h"
#include <windows.h>
#include "base/basictypes.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_variant.h"
#pragma comment(lib, "wbemuuid.lib")
using base::win::ScopedVariant;
namespace installer {
bool WMI::CreateLocalConnection(bool set_blanket,
IWbemServices** wmi_services) {
base::win::ScopedComPtr<IWbemLocator> wmi_locator;
HRESULT hr = wmi_locator.CreateInstance(CLSID_WbemLocator, NULL,
CLSCTX_INPROC_SERVER);
if (FAILED(hr))
return false;
base::win::ScopedComPtr<IWbemServices> wmi_services_r;
hr = wmi_locator->ConnectServer(base::win::ScopedBstr(L"ROOT\\CIMV2"),
NULL, NULL, 0, NULL, 0, 0,
wmi_services_r.Receive());
if (FAILED(hr))
return false;
if (set_blanket) {
hr = ::CoSetProxyBlanket(wmi_services_r,
RPC_C_AUTHN_WINNT,
RPC_C_AUTHZ_NONE,
NULL,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE);
if (FAILED(hr))
return false;
}
*wmi_services = wmi_services_r.Detach();
return true;
}
bool WMI::CreateClassMethodObject(IWbemServices* wmi_services,
const std::wstring& class_name,
const std::wstring& method_name,
IWbemClassObject** class_instance) {
// We attempt to instantiate a COM object that represents a WMI object plus
// a method rolled into one entity.
base::win::ScopedBstr b_class_name(class_name.c_str());
base::win::ScopedBstr b_method_name(method_name.c_str());
base::win::ScopedComPtr<IWbemClassObject> class_object;
HRESULT hr;
hr = wmi_services->GetObject(b_class_name, 0, NULL,
class_object.Receive(), NULL);
if (FAILED(hr))
return false;
base::win::ScopedComPtr<IWbemClassObject> params_def;
hr = class_object->GetMethod(b_method_name, 0, params_def.Receive(), NULL);
if (FAILED(hr))
return false;
if (NULL == params_def) {
// You hit this special case if the WMI class is not a CIM class. MSDN
// sometimes tells you this. Welcome to WMI hell.
return false;
}
hr = params_def->SpawnInstance(0, class_instance);
return(SUCCEEDED(hr));
}
bool SetParameter(IWbemClassObject* class_method,
const std::wstring& parameter_name, VARIANT* parameter) {
HRESULT hr = class_method->Put(parameter_name.c_str(), 0, parameter, 0);
return SUCCEEDED(hr);
}
// The code in Launch() basically calls the Create Method of the Win32_Process
// CIM class is documented here:
// http://msdn2.microsoft.com/en-us/library/aa389388(VS.85).aspx
// NOTE: The documentation for the Create method suggests that the ProcessId
// parameter and return value are of type uint32, but when we call the method
// the values in the returned out_params, are VT_I4, which is int32.
bool WMIProcess::Launch(const std::wstring& command_line, int* process_id) {
base::win::ScopedComPtr<IWbemServices> wmi_local;
if (!WMI::CreateLocalConnection(true, wmi_local.Receive()))
return false;
const wchar_t class_name[] = L"Win32_Process";
const wchar_t method_name[] = L"Create";
base::win::ScopedComPtr<IWbemClassObject> process_create;
if (!WMI::CreateClassMethodObject(wmi_local, class_name, method_name,
process_create.Receive()))
return false;
ScopedVariant b_command_line(command_line.c_str());
if (!SetParameter(process_create, L"CommandLine", b_command_line.AsInput()))
return false;
base::win::ScopedComPtr<IWbemClassObject> out_params;
HRESULT hr = wmi_local->ExecMethod(base::win::ScopedBstr(class_name),
base::win::ScopedBstr(method_name),
0, NULL, process_create,
out_params.Receive(), NULL);
if (FAILED(hr))
return false;
// We're only expecting int32 or uint32 values, so no need for ScopedVariant.
VARIANT ret_value = {VT_EMPTY};
hr = out_params->Get(L"ReturnValue", 0, &ret_value, NULL, 0);
if (FAILED(hr) || 0 != V_I4(&ret_value))
return false;
VARIANT pid = {VT_EMPTY};
hr = out_params->Get(L"ProcessId", 0, &pid, NULL, 0);
if (FAILED(hr) || 0 == V_I4(&pid))
return false;
if (process_id)
*process_id = V_I4(&pid);
return true;
}
string16 WMIComputerSystem::GetModel() {
base::win::ScopedComPtr<IWbemServices> services;
if (!WMI::CreateLocalConnection(true, services.Receive()))
return string16();
base::win::ScopedBstr query_language(L"WQL");
base::win::ScopedBstr query(L"SELECT * FROM Win32_ComputerSystem");
base::win::ScopedComPtr<IEnumWbemClassObject> enumerator;
HRESULT hr = services->ExecQuery(
query_language, query,
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL,
enumerator.Receive());
if (FAILED(hr) || !enumerator)
return string16();
base::win::ScopedComPtr<IWbemClassObject> class_object;
ULONG items_returned = 0;
hr = enumerator->Next(WBEM_INFINITE, 1, class_object.Receive(),
&items_returned);
if (!items_returned)
return string16();
base::win::ScopedVariant manufacturer;
class_object->Get(L"Manufacturer", 0, manufacturer.Receive(), 0, 0);
base::win::ScopedVariant model;
class_object->Get(L"Model", 0, model.Receive(), 0, 0);
string16 model_string;
if (manufacturer.type() == VT_BSTR) {
model_string = V_BSTR(&manufacturer);
if (model.type() == VT_BSTR)
model_string += L" ";
}
if (model.type() == VT_BSTR)
model_string += V_BSTR(&model);
return model_string;
}
} // namespace installer
<|endoftext|> |
<commit_before><commit_msg>implemented double return values (d)<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/module_utils.h"
#include <aclapi.h>
#include <atlbase.h>
#include <atlsecurity.h>
#include <sddl.h>
#include "base/file_path.h"
#include "base/file_version_info.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/shared_memory.h"
#include "base/sys_info.h"
#include "base/utf_string_conversions.h"
#include "base/version.h"
#include "chrome_frame/utils.h"
const wchar_t kSharedMemoryName[] = L"ChromeFrameVersionBeacon_";
const uint32 kSharedMemorySize = 128;
const uint32 kSharedMemoryLockTimeoutMs = 1000;
// static
DllRedirector::DllRedirector() : first_module_handle_(NULL) {
// TODO(robertshield): Allow for overrides to be taken from the environment.
std::wstring beacon_name(kSharedMemoryName);
beacon_name += GetHostProcessName(false);
shared_memory_.reset(new base::SharedMemory(beacon_name));
}
DllRedirector::DllRedirector(const char* shared_memory_name)
: shared_memory_name_(shared_memory_name), first_module_handle_(NULL) {
shared_memory_.reset(new base::SharedMemory(ASCIIToWide(shared_memory_name)));
}
DllRedirector::~DllRedirector() {
if (first_module_handle_) {
if (first_module_handle_ != reinterpret_cast<HMODULE>(&__ImageBase)) {
FreeLibrary(first_module_handle_);
}
first_module_handle_ = NULL;
}
UnregisterAsFirstCFModule();
}
bool DllRedirector::BuildSecurityAttributesForLock(
CSecurityAttributes* sec_attr) {
DCHECK(sec_attr);
int32 major_version, minor_version, fix_version;
base::SysInfo::OperatingSystemVersionNumbers(&major_version,
&minor_version,
&fix_version);
if (major_version < 6) {
// Don't bother with changing ACLs on pre-vista.
return false;
}
bool success = false;
// Fill out the rest of the security descriptor from the process token.
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSecurityDesc security_desc;
// Set the SACL from an SDDL string that allows access to low-integrity
// processes. See http://msdn.microsoft.com/en-us/library/bb625958.aspx.
if (security_desc.FromString(L"S:(ML;;NW;;;LW)")) {
CSid sid_owner;
if (token.GetOwner(&sid_owner)) {
security_desc.SetOwner(sid_owner);
} else {
NOTREACHED() << "Could not get owner.";
}
CSid sid_group;
if (token.GetPrimaryGroup(&sid_group)) {
security_desc.SetGroup(sid_group);
} else {
NOTREACHED() << "Could not get group.";
}
CDacl dacl;
if (token.GetDefaultDacl(&dacl)) {
// Add an access control entry mask for the current user.
// This is what grants this user access from lower integrity levels.
CSid sid_user;
if (token.GetUser(&sid_user)) {
success = dacl.AddAllowedAce(sid_user, MUTEX_ALL_ACCESS);
security_desc.SetDacl(dacl);
sec_attr->Set(security_desc);
}
}
}
}
return success;
}
bool DllRedirector::SetFileMappingToReadOnly(base::SharedMemoryHandle mapping) {
bool success = false;
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSid sid_user;
if (token.GetUser(&sid_user)) {
CDacl dacl;
dacl.AddAllowedAce(sid_user, STANDARD_RIGHTS_READ | FILE_MAP_READ);
success = AtlSetDacl(mapping, SE_KERNEL_OBJECT, dacl);
}
}
return success;
}
bool DllRedirector::RegisterAsFirstCFModule() {
DCHECK(first_module_handle_ == NULL);
// Build our own file version outside of the lock:
scoped_ptr<Version> our_version(GetCurrentModuleVersion());
// We sadly can't use the autolock here since we want to have a timeout.
// Be careful not to return while holding the lock. Also, attempt to do as
// little as possible while under this lock.
bool lock_acquired = false;
CSecurityAttributes sec_attr;
if (BuildSecurityAttributesForLock(&sec_attr)) {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, &sec_attr);
} else {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
}
if (!lock_acquired) {
// We couldn't get the lock in a reasonable amount of time, so fall
// back to loading our current version. We return true to indicate that the
// caller should not attempt to delegate to an already loaded version.
dll_version_.swap(our_version);
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
return true;
}
bool created_beacon = true;
bool result = shared_memory_->CreateNamed(shared_memory_name_.c_str(),
false, // open_existing
kSharedMemorySize);
if (result) {
// We created the beacon, now we need to mutate the security attributes
// on the shared memory to allow read-only access and let low-integrity
// processes open it.
bool acls_set = SetFileMappingToReadOnly(shared_memory_->handle());
DCHECK(acls_set);
} else {
created_beacon = false;
// We failed to create the shared memory segment, suggesting it may already
// exist: try to create it read-only.
result = shared_memory_->Open(shared_memory_name_.c_str(),
true /* read_only */);
}
if (result) {
// Map in the whole thing.
result = shared_memory_->Map(0);
DCHECK(shared_memory_->memory());
if (result) {
// Either write our own version number or read it in if it was already
// present in the shared memory section.
if (created_beacon) {
dll_version_.swap(our_version);
lstrcpynA(reinterpret_cast<char*>(shared_memory_->memory()),
dll_version_->GetString().c_str(),
std::min(kSharedMemorySize,
dll_version_->GetString().length() + 1));
// Mark ourself as the first module in.
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
} else {
char buffer[kSharedMemorySize] = {0};
memcpy(buffer, shared_memory_->memory(), kSharedMemorySize - 1);
dll_version_.reset(Version::GetVersionFromString(buffer));
if (!dll_version_.get() || dll_version_->Equals(*our_version.get())) {
// If we either couldn't parse a valid version out of the shared
// memory or we did parse a version and it is the same as our own,
// then pretend we're first in to avoid trying to load any other DLLs.
dll_version_.reset(our_version.release());
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
created_beacon = true;
}
}
} else {
NOTREACHED() << "Failed to map in version beacon.";
}
} else {
NOTREACHED() << "Could not create file mapping for version beacon, gle: "
<< ::GetLastError();
}
// Matching Unlock.
shared_memory_->Unlock();
return created_beacon;
}
void DllRedirector::UnregisterAsFirstCFModule() {
if (base::SharedMemory::IsHandleValid(shared_memory_->handle())) {
bool lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
if (lock_acquired) {
// Free our handles. The last closed handle SHOULD result in it being
// deleted.
shared_memory_->Close();
shared_memory_->Unlock();
}
}
}
LPFNGETCLASSOBJECT DllRedirector::GetDllGetClassObjectPtr() {
HMODULE first_module_handle = GetFirstModule();
LPFNGETCLASSOBJECT proc_ptr = reinterpret_cast<LPFNGETCLASSOBJECT>(
GetProcAddress(first_module_handle, "DllGetClassObject"));
if (!proc_ptr) {
DPLOG(ERROR) << "DllRedirector: Could not get address of DllGetClassObject "
"from first loaded module.";
// Oh boink, the first module we loaded was somehow bogus, make ourselves
// the first module again.
first_module_handle = reinterpret_cast<HMODULE>(&__ImageBase);
}
return proc_ptr;
}
Version* DllRedirector::GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> file_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
DCHECK(file_version_info.get());
Version* current_version = NULL;
if (file_version_info.get()) {
current_version = Version::GetVersionFromString(
file_version_info->file_version());
DCHECK(current_version);
}
return current_version;
}
HMODULE DllRedirector::GetFirstModule() {
DCHECK(dll_version_.get())
<< "Error: Did you call RegisterAsFirstCFModule() first?";
if (first_module_handle_ == NULL) {
first_module_handle_ = LoadVersionedModule(dll_version_.get());
if (!first_module_handle_) {
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
}
}
return first_module_handle_;
}
HMODULE DllRedirector::LoadVersionedModule(Version* version) {
DCHECK(version);
FilePath module_path;
PathService::Get(base::DIR_MODULE, &module_path);
DCHECK(!module_path.empty());
FilePath module_name = module_path.BaseName();
module_path = module_path.DirName()
.Append(ASCIIToWide(version->GetString()))
.Append(module_name);
HMODULE hmodule = LoadLibrary(module_path.value().c_str());
if (hmodule == NULL) {
DPLOG(ERROR) << "Could not load reported module version "
<< version->GetString();
}
return hmodule;
}
<commit_msg>Remove a DCHECK when failing to secure the shared memory used to hold the current version. This may well fail on older (read non-NTFS) systems since you can't secure file mappings without a securable file system underneath.<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_frame/module_utils.h"
#include <aclapi.h>
#include <atlbase.h>
#include <atlsecurity.h>
#include <sddl.h>
#include "base/file_path.h"
#include "base/file_version_info.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/shared_memory.h"
#include "base/sys_info.h"
#include "base/utf_string_conversions.h"
#include "base/version.h"
#include "chrome_frame/utils.h"
const wchar_t kSharedMemoryName[] = L"ChromeFrameVersionBeacon_";
const uint32 kSharedMemorySize = 128;
const uint32 kSharedMemoryLockTimeoutMs = 1000;
// static
DllRedirector::DllRedirector() : first_module_handle_(NULL) {
// TODO(robertshield): Allow for overrides to be taken from the environment.
std::wstring beacon_name(kSharedMemoryName);
beacon_name += GetHostProcessName(false);
shared_memory_.reset(new base::SharedMemory(beacon_name));
}
DllRedirector::DllRedirector(const char* shared_memory_name)
: shared_memory_name_(shared_memory_name), first_module_handle_(NULL) {
shared_memory_.reset(new base::SharedMemory(ASCIIToWide(shared_memory_name)));
}
DllRedirector::~DllRedirector() {
if (first_module_handle_) {
if (first_module_handle_ != reinterpret_cast<HMODULE>(&__ImageBase)) {
FreeLibrary(first_module_handle_);
}
first_module_handle_ = NULL;
}
UnregisterAsFirstCFModule();
}
bool DllRedirector::BuildSecurityAttributesForLock(
CSecurityAttributes* sec_attr) {
DCHECK(sec_attr);
int32 major_version, minor_version, fix_version;
base::SysInfo::OperatingSystemVersionNumbers(&major_version,
&minor_version,
&fix_version);
if (major_version < 6) {
// Don't bother with changing ACLs on pre-vista.
return false;
}
bool success = false;
// Fill out the rest of the security descriptor from the process token.
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSecurityDesc security_desc;
// Set the SACL from an SDDL string that allows access to low-integrity
// processes. See http://msdn.microsoft.com/en-us/library/bb625958.aspx.
if (security_desc.FromString(L"S:(ML;;NW;;;LW)")) {
CSid sid_owner;
if (token.GetOwner(&sid_owner)) {
security_desc.SetOwner(sid_owner);
} else {
NOTREACHED() << "Could not get owner.";
}
CSid sid_group;
if (token.GetPrimaryGroup(&sid_group)) {
security_desc.SetGroup(sid_group);
} else {
NOTREACHED() << "Could not get group.";
}
CDacl dacl;
if (token.GetDefaultDacl(&dacl)) {
// Add an access control entry mask for the current user.
// This is what grants this user access from lower integrity levels.
CSid sid_user;
if (token.GetUser(&sid_user)) {
success = dacl.AddAllowedAce(sid_user, MUTEX_ALL_ACCESS);
security_desc.SetDacl(dacl);
sec_attr->Set(security_desc);
}
}
}
}
return success;
}
bool DllRedirector::SetFileMappingToReadOnly(base::SharedMemoryHandle mapping) {
bool success = false;
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSid sid_user;
if (token.GetUser(&sid_user)) {
CDacl dacl;
dacl.AddAllowedAce(sid_user, STANDARD_RIGHTS_READ | FILE_MAP_READ);
success = AtlSetDacl(mapping, SE_KERNEL_OBJECT, dacl);
}
}
return success;
}
bool DllRedirector::RegisterAsFirstCFModule() {
DCHECK(first_module_handle_ == NULL);
// Build our own file version outside of the lock:
scoped_ptr<Version> our_version(GetCurrentModuleVersion());
// We sadly can't use the autolock here since we want to have a timeout.
// Be careful not to return while holding the lock. Also, attempt to do as
// little as possible while under this lock.
bool lock_acquired = false;
CSecurityAttributes sec_attr;
if (BuildSecurityAttributesForLock(&sec_attr)) {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, &sec_attr);
} else {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
}
if (!lock_acquired) {
// We couldn't get the lock in a reasonable amount of time, so fall
// back to loading our current version. We return true to indicate that the
// caller should not attempt to delegate to an already loaded version.
dll_version_.swap(our_version);
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
return true;
}
bool created_beacon = true;
bool result = shared_memory_->CreateNamed(shared_memory_name_.c_str(),
false, // open_existing
kSharedMemorySize);
if (result) {
// We created the beacon, now we need to mutate the security attributes
// on the shared memory to allow read-only access and let low-integrity
// processes open it. This will fail on FAT32 file systems.
if (!SetFileMappingToReadOnly(shared_memory_->handle())) {
DLOG(ERROR) << "Failed to set file mapping permissions.";
}
} else {
created_beacon = false;
// We failed to create the shared memory segment, suggesting it may already
// exist: try to create it read-only.
result = shared_memory_->Open(shared_memory_name_.c_str(),
true /* read_only */);
}
if (result) {
// Map in the whole thing.
result = shared_memory_->Map(0);
DCHECK(shared_memory_->memory());
if (result) {
// Either write our own version number or read it in if it was already
// present in the shared memory section.
if (created_beacon) {
dll_version_.swap(our_version);
lstrcpynA(reinterpret_cast<char*>(shared_memory_->memory()),
dll_version_->GetString().c_str(),
std::min(kSharedMemorySize,
dll_version_->GetString().length() + 1));
// Mark ourself as the first module in.
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
} else {
char buffer[kSharedMemorySize] = {0};
memcpy(buffer, shared_memory_->memory(), kSharedMemorySize - 1);
dll_version_.reset(Version::GetVersionFromString(buffer));
if (!dll_version_.get() || dll_version_->Equals(*our_version.get())) {
// If we either couldn't parse a valid version out of the shared
// memory or we did parse a version and it is the same as our own,
// then pretend we're first in to avoid trying to load any other DLLs.
dll_version_.reset(our_version.release());
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
created_beacon = true;
}
}
} else {
NOTREACHED() << "Failed to map in version beacon.";
}
} else {
NOTREACHED() << "Could not create file mapping for version beacon, gle: "
<< ::GetLastError();
}
// Matching Unlock.
shared_memory_->Unlock();
return created_beacon;
}
void DllRedirector::UnregisterAsFirstCFModule() {
if (base::SharedMemory::IsHandleValid(shared_memory_->handle())) {
bool lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
if (lock_acquired) {
// Free our handles. The last closed handle SHOULD result in it being
// deleted.
shared_memory_->Close();
shared_memory_->Unlock();
}
}
}
LPFNGETCLASSOBJECT DllRedirector::GetDllGetClassObjectPtr() {
HMODULE first_module_handle = GetFirstModule();
LPFNGETCLASSOBJECT proc_ptr = reinterpret_cast<LPFNGETCLASSOBJECT>(
GetProcAddress(first_module_handle, "DllGetClassObject"));
if (!proc_ptr) {
DPLOG(ERROR) << "DllRedirector: Could not get address of DllGetClassObject "
"from first loaded module.";
// Oh boink, the first module we loaded was somehow bogus, make ourselves
// the first module again.
first_module_handle = reinterpret_cast<HMODULE>(&__ImageBase);
}
return proc_ptr;
}
Version* DllRedirector::GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> file_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
DCHECK(file_version_info.get());
Version* current_version = NULL;
if (file_version_info.get()) {
current_version = Version::GetVersionFromString(
file_version_info->file_version());
DCHECK(current_version);
}
return current_version;
}
HMODULE DllRedirector::GetFirstModule() {
DCHECK(dll_version_.get())
<< "Error: Did you call RegisterAsFirstCFModule() first?";
if (first_module_handle_ == NULL) {
first_module_handle_ = LoadVersionedModule(dll_version_.get());
if (!first_module_handle_) {
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
}
}
return first_module_handle_;
}
HMODULE DllRedirector::LoadVersionedModule(Version* version) {
DCHECK(version);
FilePath module_path;
PathService::Get(base::DIR_MODULE, &module_path);
DCHECK(!module_path.empty());
FilePath module_name = module_path.BaseName();
module_path = module_path.DirName()
.Append(ASCIIToWide(version->GetString()))
.Append(module_name);
HMODULE hmodule = LoadLibrary(module_path.value().c_str());
if (hmodule == NULL) {
DPLOG(ERROR) << "Could not load reported module version "
<< version->GetString();
}
return hmodule;
}
<|endoftext|> |
<commit_before>/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "utils.h"
#include "consts.h"
#include "terminal.h"
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <QtWebKitWidgets/QWebFrame>
static QString findScript(const QString& jsFilePath, const QString& libraryPath)
{
if (!jsFilePath.isEmpty()) {
QFile jsFile;
// Is file in the PWD?
jsFile.setFileName(QDir::fromNativeSeparators(jsFilePath)); //< Normalise User-provided path
if (!jsFile.exists()) {
// File is not in the PWD. Is it in the lookup directory?
jsFile.setFileName(libraryPath + '/' + QDir::fromNativeSeparators(jsFilePath));
}
return jsFile.fileName();
}
return QString();
}
static QString jsFromScriptFile(const QString& scriptPath, const QString& scriptLanguage, const Encoding& enc)
{
QFile jsFile(scriptPath);
if (jsFile.exists() && jsFile.open(QFile::ReadOnly)) {
QString scriptBody = enc.decode(jsFile.readAll());
jsFile.close();
// Remove CLI script heading
if (scriptBody.startsWith("#!")) {
int len = scriptBody.indexOf(QRegExp("[\r\n]"));
if (len == -1) { len = scriptBody.length(); }
scriptBody.remove(0, len);
}
// If a language is specified and is not "javascript", reject it.
if (scriptLanguage != "javascript" && !scriptLanguage.isNull()) {
QString errMessage = QString("Unsupported language: %1").arg(scriptLanguage);
Terminal::instance()->cerr(errMessage);
qWarning("%s", qPrintable(errMessage));
return QString();
}
return scriptBody;
} else {
return QString();
}
}
namespace Utils
{
bool printDebugMessages = false;
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Q_UNUSED(context);
QDateTime now = QDateTime::currentDateTime();
switch (type) {
case QtDebugMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [DEBUG] %s\n", qPrintable(now.toString(Qt::ISODate)), qPrintable(msg));
}
break;
case QtWarningMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [WARNING] %s\n", qPrintable(now.toString(Qt::ISODate)), qPrintable(msg));
}
break;
case QtCriticalMsg:
fprintf(stderr, "%s [CRITICAL] %s\n", qPrintable(now.toString(Qt::ISODate)), qPrintable(msg));
break;
case QtFatalMsg:
fprintf(stderr, "%s [FATAL] %s\n", qPrintable(now.toString(Qt::ISODate)), qPrintable(msg));
abort();
}
}
bool injectJsInFrame(const QString& jsFilePath, const QString& libraryPath, QWebFrame* targetFrame, const bool startingScript)
{
return injectJsInFrame(jsFilePath, QString(), Encoding::UTF8, libraryPath, targetFrame, startingScript);
}
bool injectJsInFrame(const QString& jsFilePath, const QString& jsFileLanguage, const Encoding& jsFileEnc, const QString& libraryPath, QWebFrame* targetFrame, const bool startingScript)
{
// Don't do anything if an empty string is passed
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileLanguage, jsFileEnc);
if (scriptBody.isEmpty()) {
if (startingScript) {
Terminal::instance()->cerr(QString("Can't open '%1'").arg(jsFilePath));
} else {
qWarning("Can't open '%s'", qPrintable(jsFilePath));
}
return false;
}
// Execute JS code in the context of the document
targetFrame->evaluateJavaScript(scriptBody, QString(JAVASCRIPT_SOURCE_CODE_URL).arg(QFileInfo(scriptPath).fileName()));
return true;
}
bool loadJSForDebug(const QString& jsFilePath, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
return loadJSForDebug(jsFilePath, QString(), Encoding::UTF8, libraryPath, targetFrame, autorun);
}
bool loadJSForDebug(const QString& jsFilePath, const QString& jsFileLanguage, const Encoding& jsFileEnc, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileLanguage, jsFileEnc);
scriptBody = QString("function __run() {\n%1\n}").arg(scriptBody);
targetFrame->evaluateJavaScript(scriptBody, QString(JAVASCRIPT_SOURCE_CODE_URL).arg(QFileInfo(scriptPath).fileName()));
if (autorun) {
targetFrame->evaluateJavaScript("__run()", QString());
}
return true;
}
QString readResourceFileUtf8(const QString& resourceFilePath)
{
QFile f(resourceFilePath);
f.open(QFile::ReadOnly); //< It's OK to assume this succeed. If it doesn't, we have a bigger problem.
return QString::fromUtf8(f.readAll());
}
}; // namespace Utils
<commit_msg>Handle QtInfoMsg<commit_after>/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "utils.h"
#include "consts.h"
#include "terminal.h"
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <QtWebKitWidgets/QWebFrame>
static QString findScript(const QString& jsFilePath, const QString& libraryPath)
{
if (!jsFilePath.isEmpty()) {
QFile jsFile;
// Is file in the PWD?
jsFile.setFileName(QDir::fromNativeSeparators(jsFilePath)); //< Normalise User-provided path
if (!jsFile.exists()) {
// File is not in the PWD. Is it in the lookup directory?
jsFile.setFileName(libraryPath + '/' + QDir::fromNativeSeparators(jsFilePath));
}
return jsFile.fileName();
}
return QString();
}
static QString jsFromScriptFile(const QString& scriptPath, const QString& scriptLanguage, const Encoding& enc)
{
QFile jsFile(scriptPath);
if (jsFile.exists() && jsFile.open(QFile::ReadOnly)) {
QString scriptBody = enc.decode(jsFile.readAll());
jsFile.close();
// Remove CLI script heading
if (scriptBody.startsWith("#!")) {
int len = scriptBody.indexOf(QRegExp("[\r\n]"));
if (len == -1) { len = scriptBody.length(); }
scriptBody.remove(0, len);
}
// If a language is specified and is not "javascript", reject it.
if (scriptLanguage != "javascript" && !scriptLanguage.isNull()) {
QString errMessage = QString("Unsupported language: %1").arg(scriptLanguage);
Terminal::instance()->cerr(errMessage);
qWarning("%s", qPrintable(errMessage));
return QString();
}
return scriptBody;
} else {
return QString();
}
}
namespace Utils
{
bool printDebugMessages = false;
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Q_UNUSED(context);
QString now = QDateTime::currentDateTime().toString(Qt::ISODate);
switch (type) {
case QtInfoMsg:
fprintf(stderr, "%s [INFO] %s\n", qPrintable(now), qPrintable(msg));
break;
case QtDebugMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [DEBUG] %s\n", qPrintable(now), qPrintable(msg));
}
break;
case QtWarningMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [WARNING] %s\n", qPrintable(now), qPrintable(msg));
}
break;
case QtCriticalMsg:
fprintf(stderr, "%s [CRITICAL] %s\n", qPrintable(now), qPrintable(msg));
break;
case QtFatalMsg:
fprintf(stderr, "%s [FATAL] %s\n", qPrintable(now), qPrintable(msg));
abort();
}
}
bool injectJsInFrame(const QString& jsFilePath, const QString& libraryPath, QWebFrame* targetFrame, const bool startingScript)
{
return injectJsInFrame(jsFilePath, QString(), Encoding::UTF8, libraryPath, targetFrame, startingScript);
}
bool injectJsInFrame(const QString& jsFilePath, const QString& jsFileLanguage, const Encoding& jsFileEnc, const QString& libraryPath, QWebFrame* targetFrame, const bool startingScript)
{
// Don't do anything if an empty string is passed
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileLanguage, jsFileEnc);
if (scriptBody.isEmpty()) {
if (startingScript) {
Terminal::instance()->cerr(QString("Can't open '%1'").arg(jsFilePath));
} else {
qWarning("Can't open '%s'", qPrintable(jsFilePath));
}
return false;
}
// Execute JS code in the context of the document
targetFrame->evaluateJavaScript(scriptBody, QString(JAVASCRIPT_SOURCE_CODE_URL).arg(QFileInfo(scriptPath).fileName()));
return true;
}
bool loadJSForDebug(const QString& jsFilePath, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
return loadJSForDebug(jsFilePath, QString(), Encoding::UTF8, libraryPath, targetFrame, autorun);
}
bool loadJSForDebug(const QString& jsFilePath, const QString& jsFileLanguage, const Encoding& jsFileEnc, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileLanguage, jsFileEnc);
scriptBody = QString("function __run() {\n%1\n}").arg(scriptBody);
targetFrame->evaluateJavaScript(scriptBody, QString(JAVASCRIPT_SOURCE_CODE_URL).arg(QFileInfo(scriptPath).fileName()));
if (autorun) {
targetFrame->evaluateJavaScript("__run()", QString());
}
return true;
}
QString readResourceFileUtf8(const QString& resourceFilePath)
{
QFile f(resourceFilePath);
f.open(QFile::ReadOnly); //< It's OK to assume this succeed. If it doesn't, we have a bigger problem.
return QString::fromUtf8(f.readAll());
}
}; // namespace Utils
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2009 Daniël de Kok
*
* 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 "FeatureSelection.ih"
struct GainLess
{
bool operator()(pair<size_t, double> const &f1, pair<size_t, double> const &f2)
{
// Treat NaN as no gain.
double g1 = isnan(f1.second) ? 0.0 : f1.second;
double g2 = isnan(f2.second) ? 0.0 : f2.second;
if (g1 == g2)
return f1.first < f2.first;
return g1 > g2;
}
};
double zf(vector<Event> const &events, vector<double> const &ctxSums, double z,
size_t feature, double alpha);
unordered_map<size_t, double> expFeatureValues(DataSet const &dataSet)
{
unordered_map<size_t, double> expVals;
for (auto fIter = dataSet.features().begin(); fIter != dataSet.features().end();
++fIter)
{
auto expVal = 0.0;
for (auto occIter = fIter->second.begin(); occIter != fIter->second.end();
++occIter)
expVal += occIter->first->prob() * occIter->second->value();
expVals[fIter->first] = expVal;
}
return expVals;
}
unordered_map<size_t, double> expModelFeatureValues(DataSet const &dataSet,
Sums const &sums, Zs const &zs)
{
unordered_map<size_t, double> expVals;
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums.begin(), zIter = zs.begin();
ctxIter != dataSet.contexts().end(); ++ctxIter, ++ctxSumIter, ++zIter)
{
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto pyx = p_yx(*sumIter, *zIter);
for (auto fIter = evtIter->features().begin(); fIter != evtIter->features().end();
++fIter)
expVals[fIter->first] += ctxIter->prob() * pyx * fIter->second.value();
}
}
return expVals;
}
vector<unordered_set<size_t>> contextActiveFeatures(DataSet const &dataSet,
unordered_set<size_t> const &selectedFeatures, Sums const &sums, Zs const &zs)
{
vector<unordered_set<size_t>> ctxActive;
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums.begin(), zIter = zs.begin();
ctxIter != dataSet.contexts().end(); ++ctxIter, ++ctxSumIter, ++zIter)
{
unordered_set<size_t> active;
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto pyx = p_yx(*sumIter, *zIter);
for (auto fIter = evtIter->features().begin();
fIter != evtIter->features().end();
++fIter)
if (selectedFeatures.find(fIter->first) == selectedFeatures.end() &&
active.find(fIter->first) == active.end() &&
fIter->second.value() * pyx * ctxIter->prob() != 0.0)
active.insert(fIter->first);
}
ctxActive.push_back(active);
}
return ctxActive;
}
unordered_set<size_t> activeFeatures(vector<unordered_set<size_t>> const &contextActiveFeatures)
{
unordered_set<size_t> active;
for (auto ctxIter = contextActiveFeatures.begin(); ctxIter != contextActiveFeatures.end();
++ctxIter)
active.insert(ctxIter->begin(), ctxIter->end());
return active;
}
vector<double> initialZs(DataSet const &ds)
{
vector<double> zs;
auto evtFun = mem_fun_ref<vector<Event> const &>(&Context::events);
auto evtSizeFun = mem_fun_ref(&vector<Event>::size);
transform(ds.contexts().begin(), ds.contexts().end(), back_inserter(zs),
compose_f_gx(evtSizeFun, evtFun));
return zs;
}
struct makeSumVector
{
vector<double> operator()(Context const &context) const
{
return vector<double>(context.events().size(), 1.0);
}
};
vector<vector<double>> initialSums(DataSet const &ds)
{
vector<vector<double>> sums;
transform(ds.contexts().begin(), ds.contexts().end(), back_inserter(sums),
makeSumVector());
return sums;
}
unordered_map<size_t, double> r_f(unordered_map<size_t, double> const &expFeatureValues,
unordered_map<size_t, double> const &expModelFeatureValues)
{
unordered_map<size_t, double> r;
for (auto iter = expFeatureValues.begin(); iter != expFeatureValues.end();
++iter)
r[iter->first] = iter->second <=
expModelFeatureValues.find(iter->first)->second ? 1 : -1;
return r;
}
void updateGradients(DataSet const &dataSet,
unordered_set<size_t> const &unconvergedFeatures,
vector<unordered_set<size_t>> const &activeFeatures,
Sums const &sums,
Zs const &zs,
unordered_map<size_t, double> const &alphas,
unordered_map<size_t, double> *gp,
unordered_map<size_t, double> *gpp)
{
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums.begin(), zIter = zs.begin(),
activeFsIter = activeFeatures.begin(); ctxIter != dataSet.contexts().end();
++ctxIter, ++ctxSumIter, ++zIter, ++activeFsIter)
{
for (auto fsIter = activeFsIter->begin(); fsIter != activeFsIter->end();
++fsIter)
{
if (unconvergedFeatures.find(*fsIter) == unconvergedFeatures.end())
continue;
auto newZ = zf(ctxIter->events(), *ctxSumIter, *zIter, *fsIter,
alphas.find(*fsIter)->second);
auto p_fx = 0.0;
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto fVal = 0.0;
auto iter = evtIter->features().find(*fsIter);
if (iter != evtIter->features().end())
fVal = iter->second.value();
auto newSum = *sumIter * exp(alphas.find(*fsIter)->second * fVal);
p_fx += p_yx(newSum, newZ) * fVal;
}
auto gppSum = 0.0;
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto fVal = 0.0;
auto iter = evtIter->features().find(*fsIter);
if (iter != evtIter->features().end())
fVal = iter->second.value();
auto newSum = *sumIter * exp(alphas.find(*fsIter)->second * fVal);
gppSum += p_yx(newSum, newZ) * (fVal * fVal - fVal * p_fx);
}
(*gp)[*fsIter] = (*gp)[*fsIter] - ctxIter->prob() * p_fx;
(*gpp)[*fsIter] = (*gpp)[*fsIter] - ctxIter->prob() * gppSum;
}
}
}
unordered_set<size_t> updateAlphas(unordered_set<size_t> const &unconvergedFeatures,
unordered_map<size_t, double> const &r,
unordered_map<size_t, double> const &gp,
unordered_map<size_t, double> const &gpp,
unordered_map<size_t, double> *alphas,
double alphaThreshold)
{
unordered_set<size_t> newUnconvergedFs = unconvergedFeatures;
for (auto fIter = unconvergedFeatures.begin(); fIter != unconvergedFeatures.end();
++fIter)
{
size_t f = *fIter;
double rF = r.find(f)->second;
auto newAlpha = (*alphas)[f] + rF * log(1 - rF * (gp.find(f)->second / gpp.find(f)->second));
auto delta = abs((*alphas)[f] - newAlpha);
(*alphas)[f] = newAlpha;
if (delta < alphaThreshold || isnan(delta))
newUnconvergedFs.erase(f);
}
return newUnconvergedFs;
}
unordered_map<size_t, double> a_f(DataSet const &dataSet)
{
unordered_map<size_t, double> a;
for (auto iter = dataSet.features().begin(); iter != dataSet.features().end();
++iter)
a[iter->first] = 0.0;
return a;
}
set<pair<size_t, double>, GainLess> calcGains(DataSet const &dataSet,
vector<unordered_set<size_t>> const &contextActiveFeatures,
unordered_map<size_t, double> const &expFeatureValues,
unordered_map<size_t, double> const &alphas,
vector<vector<double>> const &sums,
vector<double> const &zs)
{
unordered_map<size_t, double> gainSum;
for (auto ctxIter = dataSet.contexts().begin(), fsIter = contextActiveFeatures.begin(),
ctxSumIter = sums.begin(), zIter = zs.begin(); ctxIter != dataSet.contexts().end();
++ctxIter, ++fsIter, ++ctxSumIter, ++zIter)
{
for (auto alphaIter = alphas.begin(); alphaIter != alphas.end();
++alphaIter)
{
auto newZ = zf(ctxIter->events(), *ctxSumIter, *zIter, alphaIter->first,
alphaIter->second);
auto lg = ctxIter->prob() * log(newZ / *zIter);
gainSum[alphaIter->first] -= lg;
}
}
set<pair<size_t, double>, GainLess> gains;
for (auto alphaIter = alphas.begin(); alphaIter != alphas.end();
++alphaIter)
gains.insert(make_pair(alphaIter->first,
gainSum[alphaIter->first] + alphaIter->second *
expFeatureValues.find(alphaIter->first)->second
));
return gains;
}
void adjustModel(DataSet const &dataSet, size_t feature, double alpha,
vector<vector<double>> *sums, vector<double> *zs)
{
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums->begin(), zIter = zs->begin();
ctxIter != dataSet.contexts().end(); ++ctxIter, ++ctxSumIter, ++zIter)
{
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto fIter = evtIter->features().find(feature);
if (fIter != evtIter->features().end())
{
*zIter -= *sumIter;
*sumIter *= exp(alpha * fIter->second.value());
*zIter += *sumIter;
}
}
}
}
void fullSelectionStage(DataSet const &dataSet,
double alphaThreshold,
unordered_map<size_t, double> const &expVals,
vector<double> *zs,
vector<vector<double>> *sums,
unordered_set<size_t> *selectedFeatures,
SelectedFeatureAlphas *selectedFeatureAlphas)
{
auto expModelVals = expModelFeatureValues(dataSet, *sums, *zs);
auto ctxActiveFs = contextActiveFeatures(dataSet, *selectedFeatures, *sums, *zs);
auto unconvergedFs = activeFeatures(ctxActiveFs);
auto r = r_f(expVals, expModelVals);
auto a = a_f(dataSet);
while (unconvergedFs.size() != 0)
{
auto gp = expVals;
auto gpp = a_f(dataSet);
updateGradients(dataSet, unconvergedFs, ctxActiveFs, *sums, *zs, a, &gp, &gpp);
unconvergedFs = updateAlphas(unconvergedFs, r, gp, gpp, &a, alphaThreshold);
}
auto gains = calcGains(dataSet, ctxActiveFs, expVals, a, *sums, *zs);
size_t maxF = gains.begin()->first;
auto maxGain = gains.begin()->second;
auto maxAlpha = a[maxF];
adjustModel(dataSet, maxF, maxAlpha, sums, zs);
selectedFeatures->insert(maxF);
selectedFeatureAlphas->push_back(makeTriple(maxF, maxAlpha, maxGain));
}
SelectedFeatureAlphas fsqueeze::featureSelection(DataSet const &dataSet,
double alphaThreshold, double gainThreshold, size_t nFeatures)
{
unordered_set<size_t> selectedFeatures;
SelectedFeatureAlphas selectedFeatureAlphas;
auto zs = initialZs(dataSet);
auto sums = initialSums(dataSet);
auto expVals = expFeatureValues(dataSet);
while(selectedFeatures.size() < nFeatures)
{
fullSelectionStage(dataSet, alphaThreshold, expVals, &zs, &sums,
&selectedFeatures, &selectedFeatureAlphas);
if (selectedFeatureAlphas.back().third < gainThreshold)
{
selectedFeatureAlphas.pop_back();
break;
}
}
return selectedFeatureAlphas;
}
double zf(vector<Event> const &events, vector<double> const &ctxSums, double z,
size_t feature, double alpha)
{
auto newZ = z;
for (auto evtIter = events.begin(), sumIter = ctxSums.begin();
evtIter != events.end(); ++evtIter, ++sumIter)
{
auto iter = evtIter->features().find(feature);
if (iter != evtIter->features().end())
newZ = newZ - *sumIter + *sumIter * exp(alpha * iter->second.value());
}
return newZ;
}
<commit_msg>a_f: only build a map of features we are interested in.<commit_after>/*
* Copyright (c) 2009 Daniël de Kok
*
* 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 "FeatureSelection.ih"
struct GainLess
{
bool operator()(pair<size_t, double> const &f1, pair<size_t, double> const &f2)
{
// Treat NaN as no gain.
double g1 = isnan(f1.second) ? 0.0 : f1.second;
double g2 = isnan(f2.second) ? 0.0 : f2.second;
if (g1 == g2)
return f1.first < f2.first;
return g1 > g2;
}
};
double zf(vector<Event> const &events, vector<double> const &ctxSums, double z,
size_t feature, double alpha);
unordered_map<size_t, double> expFeatureValues(DataSet const &dataSet)
{
unordered_map<size_t, double> expVals;
for (auto fIter = dataSet.features().begin(); fIter != dataSet.features().end();
++fIter)
{
auto expVal = 0.0;
for (auto occIter = fIter->second.begin(); occIter != fIter->second.end();
++occIter)
expVal += occIter->first->prob() * occIter->second->value();
expVals[fIter->first] = expVal;
}
return expVals;
}
unordered_map<size_t, double> expModelFeatureValues(DataSet const &dataSet,
Sums const &sums, Zs const &zs)
{
unordered_map<size_t, double> expVals;
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums.begin(), zIter = zs.begin();
ctxIter != dataSet.contexts().end(); ++ctxIter, ++ctxSumIter, ++zIter)
{
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto pyx = p_yx(*sumIter, *zIter);
for (auto fIter = evtIter->features().begin(); fIter != evtIter->features().end();
++fIter)
expVals[fIter->first] += ctxIter->prob() * pyx * fIter->second.value();
}
}
return expVals;
}
vector<unordered_set<size_t>> contextActiveFeatures(DataSet const &dataSet,
unordered_set<size_t> const &selectedFeatures, Sums const &sums, Zs const &zs)
{
vector<unordered_set<size_t>> ctxActive;
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums.begin(), zIter = zs.begin();
ctxIter != dataSet.contexts().end(); ++ctxIter, ++ctxSumIter, ++zIter)
{
unordered_set<size_t> active;
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto pyx = p_yx(*sumIter, *zIter);
for (auto fIter = evtIter->features().begin();
fIter != evtIter->features().end();
++fIter)
if (selectedFeatures.find(fIter->first) == selectedFeatures.end() &&
active.find(fIter->first) == active.end() &&
fIter->second.value() * pyx * ctxIter->prob() != 0.0)
active.insert(fIter->first);
}
ctxActive.push_back(active);
}
return ctxActive;
}
unordered_set<size_t> activeFeatures(vector<unordered_set<size_t>> const &contextActiveFeatures)
{
unordered_set<size_t> active;
for (auto ctxIter = contextActiveFeatures.begin(); ctxIter != contextActiveFeatures.end();
++ctxIter)
active.insert(ctxIter->begin(), ctxIter->end());
return active;
}
vector<double> initialZs(DataSet const &ds)
{
vector<double> zs;
auto evtFun = mem_fun_ref<vector<Event> const &>(&Context::events);
auto evtSizeFun = mem_fun_ref(&vector<Event>::size);
transform(ds.contexts().begin(), ds.contexts().end(), back_inserter(zs),
compose_f_gx(evtSizeFun, evtFun));
return zs;
}
struct makeSumVector
{
vector<double> operator()(Context const &context) const
{
return vector<double>(context.events().size(), 1.0);
}
};
vector<vector<double>> initialSums(DataSet const &ds)
{
vector<vector<double>> sums;
transform(ds.contexts().begin(), ds.contexts().end(), back_inserter(sums),
makeSumVector());
return sums;
}
unordered_map<size_t, double> r_f(unordered_map<size_t, double> const &expFeatureValues,
unordered_map<size_t, double> const &expModelFeatureValues)
{
unordered_map<size_t, double> r;
for (auto iter = expFeatureValues.begin(); iter != expFeatureValues.end();
++iter)
r[iter->first] = iter->second <=
expModelFeatureValues.find(iter->first)->second ? 1 : -1;
return r;
}
void updateGradients(DataSet const &dataSet,
unordered_set<size_t> const &unconvergedFeatures,
vector<unordered_set<size_t>> const &activeFeatures,
Sums const &sums,
Zs const &zs,
unordered_map<size_t, double> const &alphas,
unordered_map<size_t, double> *gp,
unordered_map<size_t, double> *gpp)
{
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums.begin(), zIter = zs.begin(),
activeFsIter = activeFeatures.begin(); ctxIter != dataSet.contexts().end();
++ctxIter, ++ctxSumIter, ++zIter, ++activeFsIter)
{
for (auto fsIter = activeFsIter->begin(); fsIter != activeFsIter->end();
++fsIter)
{
if (unconvergedFeatures.find(*fsIter) == unconvergedFeatures.end())
continue;
auto newZ = zf(ctxIter->events(), *ctxSumIter, *zIter, *fsIter,
alphas.find(*fsIter)->second);
auto p_fx = 0.0;
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto fVal = 0.0;
auto iter = evtIter->features().find(*fsIter);
if (iter != evtIter->features().end())
fVal = iter->second.value();
auto newSum = *sumIter * exp(alphas.find(*fsIter)->second * fVal);
p_fx += p_yx(newSum, newZ) * fVal;
}
auto gppSum = 0.0;
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto fVal = 0.0;
auto iter = evtIter->features().find(*fsIter);
if (iter != evtIter->features().end())
fVal = iter->second.value();
auto newSum = *sumIter * exp(alphas.find(*fsIter)->second * fVal);
gppSum += p_yx(newSum, newZ) * (fVal * fVal - fVal * p_fx);
}
(*gp)[*fsIter] = (*gp)[*fsIter] - ctxIter->prob() * p_fx;
(*gpp)[*fsIter] = (*gpp)[*fsIter] - ctxIter->prob() * gppSum;
}
}
}
unordered_set<size_t> updateAlphas(unordered_set<size_t> const &unconvergedFeatures,
unordered_map<size_t, double> const &r,
unordered_map<size_t, double> const &gp,
unordered_map<size_t, double> const &gpp,
unordered_map<size_t, double> *alphas,
double alphaThreshold)
{
unordered_set<size_t> newUnconvergedFs = unconvergedFeatures;
for (auto fIter = unconvergedFeatures.begin(); fIter != unconvergedFeatures.end();
++fIter)
{
size_t f = *fIter;
double rF = r.find(f)->second;
auto newAlpha = (*alphas)[f] + rF * log(1 - rF * (gp.find(f)->second / gpp.find(f)->second));
auto delta = abs((*alphas)[f] - newAlpha);
(*alphas)[f] = newAlpha;
if (delta < alphaThreshold || isnan(delta))
newUnconvergedFs.erase(f);
}
return newUnconvergedFs;
}
unordered_map<size_t, double> a_f(unordered_set<size_t> &features)
{
unordered_map<size_t, double> a;
for (auto iter = features.begin(); iter != features.end();
++iter)
a[*iter] = 0.0;
return a;
}
set<pair<size_t, double>, GainLess> calcGains(DataSet const &dataSet,
vector<unordered_set<size_t>> const &contextActiveFeatures,
unordered_map<size_t, double> const &expFeatureValues,
unordered_map<size_t, double> const &alphas,
vector<vector<double>> const &sums,
vector<double> const &zs)
{
unordered_map<size_t, double> gainSum;
for (auto ctxIter = dataSet.contexts().begin(), fsIter = contextActiveFeatures.begin(),
ctxSumIter = sums.begin(), zIter = zs.begin(); ctxIter != dataSet.contexts().end();
++ctxIter, ++fsIter, ++ctxSumIter, ++zIter)
{
for (auto alphaIter = alphas.begin(); alphaIter != alphas.end();
++alphaIter)
{
auto newZ = zf(ctxIter->events(), *ctxSumIter, *zIter, alphaIter->first,
alphaIter->second);
auto lg = ctxIter->prob() * log(newZ / *zIter);
gainSum[alphaIter->first] -= lg;
}
}
set<pair<size_t, double>, GainLess> gains;
for (auto alphaIter = alphas.begin(); alphaIter != alphas.end();
++alphaIter)
gains.insert(make_pair(alphaIter->first,
gainSum[alphaIter->first] + alphaIter->second *
expFeatureValues.find(alphaIter->first)->second
));
return gains;
}
void adjustModel(DataSet const &dataSet, size_t feature, double alpha,
vector<vector<double>> *sums, vector<double> *zs)
{
for (auto ctxIter = dataSet.contexts().begin(), ctxSumIter = sums->begin(), zIter = zs->begin();
ctxIter != dataSet.contexts().end(); ++ctxIter, ++ctxSumIter, ++zIter)
{
for (auto evtIter = ctxIter->events().begin(), sumIter = ctxSumIter->begin();
evtIter != ctxIter->events().end(); ++evtIter, ++sumIter)
{
auto fIter = evtIter->features().find(feature);
if (fIter != evtIter->features().end())
{
*zIter -= *sumIter;
*sumIter *= exp(alpha * fIter->second.value());
*zIter += *sumIter;
}
}
}
}
void fullSelectionStage(DataSet const &dataSet,
double alphaThreshold,
unordered_map<size_t, double> const &expVals,
vector<double> *zs,
vector<vector<double>> *sums,
unordered_set<size_t> *selectedFeatures,
SelectedFeatureAlphas *selectedFeatureAlphas)
{
auto expModelVals = expModelFeatureValues(dataSet, *sums, *zs);
auto ctxActiveFs = contextActiveFeatures(dataSet, *selectedFeatures, *sums, *zs);
auto unconvergedFs = activeFeatures(ctxActiveFs);
auto r = r_f(expVals, expModelVals);
auto a = a_f(unconvergedFs);
while (unconvergedFs.size() != 0)
{
auto gp = expVals;
auto gpp = a_f(unconvergedFs);
updateGradients(dataSet, unconvergedFs, ctxActiveFs, *sums, *zs, a, &gp, &gpp);
unconvergedFs = updateAlphas(unconvergedFs, r, gp, gpp, &a, alphaThreshold);
}
auto gains = calcGains(dataSet, ctxActiveFs, expVals, a, *sums, *zs);
size_t maxF = gains.begin()->first;
auto maxGain = gains.begin()->second;
auto maxAlpha = a[maxF];
adjustModel(dataSet, maxF, maxAlpha, sums, zs);
selectedFeatures->insert(maxF);
selectedFeatureAlphas->push_back(makeTriple(maxF, maxAlpha, maxGain));
}
SelectedFeatureAlphas fsqueeze::featureSelection(DataSet const &dataSet,
double alphaThreshold, double gainThreshold, size_t nFeatures)
{
unordered_set<size_t> selectedFeatures;
SelectedFeatureAlphas selectedFeatureAlphas;
auto zs = initialZs(dataSet);
auto sums = initialSums(dataSet);
auto expVals = expFeatureValues(dataSet);
while(selectedFeatures.size() < nFeatures)
{
fullSelectionStage(dataSet, alphaThreshold, expVals, &zs, &sums,
&selectedFeatures, &selectedFeatureAlphas);
if (selectedFeatureAlphas.back().third < gainThreshold)
{
selectedFeatureAlphas.pop_back();
break;
}
}
return selectedFeatureAlphas;
}
double zf(vector<Event> const &events, vector<double> const &ctxSums, double z,
size_t feature, double alpha)
{
auto newZ = z;
for (auto evtIter = events.begin(), sumIter = ctxSums.begin();
evtIter != events.end(); ++evtIter, ++sumIter)
{
auto iter = evtIter->features().find(feature);
if (iter != evtIter->features().end())
newZ = newZ - *sumIter + *sumIter * exp(alpha * iter->second.value());
}
return newZ;
}
<|endoftext|> |
<commit_before>#include <memory>
#include <sstream>
#include <queso/Environment.h>
#ifdef QUESO_HAVE_LIBMESH
#include <libmesh/libmesh.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <queso/FunctionOperatorBuilder.h>
#include <queso/LibMeshFunction.h>
#include <queso/LibMeshNegativeLaplacianOperator.h>
#include <queso/InfiniteDimensionalGaussian.h>
#include <queso/InfiniteDimensionalLikelihoodBase.h>
#include <queso/InfiniteDimensionalMCMCSampler.h>
#include <queso/InfiniteDimensionalMCMCSamplerOptions.h>
#endif // QUESO_HAVE_LIBMESH
#include <mpi.h>
#ifdef QUESO_HAVE_LIBMESH
class Likelihood : public QUESO::InfiniteDimensionalLikelihoodBase {
public:
Likelihood();
~Likelihood();
virtual double evaluate(QUESO::FunctionBase &flow);
};
Likelihood::Likelihood()
: QUESO::InfiniteDimensionalLikelihoodBase(1.0)
{
}
Likelihood::~Likelihood() {}
double Likelihood::evaluate(QUESO::FunctionBase &flow)
{
return 1.0;
}
#endif
int main(int argc, char **argv)
{
#ifdef QUESO_HAVE_LIBMESH
const char * in_file_name = "test_infinite/inf_options";
const char * prefix = "";
const unsigned int num_pairs = 5;
const double alpha = 3.0;
const double beta = 1.0;
// EnvOptionsValuesClass opts;
// opts.m_seed = -1;
MPI_Init(&argc, &argv);
QUESO::FullEnvironment env(MPI_COMM_WORLD, in_file_name, prefix, NULL);
#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
// SLEPc farts with libMesh::Real==float
libmesh_example_assert(false, "--disable-singleprecision");
#endif
// Need an artificial block here because libmesh needs to
// call PetscFinalize before we call MPI_Finalize
#ifdef LIBMESH_HAVE_SLEPC
{
libMesh::LibMeshInit init(argc, argv);
libMesh::Mesh mesh(init.comm());
libMesh::MeshTools::Generation::build_square(mesh,
20, 20, 0.0, 1.0, 0.0, 1.0, libMeshEnums::QUAD4);
QUESO::FunctionOperatorBuilder fobuilder;
fobuilder.order = "FIRST";
fobuilder.family = "LAGRANGE";
fobuilder.num_req_eigenpairs = num_pairs;
QUESO::LibMeshFunction mean(fobuilder, mesh);
QUESO::LibMeshNegativeLaplacianOperator precision(fobuilder, mesh);
QUESO::InfiniteDimensionalGaussian mu(env, mean, precision, alpha, beta);
Likelihood llhd;
QUESO::InfiniteDimensionalMCMCSamplerOptions opts(env, "");
QUESO::InfiniteDimensionalMCMCSampler sampler(env, mu, llhd, &opts);
if (opts.m_num_iters != 10 || // Input file value is 10
opts.m_save_freq != 5 || // Ditto 5
opts.m_rwmh_step != 0.1) {
return 1;
}
return 0;
}
#endif // LIBMESH_HAVE_SLEPC
MPI_Finalize();
return 0;
#else
return 77;
#endif
}
<commit_msg>test_inf_options only works with HDF5<commit_after>#include <memory>
#include <sstream>
#include <queso/Environment.h>
#ifdef QUESO_HAVE_LIBMESH
#include <libmesh/libmesh.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <queso/FunctionOperatorBuilder.h>
#include <queso/LibMeshFunction.h>
#include <queso/LibMeshNegativeLaplacianOperator.h>
#include <queso/InfiniteDimensionalGaussian.h>
#include <queso/InfiniteDimensionalLikelihoodBase.h>
#include <queso/InfiniteDimensionalMCMCSampler.h>
#include <queso/InfiniteDimensionalMCMCSamplerOptions.h>
#endif // QUESO_HAVE_LIBMESH
#include <mpi.h>
#ifdef QUESO_HAVE_LIBMESH
class Likelihood : public QUESO::InfiniteDimensionalLikelihoodBase {
public:
Likelihood();
~Likelihood();
virtual double evaluate(QUESO::FunctionBase &flow);
};
Likelihood::Likelihood()
: QUESO::InfiniteDimensionalLikelihoodBase(1.0)
{
}
Likelihood::~Likelihood() {}
double Likelihood::evaluate(QUESO::FunctionBase &flow)
{
return 1.0;
}
#endif
int main(int argc, char **argv)
{
#ifdef QUESO_HAVE_LIBMESH
const char * in_file_name = "test_infinite/inf_options";
const char * prefix = "";
const unsigned int num_pairs = 5;
const double alpha = 3.0;
const double beta = 1.0;
// EnvOptionsValuesClass opts;
// opts.m_seed = -1;
MPI_Init(&argc, &argv);
QUESO::FullEnvironment env(MPI_COMM_WORLD, in_file_name, prefix, NULL);
#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
// SLEPc farts with libMesh::Real==float
libmesh_example_assert(false, "--disable-singleprecision");
#endif
// Need an artificial block here because libmesh needs to
// call PetscFinalize before we call MPI_Finalize
#if defined(LIBMESH_HAVE_SLEPC) && defined(QUESO_HAVE_HDF5)
{
libMesh::LibMeshInit init(argc, argv);
libMesh::Mesh mesh(init.comm());
libMesh::MeshTools::Generation::build_square(mesh,
20, 20, 0.0, 1.0, 0.0, 1.0, libMeshEnums::QUAD4);
QUESO::FunctionOperatorBuilder fobuilder;
fobuilder.order = "FIRST";
fobuilder.family = "LAGRANGE";
fobuilder.num_req_eigenpairs = num_pairs;
QUESO::LibMeshFunction mean(fobuilder, mesh);
QUESO::LibMeshNegativeLaplacianOperator precision(fobuilder, mesh);
QUESO::InfiniteDimensionalGaussian mu(env, mean, precision, alpha, beta);
Likelihood llhd;
QUESO::InfiniteDimensionalMCMCSamplerOptions opts(env, "");
QUESO::InfiniteDimensionalMCMCSampler sampler(env, mu, llhd, &opts);
if (opts.m_num_iters != 10 || // Input file value is 10
opts.m_save_freq != 5 || // Ditto 5
opts.m_rwmh_step != 0.1) {
return 1;
}
return 0;
}
#endif // LIBMESH_HAVE_SLEPC
MPI_Finalize();
return 0;
#else
return 77;
#endif
}
<|endoftext|> |
<commit_before>/*
* libMaia - maiaObject.cpp
* Copyright (c) 2003 Frerich Raabe <raabe@kde.org> and
* Ian Reinhart Geiser <geiseri@kde.org>
* Copyright (c) 2007 Sebastian Wiedenroth <wiedi@frubar.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "maiaObject.h"
MaiaObject::MaiaObject(QObject* parent) : QObject(parent){
QDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
}
QDomElement MaiaObject::toXml(QVariant arg) {
//dummy document
QDomDocument doc;
//value element, we need this in each case
QDomElement tagValue = doc.createElement("value");
switch(arg.type()) {
case QVariant::String: {
QDomElement tagString = doc.createElement("string");
QDomText textString = doc.createTextNode(arg.toString());
tagValue.appendChild(tagString);
tagString.appendChild(textString);
return tagValue;
} case QVariant::Int: {
QDomElement tagInt = doc.createElement("int");
QDomText textInt = doc.createTextNode(QString::number(arg.toInt()));
tagValue.appendChild(tagInt);
tagInt.appendChild(textInt);
return tagValue;
} case QVariant::Double: {
QDomElement tagDouble = doc.createElement("double");
QDomText textDouble = doc.createTextNode(QString::number(arg.toDouble()));
tagValue.appendChild(tagDouble);
tagDouble.appendChild(textDouble);
return tagValue;
} case QVariant::Bool: {
QString textValue = arg.toBool() ? "true" : "false";
QDomElement tag = doc.createElement("boolean");
QDomText text = doc.createTextNode(textValue);
tagValue.appendChild(tag);
tag.appendChild(text);
return tagValue;
} case QVariant::ByteArray: {
QString textValue = arg.toByteArray().toBase64();
QDomElement tag = doc.createElement("base64");
QDomText text = doc.createTextNode(textValue);
tagValue.appendChild(tag);
tag.appendChild(text);
return tagValue;
} case QVariant::DateTime: {
QString textValue = arg.toDateTime().toString("yyyyMMddThh:mm:ss");
QDomElement tag = doc.createElement("datetime.iso8601");
QDomText text = doc.createTextNode(textValue);
tagValue.appendChild(tag);
tag.appendChild(text);
return tagValue;
} case QVariant::List: {
QDomElement tagArray = doc.createElement("array");
QDomElement tagData = doc.createElement("data");
tagArray.appendChild(tagData);
tagValue.appendChild(tagArray);
const QList<QVariant> args = arg.toList();
for(int i = 0; i < args.size(); ++i) {
tagData.appendChild(toXml(args.at(i)));
}
return tagValue;
} case QVariant::Map: {
QDomElement tagStruct = doc.createElement("struct");
QDomElement member;
QDomElement name;
tagValue.appendChild(tagStruct);
QMap<QString, QVariant> map = arg.toMap();
QMapIterator<QString, QVariant> i(map);
while(i.hasNext()) {
i.next();
member = doc.createElement("member");
name = doc.createElement("name");
// (key) -> name -> member -> struct
tagStruct.appendChild(member);
member.appendChild(name);
name.appendChild(doc.createTextNode(i.key()));
// add variables by recursion
member.appendChild(toXml(i.value()));
}
return tagValue;
} default:
qDebug() << "Failed to marshal unknown variant type: " << arg.type() << endl;
}
return QDomElement(); //QString::null;
}
QVariant MaiaObject::fromXml(const QDomElement &elem) {
if(elem.tagName().toLower() != "value") {
return QVariant();
}
// If no type is indicated, the type is string.
if(!elem.firstChild().isElement()) {
return QVariant(elem.text());
}
const QDomElement typeElement = elem.firstChild().toElement();
const QString typeName = typeElement.tagName().toLower();
if(typeName == "string")
return QVariant(typeElement.text());
else if(typeName == "i4" || typeName == "int")
return QVariant(typeElement.text().toInt());
else if(typeName == "double")
return QVariant(typeElement.text().toDouble());
else if (typeName == "boolean") {
if(typeElement.text().toLower() == "true" || typeElement.text() == "1")
return QVariant(true);
else
return QVariant(false);
} else if(typeName == "base64")
return QVariant(QByteArray::fromBase64( typeElement.text().toLatin1()));
else if(typeName == "datetime" || typeName == "datetime.iso8601")
return QVariant(QDateTime::fromString(typeElement.text(), "yyyyMMddThh:mm:ss"));
else if ( typeName == "array" ) {
QList<QVariant> values;
QDomNode valueNode = typeElement.firstChild().firstChild();
while(!valueNode.isNull()) {
values << fromXml(valueNode.toElement());
valueNode = valueNode.nextSibling();
}
return QVariant(values);
}
else if ( typeName == "struct" ) {
QMap<QString, QVariant> map;
QDomNode memberNode = typeElement.firstChild();
while(!memberNode.isNull()) {
const QString key = memberNode.toElement().elementsByTagName("name").item(0).toElement().text();
const QVariant data = fromXml(memberNode.toElement().elementsByTagName("value").item(0).toElement());
map[key] = data;
memberNode = memberNode.nextSibling();
}
return QVariant(map);
} else {
qDebug() << "Cannot demarshal unknown type " << typeElement.tagName().toLower();
}
return QVariant();
}
QString MaiaObject::prepareCall(QString method, QList<QVariant> args) {
QDomDocument doc;
QDomProcessingInstruction header = doc.createProcessingInstruction( "xml", QString("version=\"1.0\" encoding=\"UTF-8\"" ));
doc.appendChild(header);
QDomElement methodCall = doc.createElement("methodCall");
QDomElement methodName = doc.createElement("methodName");
QDomElement params = doc.createElement("params");
QDomElement param;
doc.appendChild(methodCall);
methodCall.appendChild(methodName);
methodName.appendChild(doc.createTextNode(method));
methodCall.appendChild(params);
for(int i = 0; i < args.size(); ++i) {
param = doc.createElement("param");
param.appendChild(toXml(args.at(i)));
params.appendChild(param);
}
return doc.toString();
}
QString MaiaObject::prepareResponse(QVariant arg) {
QDomDocument doc;
QDomProcessingInstruction header = doc.createProcessingInstruction( "xml", QString("version=\"1.0\" encoding=\"UTF-8\"" ));
doc.appendChild(header);
QDomElement methodResponse = doc.createElement("methodResponse");
QDomElement params = doc.createElement("params");
QDomElement param;
doc.appendChild(methodResponse);
methodResponse.appendChild(params);
if(!arg.isNull()) {
param = doc.createElement("param");
param.appendChild(toXml(arg));
params.appendChild(param);
}
return doc.toString();
}
void MaiaObject::parseResponse(QString response, QNetworkReply* reply) {
QDomDocument doc;
QVariant arg;
QString errorMsg;
int errorLine;
int errorColumn;
if(!doc.setContent(response, &errorMsg, &errorLine, &errorColumn)) {
emit fault(-32700, QString("parse error: response not well formed at line %1: %2").arg(errorLine).arg(errorMsg), reply);
delete this;
return;
}
if(doc.documentElement().firstChild().toElement().tagName().toLower() == "params") {
QDomNode paramNode = doc.documentElement().firstChild().firstChild();
if(!paramNode.isNull()) {
arg = fromXml( paramNode.firstChild().toElement() );
}
emit aresponse(arg, reply);
} else if(doc.documentElement().firstChild().toElement().tagName().toLower() == "fault") {
const QVariant errorVariant = fromXml(doc.documentElement().firstChild().firstChild().toElement());
emit fault(errorVariant.toMap() [ "faultCode" ].toInt(),
errorVariant.toMap() [ "faultString" ].toString(),
reply);
} else {
emit fault(-32600,
tr("parse error: invalid xml-rpc. not conforming to spec."),
reply);
}
delete this;
return;
}
<commit_msg>send the correct bool types<commit_after>/*
* libMaia - maiaObject.cpp
* Copyright (c) 2003 Frerich Raabe <raabe@kde.org> and
* Ian Reinhart Geiser <geiseri@kde.org>
* Copyright (c) 2007 Sebastian Wiedenroth <wiedi@frubar.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "maiaObject.h"
MaiaObject::MaiaObject(QObject* parent) : QObject(parent){
QDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
}
QDomElement MaiaObject::toXml(QVariant arg) {
//dummy document
QDomDocument doc;
//value element, we need this in each case
QDomElement tagValue = doc.createElement("value");
switch(arg.type()) {
case QVariant::String: {
QDomElement tagString = doc.createElement("string");
QDomText textString = doc.createTextNode(arg.toString());
tagValue.appendChild(tagString);
tagString.appendChild(textString);
return tagValue;
} case QVariant::Int: {
QDomElement tagInt = doc.createElement("int");
QDomText textInt = doc.createTextNode(QString::number(arg.toInt()));
tagValue.appendChild(tagInt);
tagInt.appendChild(textInt);
return tagValue;
} case QVariant::Double: {
QDomElement tagDouble = doc.createElement("double");
QDomText textDouble = doc.createTextNode(QString::number(arg.toDouble()));
tagValue.appendChild(tagDouble);
tagDouble.appendChild(textDouble);
return tagValue;
} case QVariant::Bool: {
QString textValue = arg.toBool() ? "1" : "0";
QDomElement tag = doc.createElement("boolean");
QDomText text = doc.createTextNode(textValue);
tagValue.appendChild(tag);
tag.appendChild(text);
return tagValue;
} case QVariant::ByteArray: {
QString textValue = arg.toByteArray().toBase64();
QDomElement tag = doc.createElement("base64");
QDomText text = doc.createTextNode(textValue);
tagValue.appendChild(tag);
tag.appendChild(text);
return tagValue;
} case QVariant::DateTime: {
QString textValue = arg.toDateTime().toString("yyyyMMddThh:mm:ss");
QDomElement tag = doc.createElement("datetime.iso8601");
QDomText text = doc.createTextNode(textValue);
tagValue.appendChild(tag);
tag.appendChild(text);
return tagValue;
} case QVariant::List: {
QDomElement tagArray = doc.createElement("array");
QDomElement tagData = doc.createElement("data");
tagArray.appendChild(tagData);
tagValue.appendChild(tagArray);
const QList<QVariant> args = arg.toList();
for(int i = 0; i < args.size(); ++i) {
tagData.appendChild(toXml(args.at(i)));
}
return tagValue;
} case QVariant::Map: {
QDomElement tagStruct = doc.createElement("struct");
QDomElement member;
QDomElement name;
tagValue.appendChild(tagStruct);
QMap<QString, QVariant> map = arg.toMap();
QMapIterator<QString, QVariant> i(map);
while(i.hasNext()) {
i.next();
member = doc.createElement("member");
name = doc.createElement("name");
// (key) -> name -> member -> struct
tagStruct.appendChild(member);
member.appendChild(name);
name.appendChild(doc.createTextNode(i.key()));
// add variables by recursion
member.appendChild(toXml(i.value()));
}
return tagValue;
} default:
qDebug() << "Failed to marshal unknown variant type: " << arg.type() << endl;
}
return QDomElement(); //QString::null;
}
QVariant MaiaObject::fromXml(const QDomElement &elem) {
if(elem.tagName().toLower() != "value") {
return QVariant();
}
// If no type is indicated, the type is string.
if(!elem.firstChild().isElement()) {
return QVariant(elem.text());
}
const QDomElement typeElement = elem.firstChild().toElement();
const QString typeName = typeElement.tagName().toLower();
if(typeName == "string")
return QVariant(typeElement.text());
else if(typeName == "i4" || typeName == "int")
return QVariant(typeElement.text().toInt());
else if(typeName == "double")
return QVariant(typeElement.text().toDouble());
else if (typeName == "boolean") {
if(typeElement.text().toLower() == "true" || typeElement.text() == "1")
return QVariant(true);
else
return QVariant(false);
} else if(typeName == "base64")
return QVariant(QByteArray::fromBase64( typeElement.text().toLatin1()));
else if(typeName == "datetime" || typeName == "datetime.iso8601")
return QVariant(QDateTime::fromString(typeElement.text(), "yyyyMMddThh:mm:ss"));
else if ( typeName == "array" ) {
QList<QVariant> values;
QDomNode valueNode = typeElement.firstChild().firstChild();
while(!valueNode.isNull()) {
values << fromXml(valueNode.toElement());
valueNode = valueNode.nextSibling();
}
return QVariant(values);
}
else if ( typeName == "struct" ) {
QMap<QString, QVariant> map;
QDomNode memberNode = typeElement.firstChild();
while(!memberNode.isNull()) {
const QString key = memberNode.toElement().elementsByTagName("name").item(0).toElement().text();
const QVariant data = fromXml(memberNode.toElement().elementsByTagName("value").item(0).toElement());
map[key] = data;
memberNode = memberNode.nextSibling();
}
return QVariant(map);
} else {
qDebug() << "Cannot demarshal unknown type " << typeElement.tagName().toLower();
}
return QVariant();
}
QString MaiaObject::prepareCall(QString method, QList<QVariant> args) {
QDomDocument doc;
QDomProcessingInstruction header = doc.createProcessingInstruction( "xml", QString("version=\"1.0\" encoding=\"UTF-8\"" ));
doc.appendChild(header);
QDomElement methodCall = doc.createElement("methodCall");
QDomElement methodName = doc.createElement("methodName");
QDomElement params = doc.createElement("params");
QDomElement param;
doc.appendChild(methodCall);
methodCall.appendChild(methodName);
methodName.appendChild(doc.createTextNode(method));
methodCall.appendChild(params);
for(int i = 0; i < args.size(); ++i) {
param = doc.createElement("param");
param.appendChild(toXml(args.at(i)));
params.appendChild(param);
}
return doc.toString();
}
QString MaiaObject::prepareResponse(QVariant arg) {
QDomDocument doc;
QDomProcessingInstruction header = doc.createProcessingInstruction( "xml", QString("version=\"1.0\" encoding=\"UTF-8\"" ));
doc.appendChild(header);
QDomElement methodResponse = doc.createElement("methodResponse");
QDomElement params = doc.createElement("params");
QDomElement param;
doc.appendChild(methodResponse);
methodResponse.appendChild(params);
if(!arg.isNull()) {
param = doc.createElement("param");
param.appendChild(toXml(arg));
params.appendChild(param);
}
return doc.toString();
}
void MaiaObject::parseResponse(QString response, QNetworkReply* reply) {
QDomDocument doc;
QVariant arg;
QString errorMsg;
int errorLine;
int errorColumn;
if(!doc.setContent(response, &errorMsg, &errorLine, &errorColumn)) {
emit fault(-32700, QString("parse error: response not well formed at line %1: %2").arg(errorLine).arg(errorMsg), reply);
delete this;
return;
}
if(doc.documentElement().firstChild().toElement().tagName().toLower() == "params") {
QDomNode paramNode = doc.documentElement().firstChild().firstChild();
if(!paramNode.isNull()) {
arg = fromXml( paramNode.firstChild().toElement() );
}
emit aresponse(arg, reply);
} else if(doc.documentElement().firstChild().toElement().tagName().toLower() == "fault") {
const QVariant errorVariant = fromXml(doc.documentElement().firstChild().firstChild().toElement());
emit fault(errorVariant.toMap() [ "faultCode" ].toInt(),
errorVariant.toMap() [ "faultString" ].toString(),
reply);
} else {
emit fault(-32600,
tr("parse error: invalid xml-rpc. not conforming to spec."),
reply);
}
delete this;
return;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2012-2013 LevelDOWN contributors
* See list at <https://github.com/rvagg/node-leveldown#contributing>
* MIT +no-false-attribs License
* <https://github.com/rvagg/node-leveldown/blob/master/LICENSE>
*/
#include <node.h>
#include <node_buffer.h>
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
#include "leveldown.h"
#include "database.h"
#include "async.h"
#include "database_async.h"
#include "batch.h"
#include "cbatch.h"
#include "iterator.h"
namespace leveldown {
Database::Database (char* location) : location(location) {
db = NULL;
};
Database::~Database () {
if (db != NULL)
delete db;
};
const char* Database::Location() const { return location; }
/* Calls from worker threads, NO V8 HERE *****************************/
leveldb::Status Database::OpenDatabase (
leveldb::Options* options
, std::string location
) {
return leveldb::DB::Open(*options, location, &db);
}
leveldb::Status Database::PutToDatabase (
leveldb::WriteOptions* options
, leveldb::Slice key
, leveldb::Slice value
) {
return db->Put(*options, key, value);
}
leveldb::Status Database::GetFromDatabase (
leveldb::ReadOptions* options
, leveldb::Slice key
, std::string& value
) {
return db->Get(*options, key, &value);
}
leveldb::Status Database::DeleteFromDatabase (
leveldb::WriteOptions* options
, leveldb::Slice key
) {
return db->Delete(*options, key);
}
leveldb::Status Database::WriteBatchToDatabase (
leveldb::WriteOptions* options
, leveldb::WriteBatch* batch
) {
return db->Write(*options, batch);
}
uint64_t Database::ApproximateSizeFromDatabase (const leveldb::Range* range) {
uint64_t size;
db->GetApproximateSizes(range, 1, &size);
return size;
}
leveldb::Iterator* Database::NewIterator (leveldb::ReadOptions* options) {
return db->NewIterator(*options);
}
const leveldb::Snapshot* Database::NewSnapshot () {
return db->GetSnapshot();
}
void Database::ReleaseSnapshot (const leveldb::Snapshot* snapshot) {
return db->ReleaseSnapshot(snapshot);
}
void Database::CloseDatabase () {
delete db;
db = NULL;
}
/* V8 exposed functions *****************************/
v8::Persistent<v8::Function> Database::constructor;
v8::Handle<v8::Value> LevelDOWN (const v8::Arguments& args) {
v8::HandleScope scope;
return scope.Close(Database::NewInstance(args));
}
void Database::Init () {
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(New);
tpl->SetClassName(v8::String::NewSymbol("Database"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("open")
, v8::FunctionTemplate::New(Open)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("close")
, v8::FunctionTemplate::New(Close)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("put")
, v8::FunctionTemplate::New(Put)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("get")
, v8::FunctionTemplate::New(Get)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("del")
, v8::FunctionTemplate::New(Delete)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("batch")
, v8::FunctionTemplate::New(Batch)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("approximateSize")
, v8::FunctionTemplate::New(ApproximateSize)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("iterator")
, v8::FunctionTemplate::New(Iterator)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("write")
, v8::FunctionTemplate::New(Write)->GetFunction()
);
constructor = v8::Persistent<v8::Function>::New(tpl->GetFunction());
}
v8::Handle<v8::Value> Database::New (const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() == 0) {
LD_THROW_RETURN("leveldown() requires at least a location argument")
}
if (!args[0]->IsString()) {
LD_THROW_RETURN("leveldown() requires a location string argument")
}
LD_FROM_V8_STRING(location, v8::Handle<v8::String>::Cast(args[0]))
Database* obj = new Database(location);
obj->Wrap(args.This());
return args.This();
}
v8::Handle<v8::Value> Database::NewInstance (const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Object> instance;
if (args.Length() == 0) {
instance = constructor->NewInstance(0, NULL);
} else {
v8::Handle<v8::Value> argv[] = { args[0] };
instance = constructor->NewInstance(1, argv);
}
return scope.Close(instance);
}
v8::Handle<v8::Value> Database::Open (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(open, 0, 1)
LD_BOOLEAN_OPTION_VALUE_DEFTRUE(optionsObj, createIfMissing)
LD_BOOLEAN_OPTION_VALUE(optionsObj, errorIfExists)
LD_BOOLEAN_OPTION_VALUE(optionsObj, compression)
LD_UINT32_OPTION_VALUE(optionsObj, cacheSize, 8 << 20)
OpenWorker* worker = new OpenWorker(
database
, callback
, createIfMissing
, errorIfExists
, compression
, cacheSize
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Close (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON_ONEARG(close)
CloseWorker* worker = new CloseWorker(database, callback);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Put (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(put, 2, 3)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], key)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[1], value)
v8::Local<v8::Value> keyBufferV = args[0];
v8::Local<v8::Value> valueBufferV = args[1];
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBufferV)
LD_STRING_OR_BUFFER_TO_SLICE(value, valueBufferV)
v8::Persistent<v8::Value> keyBuffer =
v8::Persistent<v8::Value>::New(keyBufferV);
v8::Persistent<v8::Value> valueBuffer =
v8::Persistent<v8::Value>::New(valueBufferV);
LD_BOOLEAN_OPTION_VALUE(optionsObj, sync)
WriteWorker* worker = new WriteWorker(
database
, callback
, key
, value
, sync
, keyBuffer
, valueBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
Handle<Value> Database::Write(const Arguments& args) {
HandleScope scope;
Database* database = ObjectWrap::Unwrap<Database>(args.This());
if (args.Length() < 1) {
ThrowException(Exception::Error(String::New("batch required")));
return scope.Close(Undefined());
}
WriteParams *params = new WriteParams();
params->request.data = params;
params->db = database->db;
params->cb = Persistent<Function>::New(Local<Function>::Cast(args[1]));
params->batch = ObjectWrap::Unwrap<CBatch>(args[0]->ToObject());
uv_queue_work(uv_default_loop(), ¶ms->request, WriteDoing, WriteAfter);
return scope.Close(args.Holder());
}
void Database::WriteDoing (uv_work_t *req) {
WriteParams *params = (WriteParams *)req->data;
leveldb::WriteBatch wb = params->batch->batch;
params->status = params->db->Write(leveldb::WriteOptions(), &wb);
}
void Database::WriteAfter (uv_work_t *req) {
HandleScope scope;
WriteParams *params = (WriteParams *)req->data;
Handle<Value> argv[1];
if (params->status.ok()) {
argv[0] = Local<Value>::New(Undefined());
} else {
argv[0] = Local<Value>::New(String::New(params->status.ToString().data()));
}
if (params->cb->IsFunction()) {
TryCatch try_catch;
params->cb->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
params->cb.Dispose();
delete params;
scope.Close(Undefined());
}
v8::Handle<v8::Value> Database::Get (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(put, 1, 2)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], key)
v8::Local<v8::Value> keyBufferV = args[0];
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBufferV)
v8::Persistent<v8::Value> keyBuffer = v8::Persistent<v8::Value>::New(keyBufferV);
LD_BOOLEAN_OPTION_VALUE_DEFTRUE(optionsObj, asBuffer)
LD_BOOLEAN_OPTION_VALUE_DEFTRUE(optionsObj, fillCache)
ReadWorker* worker = new ReadWorker(
database
, callback
, key
, asBuffer
, fillCache
, keyBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Delete (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(put, 1, 2)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], key)
v8::Local<v8::Value> keyBufferV = args[0];
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBufferV)
v8::Persistent<v8::Value> keyBuffer =
v8::Persistent<v8::Value>::New(keyBufferV);
LD_BOOLEAN_OPTION_VALUE(optionsObj, sync)
DeleteWorker* worker = new DeleteWorker(
database
, callback
, key
, sync
, keyBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
/* property key & value strings for elements of the array sent to batch() */
LD_SYMBOL ( str_key , key );
LD_SYMBOL ( str_value , value );
LD_SYMBOL ( str_type , type );
LD_SYMBOL ( str_del , del );
LD_SYMBOL ( str_put , put );
v8::Handle<v8::Value> Database::Batch (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(batch, 1, 2)
LD_BOOLEAN_OPTION_VALUE(optionsObj, sync)
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(args[0]);
std::vector< v8::Persistent<v8::Value> >* references =
new std::vector< v8::Persistent<v8::Value> >;
leveldb::WriteBatch* batch = new leveldb::WriteBatch();
for (unsigned int i = 0; i < array->Length(); i++) {
if (!array->Get(i)->IsObject())
continue;
v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(array->Get(i));
LD_CB_ERR_IF_NULL_OR_UNDEFINED(obj->Get(str_type), type)
v8::Local<v8::Value> keyBuffer = obj->Get(str_key);
LD_CB_ERR_IF_NULL_OR_UNDEFINED(keyBuffer, key)
if (obj->Get(str_type)->StrictEquals(str_del)) {
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBuffer)
batch->Delete(key);
if (node::Buffer::HasInstance(keyBuffer->ToObject()))
references->push_back(v8::Persistent<v8::Value>::New(keyBuffer));
} else if (obj->Get(str_type)->StrictEquals(str_put)) {
v8::Local<v8::Value> valueBuffer = obj->Get(str_value);
LD_CB_ERR_IF_NULL_OR_UNDEFINED(valueBuffer, value)
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBuffer)
LD_STRING_OR_BUFFER_TO_SLICE(value, valueBuffer)
batch->Put(key, value);
if (node::Buffer::HasInstance(keyBuffer->ToObject()))
references->push_back(v8::Persistent<v8::Value>::New(keyBuffer));
if (node::Buffer::HasInstance(valueBuffer->ToObject()))
references->push_back(v8::Persistent<v8::Value>::New(valueBuffer));
}
}
AsyncQueueWorker(new BatchWorker(
database
, callback
, batch
, references
, sync
));
return v8::Undefined();
}
v8::Handle<v8::Value> Database::ApproximateSize (const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Value> startBufferV = args[0];
v8::Local<v8::Value> endBufferV = args[1];
if (startBufferV->IsNull()
|| startBufferV->IsUndefined()
|| startBufferV->IsFunction() // callback in pos 0?
|| endBufferV->IsNull()
|| endBufferV->IsUndefined()
|| endBufferV->IsFunction() // callback in pos 1?
) {
LD_THROW_RETURN( \
"approximateSize() requires valid `start`, `end` and `callback` arguments" \
)
}
LD_METHOD_SETUP_COMMON(approximateSize, -1, 2)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], start)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[1], end)
LD_STRING_OR_BUFFER_TO_SLICE(start, startBufferV)
LD_STRING_OR_BUFFER_TO_SLICE(end, endBufferV)
v8::Persistent<v8::Value> startBuffer =
v8::Persistent<v8::Value>::New(startBufferV);
v8::Persistent<v8::Value> endBuffer =
v8::Persistent<v8::Value>::New(endBufferV);
ApproximateSizeWorker* worker = new ApproximateSizeWorker(
database
, callback
, start
, end
, startBuffer
, endBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Iterator (const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Object> optionsObj;
if (args.Length() > 0 && args[0]->IsObject()) {
optionsObj = v8::Local<v8::Object>::Cast(args[0]);
}
return scope.Close(Iterator::NewInstance(args.This(), optionsObj));
}
} // namespace leveldown
<commit_msg>(uv_after_work_cb) cast in cbatch for Node 0.10<commit_after>/* Copyright (c) 2012-2013 LevelDOWN contributors
* See list at <https://github.com/rvagg/node-leveldown#contributing>
* MIT +no-false-attribs License
* <https://github.com/rvagg/node-leveldown/blob/master/LICENSE>
*/
#include <node.h>
#include <node_buffer.h>
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
#include "leveldown.h"
#include "database.h"
#include "async.h"
#include "database_async.h"
#include "batch.h"
#include "cbatch.h"
#include "iterator.h"
namespace leveldown {
Database::Database (char* location) : location(location) {
db = NULL;
};
Database::~Database () {
if (db != NULL)
delete db;
};
const char* Database::Location() const { return location; }
/* Calls from worker threads, NO V8 HERE *****************************/
leveldb::Status Database::OpenDatabase (
leveldb::Options* options
, std::string location
) {
return leveldb::DB::Open(*options, location, &db);
}
leveldb::Status Database::PutToDatabase (
leveldb::WriteOptions* options
, leveldb::Slice key
, leveldb::Slice value
) {
return db->Put(*options, key, value);
}
leveldb::Status Database::GetFromDatabase (
leveldb::ReadOptions* options
, leveldb::Slice key
, std::string& value
) {
return db->Get(*options, key, &value);
}
leveldb::Status Database::DeleteFromDatabase (
leveldb::WriteOptions* options
, leveldb::Slice key
) {
return db->Delete(*options, key);
}
leveldb::Status Database::WriteBatchToDatabase (
leveldb::WriteOptions* options
, leveldb::WriteBatch* batch
) {
return db->Write(*options, batch);
}
uint64_t Database::ApproximateSizeFromDatabase (const leveldb::Range* range) {
uint64_t size;
db->GetApproximateSizes(range, 1, &size);
return size;
}
leveldb::Iterator* Database::NewIterator (leveldb::ReadOptions* options) {
return db->NewIterator(*options);
}
const leveldb::Snapshot* Database::NewSnapshot () {
return db->GetSnapshot();
}
void Database::ReleaseSnapshot (const leveldb::Snapshot* snapshot) {
return db->ReleaseSnapshot(snapshot);
}
void Database::CloseDatabase () {
delete db;
db = NULL;
}
/* V8 exposed functions *****************************/
v8::Persistent<v8::Function> Database::constructor;
v8::Handle<v8::Value> LevelDOWN (const v8::Arguments& args) {
v8::HandleScope scope;
return scope.Close(Database::NewInstance(args));
}
void Database::Init () {
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(New);
tpl->SetClassName(v8::String::NewSymbol("Database"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("open")
, v8::FunctionTemplate::New(Open)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("close")
, v8::FunctionTemplate::New(Close)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("put")
, v8::FunctionTemplate::New(Put)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("get")
, v8::FunctionTemplate::New(Get)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("del")
, v8::FunctionTemplate::New(Delete)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("batch")
, v8::FunctionTemplate::New(Batch)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("approximateSize")
, v8::FunctionTemplate::New(ApproximateSize)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("iterator")
, v8::FunctionTemplate::New(Iterator)->GetFunction()
);
tpl->PrototypeTemplate()->Set(
v8::String::NewSymbol("write")
, v8::FunctionTemplate::New(Write)->GetFunction()
);
constructor = v8::Persistent<v8::Function>::New(tpl->GetFunction());
}
v8::Handle<v8::Value> Database::New (const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() == 0) {
LD_THROW_RETURN("leveldown() requires at least a location argument")
}
if (!args[0]->IsString()) {
LD_THROW_RETURN("leveldown() requires a location string argument")
}
LD_FROM_V8_STRING(location, v8::Handle<v8::String>::Cast(args[0]))
Database* obj = new Database(location);
obj->Wrap(args.This());
return args.This();
}
v8::Handle<v8::Value> Database::NewInstance (const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Object> instance;
if (args.Length() == 0) {
instance = constructor->NewInstance(0, NULL);
} else {
v8::Handle<v8::Value> argv[] = { args[0] };
instance = constructor->NewInstance(1, argv);
}
return scope.Close(instance);
}
v8::Handle<v8::Value> Database::Open (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(open, 0, 1)
LD_BOOLEAN_OPTION_VALUE_DEFTRUE(optionsObj, createIfMissing)
LD_BOOLEAN_OPTION_VALUE(optionsObj, errorIfExists)
LD_BOOLEAN_OPTION_VALUE(optionsObj, compression)
LD_UINT32_OPTION_VALUE(optionsObj, cacheSize, 8 << 20)
OpenWorker* worker = new OpenWorker(
database
, callback
, createIfMissing
, errorIfExists
, compression
, cacheSize
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Close (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON_ONEARG(close)
CloseWorker* worker = new CloseWorker(database, callback);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Put (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(put, 2, 3)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], key)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[1], value)
v8::Local<v8::Value> keyBufferV = args[0];
v8::Local<v8::Value> valueBufferV = args[1];
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBufferV)
LD_STRING_OR_BUFFER_TO_SLICE(value, valueBufferV)
v8::Persistent<v8::Value> keyBuffer =
v8::Persistent<v8::Value>::New(keyBufferV);
v8::Persistent<v8::Value> valueBuffer =
v8::Persistent<v8::Value>::New(valueBufferV);
LD_BOOLEAN_OPTION_VALUE(optionsObj, sync)
WriteWorker* worker = new WriteWorker(
database
, callback
, key
, value
, sync
, keyBuffer
, valueBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
Handle<Value> Database::Write(const Arguments& args) {
HandleScope scope;
Database* database = ObjectWrap::Unwrap<Database>(args.This());
if (args.Length() < 1) {
ThrowException(Exception::Error(String::New("batch required")));
return scope.Close(Undefined());
}
WriteParams *params = new WriteParams();
params->request.data = params;
params->db = database->db;
params->cb = Persistent<Function>::New(Local<Function>::Cast(args[1]));
params->batch = ObjectWrap::Unwrap<CBatch>(args[0]->ToObject());
uv_queue_work(uv_default_loop(), ¶ms->request, WriteDoing, (uv_after_work_cb)WriteAfter);
return scope.Close(args.Holder());
}
void Database::WriteDoing (uv_work_t *req) {
WriteParams *params = (WriteParams *)req->data;
leveldb::WriteBatch wb = params->batch->batch;
params->status = params->db->Write(leveldb::WriteOptions(), &wb);
}
void Database::WriteAfter (uv_work_t *req) {
HandleScope scope;
WriteParams *params = (WriteParams *)req->data;
Handle<Value> argv[1];
if (params->status.ok()) {
argv[0] = Local<Value>::New(Undefined());
} else {
argv[0] = Local<Value>::New(String::New(params->status.ToString().data()));
}
if (params->cb->IsFunction()) {
TryCatch try_catch;
params->cb->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
params->cb.Dispose();
delete params;
scope.Close(Undefined());
}
v8::Handle<v8::Value> Database::Get (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(put, 1, 2)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], key)
v8::Local<v8::Value> keyBufferV = args[0];
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBufferV)
v8::Persistent<v8::Value> keyBuffer = v8::Persistent<v8::Value>::New(keyBufferV);
LD_BOOLEAN_OPTION_VALUE_DEFTRUE(optionsObj, asBuffer)
LD_BOOLEAN_OPTION_VALUE_DEFTRUE(optionsObj, fillCache)
ReadWorker* worker = new ReadWorker(
database
, callback
, key
, asBuffer
, fillCache
, keyBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Delete (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(put, 1, 2)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], key)
v8::Local<v8::Value> keyBufferV = args[0];
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBufferV)
v8::Persistent<v8::Value> keyBuffer =
v8::Persistent<v8::Value>::New(keyBufferV);
LD_BOOLEAN_OPTION_VALUE(optionsObj, sync)
DeleteWorker* worker = new DeleteWorker(
database
, callback
, key
, sync
, keyBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
/* property key & value strings for elements of the array sent to batch() */
LD_SYMBOL ( str_key , key );
LD_SYMBOL ( str_value , value );
LD_SYMBOL ( str_type , type );
LD_SYMBOL ( str_del , del );
LD_SYMBOL ( str_put , put );
v8::Handle<v8::Value> Database::Batch (const v8::Arguments& args) {
v8::HandleScope scope;
LD_METHOD_SETUP_COMMON(batch, 1, 2)
LD_BOOLEAN_OPTION_VALUE(optionsObj, sync)
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(args[0]);
std::vector< v8::Persistent<v8::Value> >* references =
new std::vector< v8::Persistent<v8::Value> >;
leveldb::WriteBatch* batch = new leveldb::WriteBatch();
for (unsigned int i = 0; i < array->Length(); i++) {
if (!array->Get(i)->IsObject())
continue;
v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(array->Get(i));
LD_CB_ERR_IF_NULL_OR_UNDEFINED(obj->Get(str_type), type)
v8::Local<v8::Value> keyBuffer = obj->Get(str_key);
LD_CB_ERR_IF_NULL_OR_UNDEFINED(keyBuffer, key)
if (obj->Get(str_type)->StrictEquals(str_del)) {
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBuffer)
batch->Delete(key);
if (node::Buffer::HasInstance(keyBuffer->ToObject()))
references->push_back(v8::Persistent<v8::Value>::New(keyBuffer));
} else if (obj->Get(str_type)->StrictEquals(str_put)) {
v8::Local<v8::Value> valueBuffer = obj->Get(str_value);
LD_CB_ERR_IF_NULL_OR_UNDEFINED(valueBuffer, value)
LD_STRING_OR_BUFFER_TO_SLICE(key, keyBuffer)
LD_STRING_OR_BUFFER_TO_SLICE(value, valueBuffer)
batch->Put(key, value);
if (node::Buffer::HasInstance(keyBuffer->ToObject()))
references->push_back(v8::Persistent<v8::Value>::New(keyBuffer));
if (node::Buffer::HasInstance(valueBuffer->ToObject()))
references->push_back(v8::Persistent<v8::Value>::New(valueBuffer));
}
}
AsyncQueueWorker(new BatchWorker(
database
, callback
, batch
, references
, sync
));
return v8::Undefined();
}
v8::Handle<v8::Value> Database::ApproximateSize (const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Value> startBufferV = args[0];
v8::Local<v8::Value> endBufferV = args[1];
if (startBufferV->IsNull()
|| startBufferV->IsUndefined()
|| startBufferV->IsFunction() // callback in pos 0?
|| endBufferV->IsNull()
|| endBufferV->IsUndefined()
|| endBufferV->IsFunction() // callback in pos 1?
) {
LD_THROW_RETURN( \
"approximateSize() requires valid `start`, `end` and `callback` arguments" \
)
}
LD_METHOD_SETUP_COMMON(approximateSize, -1, 2)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[0], start)
LD_CB_ERR_IF_NULL_OR_UNDEFINED(args[1], end)
LD_STRING_OR_BUFFER_TO_SLICE(start, startBufferV)
LD_STRING_OR_BUFFER_TO_SLICE(end, endBufferV)
v8::Persistent<v8::Value> startBuffer =
v8::Persistent<v8::Value>::New(startBufferV);
v8::Persistent<v8::Value> endBuffer =
v8::Persistent<v8::Value>::New(endBufferV);
ApproximateSizeWorker* worker = new ApproximateSizeWorker(
database
, callback
, start
, end
, startBuffer
, endBuffer
);
AsyncQueueWorker(worker);
return v8::Undefined();
}
v8::Handle<v8::Value> Database::Iterator (const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Object> optionsObj;
if (args.Length() > 0 && args[0]->IsObject()) {
optionsObj = v8::Local<v8::Object>::Cast(args[0]);
}
return scope.Close(Iterator::NewInstance(args.This(), optionsObj));
}
} // namespace leveldown
<|endoftext|> |
<commit_before>//
// shell-sort.cpp
// Copyright (c) 2017 Dylan Brown. All rights reserved.
//
// NOTES
// Shell sort is a variation on insertion sort which reduces the required number
// of swaps. The idea is to sort to interleaved subsequences with large gaps
// between the elements. Theses gaps shrink in a predefined increment sequence.
//
// [ S H E L L S O R T E X A M P L E ]
// ... completed to 4-sort ...
// [ L E E A M H L E P S O L T S X R ] // h-sorted.
// [ L-------M-------P-------T ]
// [ E-------H-------S-------S ] // Each row
// [ E-------L-------O-------X ] // is sorted.
// [ A-------E-------L-------R ]
//
// First published by Donald Shell (ACM, 1959). This sorting algorithm is a
// useful tool when a std::sort is unavailable, as in some embedded systems.
// The best increment sequence is an unsetteled question. Here are some options:
// D. Shell (original): floor( N/(2^k) ), ... 1. // O(n^2)
// ->V. Pratt (1971): (3^k - 1) / 2, and < ceil(N/3) ... 1. // O(n^(3/2))
// M. Ciura (2001): 1750, 701, 301, 132, 57, 23, 10, 4, 1. // Empirical proof
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
template <typename T> class Shell {
public:
// requires Sortable<T> (T must implement comparison operators).
void sort(std::vector<T> &a);
bool is_sorted(const std::vector<T> &a) {
for (int i = 1; i < a.size(); i++) {
if (less(a[i], a[i - 1])) {
return false;
}
}
return true;
}
void show(const std::vector<T> &a) {
for (auto item : a) {
std::cout << item << " ";
}
std::cout << std::endl;
}
private:
// Returns true if v < w. Again, T must implement comparison operators.
bool less(T v, T w) { return (v < w); }
// Pass by reference to ensure std::swap mutates the caller's data.
void exch(std::vector<T> &a, int i, int j) { std::swap(a[i], a[j]); }
};
template <typename T> void Shell<T>::sort(std::vector<T> &a) {
int N = a.size();
int h = 1;
while (h < N / 3) // Note the integer division.
h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
exch(a, j, j - h);
}
h = h / 3; // Again, note the integer division.
}
}
int main(int argc, char *argv[]) {
// Read file given on command line.
std::string filename;
if (argc != 2) {
std::cout << "Usage: shell-sort ../algs4-data/words3.txt" << std::endl;
return EXIT_FAILURE;
} else {
filename = argv[1];
}
std::ifstream input_file(filename);
if (!input_file.is_open()) {
std::cout << "ERROR: failed to open \"" << filename << "\" for reading."
<< std::endl;
return EXIT_FAILURE;
}
// Instantiate a shell sort object.
auto shl = Shell<std::string>();
// For this example, we'll sort strings in alphabetical order.
// Read the input data into a std::vector of std::string tokens.
std::vector<std::string> tokens;
for (std::string tkn; input_file >> tkn;) {
tokens.push_back(tkn);
}
input_file.close();
// Apply the weighted quick-union algorithm to the input data.
auto begin = std::chrono::steady_clock::now();
shl.sort(tokens);
auto end = std::chrono::steady_clock::now();
// Ensure that the data structure is sorted.
if (!shl.is_sorted(tokens)) {
std::cout << "ERROR: upon review, shell sort"
" failed to completely sort the data."
<< std::endl;
return EXIT_FAILURE;
}
// Output the performance and results.
std::cout << "Shell::sort, elapsed time (ns) = "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin)
.count()
<< std::endl;
shl.show(tokens);
}
<commit_msg>Update shell-sort.cpp<commit_after>//
// shell-sort.cpp
// Copyright (c) 2017 Dylan Brown. All rights reserved.
//
// NOTES
// Shell sort is a variation on insertion sort which reduces the required number
// of swaps. The idea is to sort to interleaved subsequences with large gaps
// between the elements. Theses gaps shrink in a predefined increment sequence.
//
// [ S H E L L S O R T E X A M P L E ]
// ... completed to 4-sort ...
// [ L E E A M H L E P S O L T S X R ] // h-sorted.
// [ L-------M-------P-------T ]
// [ E-------H-------S-------S ] // Each row
// [ E-------L-------O-------X ] // is sorted.
// [ A-------E-------L-------R ]
//
// First published by Donald Shell (ACM, 1959). This sorting algorithm is a
// useful tool when a std::sort is unavailable, as in some embedded systems.
// The best increment sequence is an unsetteled question. Here are some options:
// D. Shell (original): floor( N/(2^k) ), ... 1. // O(n^2)
// ->V. Pratt (1971): (3^k - 1) / 2, and < ceil(N/3) ... 1. // O(n^(3/2))
// M. Ciura (2001): 1750, 701, 301, 132, 57, 23, 10, 4, 1. // Empirical proof
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
template <typename T> class Shell {
public:
// requires Sortable<T> (T must implement comparison operators).
void sort(std::vector<T> &a);
bool is_sorted(const std::vector<T> &a) {
for (int i = 1; i < a.size(); i++) {
if (less(a[i], a[i - 1])) {
return false;
}
}
return true;
}
void show(const std::vector<T> &a) {
for (auto item : a) {
std::cout << item << " ";
}
std::cout << std::endl;
}
private:
// Returns true if v < w. Again, T must implement comparison operators.
bool less(T v, T w) { return (v < w); }
// Pass by reference to ensure std::swap mutates the caller's data.
void exch(std::vector<T> &a, int i, int j) { std::swap(a[i], a[j]); }
};
template <typename T> void Shell<T>::sort(std::vector<T> &a) {
int N = a.size();
int h = 1;
while (h < N / 3) // Note the integer division.
h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
exch(a, j, j - h);
}
h = h / 3; // Again, note the integer division.
}
}
int main(int argc, char *argv[]) {
// Read file given on command line.
std::string filename;
if (argc != 2) {
std::cout << "Usage: shell-sort ../algs4-data/words3.txt" << std::endl;
return EXIT_FAILURE;
} else {
filename = argv[1];
}
std::ifstream input_file(filename);
if (!input_file.is_open()) {
std::cout << "ERROR: failed to open \"" << filename << "\" for reading."
<< std::endl;
return EXIT_FAILURE;
}
// Instantiate a shell sort object.
auto shl = Shell<std::string>();
// For this example, we'll sort strings in alphabetical order.
// Read the input data into a std::vector of std::string tokens.
std::vector<std::string> tokens;
for (std::string tkn; input_file >> tkn;) {
tokens.push_back(tkn);
}
input_file.close();
// Apply the weighted quick-union algorithm to the input data.
auto begin = std::chrono::steady_clock::now();
shl.sort(tokens);
auto end = std::chrono::steady_clock::now();
// Ensure that the data structure is sorted.
if (!shl.is_sorted(tokens)) {
std::cout << "ERROR: upon review, shell sort"
" failed to completely sort the data."
<< std::endl;
return EXIT_FAILURE;
}
// Output the performance and results.
std::cout << "Shell::sort, elapsed time (ns) = "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin)
.count()
<< std::endl;
shl.show(tokens);
}
<|endoftext|> |
<commit_before>#pragma once
#include "c.hpp"
#include "global.hpp"
namespace WonderRabbitProject
{
namespace SQLite3
{
inline void validate(RESULT_CODE r)
{
switch(r)
{
case RESULT_CODE::OK:
case RESULT_CODE::ROW:
case RESULT_CODE::DONE:
return;
default:
// ToDo: to_string(RESULT_CODE)
auto m = u8"FAIL; RESULT_CODE is " + std::to_string(int(r));
throw std::runtime_error(m);
}
}
struct zeroblob_size_t final
{
explicit zeroblob_size_t(size_t size__) noexcept
: size_(size__)
{ }
size_t size() const
{ return size_; }
private:
const size_t size_;
};
}
}
<commit_msg>specialize the runtime exception and include result code.<commit_after>#pragma once
#include "c.hpp"
#include "global.hpp"
namespace WonderRabbitProject
{
namespace SQLite3
{
struct runtime_error
: public std::runtime_error
{
const RESULT_CODE result_code;
runtime_error( const std::string& message, const RESULT_CODE r )
: std::runtime_error( message )
, result_code( r )
{ }
};
inline void validate(RESULT_CODE r)
{
switch(r)
{
case RESULT_CODE::OK:
case RESULT_CODE::ROW:
case RESULT_CODE::DONE:
return;
default:
// ToDo: to_string(RESULT_CODE)
auto m = u8"FAIL; RESULT_CODE is " + std::to_string( static_cast< int >( r ) );
throw runtime_error( m );
}
}
struct zeroblob_size_t final
{
explicit zeroblob_size_t(size_t size__) noexcept
: size_(size__)
{ }
size_t size() const
{ return size_; }
private:
const size_t size_;
};
}
}
<|endoftext|> |
<commit_before>#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_
#define CLOTHO_BIT_BLOCK_FITNESS_HPP_
#include <iostream>
#include "clotho/fitness/bit_block_genotyper.hpp"
#include "clotho/utility/bit_block_iterator.hpp"
#include "clotho/fitness/no_fit.hpp"
namespace clotho {
namespace fitness {
template < class HetFit, class AltHomFit, class RefHomFit, class Result = double >
class bit_block_fitness {
public:
typedef Result result_type;
bit_block_fitness() {}
bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) :
m_hets( hets )
, m_ahoms(ahoms)
, m_rhoms(rhoms) {
}
template < class Block, class ElementIterator >
result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
result_type res = f;
typedef bit_block_genotyper< Block > genotyper;
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms);
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms);
return res;
}
virtual ~bit_block_fitness() {}
protected:
template < class Block, class ElementIterator, class FitOp >
void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
typedef clotho::utility::bit_block_iterator< Block, clotho::utility::walk_iterator_tag > iterator;
iterator it( b ), end;
while( it != end ) {
(*op)( res, *(first + *it++));
}
}
template < class Block, class ElementIterator, class SetOp, class FitOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
Block bits = ( (*sop)(b0, b1) & keep );
computeFitness( res, bits, first, op );
}
template < class Block, class ElementIterator, class SetOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }
HetFit m_hets;
AltHomFit m_ahoms;
RefHomFit m_rhoms;
};
template < class HetFit, class HomFit, class Result >
class bit_block_fitness< HetFit, HomFit, HomFit, Result > {
public:
typedef Result result_type;
bit_block_fitness( ) {}
bit_block_fitness( const HetFit & hets, const HomFit & homs ) :
m_hets( hets )
, m_homs(homs) {
}
template < class Block, class ElementIterator >
result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
result_type res = f;
typedef bit_block_genotyper< Block > genotyper;
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs);
return res;
}
virtual ~bit_block_fitness() {}
protected:
template < class Block, class ElementIterator, class FitOp >
inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
typedef clotho::utility::bit_block_iterator< Block > iterator;
iterator it( b ), end;
while( it != end ) {
(*op)( res, *(first + *it++));
}
}
template < class Block, class ElementIterator, class SetOp, class FitOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
Block bits = ( (*sop)(b0, b1) & keep );
computeFitness( res, bits, first, op );
}
template < class Block, class ElementIterator, class SetOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }
HetFit m_hets;
HomFit m_homs;
};
template < class Result >
class bit_block_fitness< no_fit, no_fit, no_fit, Result > {
public:
typedef Result result_type;
bit_block_fitness( ) {}
template < class Block, class ElementIterator >
result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
return f;
}
virtual ~bit_block_fitness() {}
};
} // namespace fitness {
} // namespace clotho {
#endif // CLOTHO_BIT_BLOCK_FITNESS_HPP_
<commit_msg>Utilizing bit_block_iterator.done() method. Changed iterator advancement<commit_after>#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_
#define CLOTHO_BIT_BLOCK_FITNESS_HPP_
#include <iostream>
#include "clotho/fitness/bit_block_genotyper.hpp"
#include "clotho/utility/bit_block_iterator.hpp"
#include "clotho/fitness/no_fit.hpp"
namespace clotho {
namespace fitness {
template < class HetFit, class AltHomFit, class RefHomFit, class Result = double >
class bit_block_fitness {
public:
typedef Result result_type;
bit_block_fitness() {}
bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) :
m_hets( hets )
, m_ahoms(ahoms)
, m_rhoms(rhoms) {
}
template < class Block, class ElementIterator >
result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
result_type res = f;
typedef bit_block_genotyper< Block > genotyper;
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms);
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms);
return res;
}
virtual ~bit_block_fitness() {}
protected:
template < class Block, class ElementIterator, class FitOp >
void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
typedef clotho::utility::bit_block_iterator< Block, clotho::utility::walk_iterator_tag > iterator;
iterator it( b );
while( !it.done() ) {
(*op)( res, *(first + *it));
++it;
}
}
template < class Block, class ElementIterator, class SetOp, class FitOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
Block bits = ( (*sop)(b0, b1) & keep );
computeFitness( res, bits, first, op );
}
template < class Block, class ElementIterator, class SetOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }
HetFit m_hets;
AltHomFit m_ahoms;
RefHomFit m_rhoms;
};
template < class HetFit, class HomFit, class Result >
class bit_block_fitness< HetFit, HomFit, HomFit, Result > {
public:
typedef Result result_type;
bit_block_fitness( ) {}
bit_block_fitness( const HetFit & hets, const HomFit & homs ) :
m_hets( hets )
, m_homs(homs) {
}
template < class Block, class ElementIterator >
result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
result_type res = f;
typedef bit_block_genotyper< Block > genotyper;
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs);
return res;
}
virtual ~bit_block_fitness() {}
protected:
template < class Block, class ElementIterator, class FitOp >
inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
typedef clotho::utility::bit_block_iterator< Block > iterator;
iterator it( b );
while( !it.done() ) {
(*op)( res, *(first + *it));
++it;
}
}
template < class Block, class ElementIterator, class SetOp, class FitOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
Block bits = ( (*sop)(b0, b1) & keep );
computeFitness( res, bits, first, op );
}
template < class Block, class ElementIterator, class SetOp >
inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }
HetFit m_hets;
HomFit m_homs;
};
template < class Result >
class bit_block_fitness< no_fit, no_fit, no_fit, Result > {
public:
typedef Result result_type;
bit_block_fitness( ) {}
template < class Block, class ElementIterator >
result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
return f;
}
virtual ~bit_block_fitness() {}
};
} // namespace fitness {
} // namespace clotho {
#endif // CLOTHO_BIT_BLOCK_FITNESS_HPP_
<|endoftext|> |
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <boost/program_options.hpp>
#include <graph/graph.hh>
#include <graph/product.hh>
#include <graph/file_formats.hh>
#include <iostream>
#include <exception>
#include <cstdlib>
#include <set>
using namespace parasols;
namespace po = boost::program_options;
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
("format", po::value<std::string>(), "Specify the format of the input")
;
po::options_description all_options{ "All options" };
all_options.add_options()
("graph1", "First input graph (DIMACS format, unless --format is specified).")
("graph2", "Second input graph (DIMACS format, unless --format is specified).")
;
all_options.add(display_options);
po::positional_options_description positional_options;
positional_options
.add("graph1", 1)
.add("graph2", 1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] graph1 graph2" << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No n specified? Show a message and exit. */
if (! options_vars.count("graph1") || ! options_vars.count("graph2")) {
std::cout << "Usage: " << argv[0] << " [options] graph1 graph2" << std::endl;
return EXIT_FAILURE;
}
/* Turn a format name into a runnable function. */
auto format = graph_file_formats.begin(), format_end = graph_file_formats.end();
if (options_vars.count("format"))
for ( ; format != format_end ; ++format)
if (format->first == options_vars["format"].as<std::string>())
break;
/* Unknown format? Show a message and exit. */
if (format == format_end) {
std::cerr << "Unknown format " << options_vars["format"].as<std::string>() << ", choose from:";
for (auto a : graph_file_formats)
std::cerr << " " << a.first;
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* Read in the graphs */
auto graph1 = std::get<1>(*format)(options_vars["graph1"].as<std::string>());
auto graph2 = std::get<1>(*format)(options_vars["graph2"].as<std::string>());
auto product = modular_product(graph1, graph2);
std::cout << "p edge " << product.size() << " 0" << std::endl;
for (int e = 0 ; e < product.size() ; ++e) {
for (int f = e + 1 ; f < product.size() ; ++f) {
if (product.adjacent(e, f))
std::cout << "e " << e << " " << f << std::endl;
}
}
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>1-indexed<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <boost/program_options.hpp>
#include <graph/graph.hh>
#include <graph/product.hh>
#include <graph/file_formats.hh>
#include <iostream>
#include <exception>
#include <cstdlib>
#include <set>
using namespace parasols;
namespace po = boost::program_options;
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
("format", po::value<std::string>(), "Specify the format of the input")
;
po::options_description all_options{ "All options" };
all_options.add_options()
("graph1", "First input graph (DIMACS format, unless --format is specified).")
("graph2", "Second input graph (DIMACS format, unless --format is specified).")
;
all_options.add(display_options);
po::positional_options_description positional_options;
positional_options
.add("graph1", 1)
.add("graph2", 1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] graph1 graph2" << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No n specified? Show a message and exit. */
if (! options_vars.count("graph1") || ! options_vars.count("graph2")) {
std::cout << "Usage: " << argv[0] << " [options] graph1 graph2" << std::endl;
return EXIT_FAILURE;
}
/* Turn a format name into a runnable function. */
auto format = graph_file_formats.begin(), format_end = graph_file_formats.end();
if (options_vars.count("format"))
for ( ; format != format_end ; ++format)
if (format->first == options_vars["format"].as<std::string>())
break;
/* Unknown format? Show a message and exit. */
if (format == format_end) {
std::cerr << "Unknown format " << options_vars["format"].as<std::string>() << ", choose from:";
for (auto a : graph_file_formats)
std::cerr << " " << a.first;
std::cerr << std::endl;
return EXIT_FAILURE;
}
/* Read in the graphs */
auto graph1 = std::get<1>(*format)(options_vars["graph1"].as<std::string>());
auto graph2 = std::get<1>(*format)(options_vars["graph2"].as<std::string>());
auto product = modular_product(graph1, graph2);
std::cout << "p edge " << product.size() << " 0" << std::endl;
for (int e = 0 ; e < product.size() ; ++e) {
for (int f = e + 1 ; f < product.size() ; ++f) {
if (product.adjacent(e, f))
std::cout << "e " << (e + 1) << " " << (f + 1) << std::endl;
}
}
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>#include <enumerate.hpp>
#include <range.hpp>
#include <string>
#include <iostream>
#include <vector>
using iter::enumerate;
using iter::range;
int main() {
std::cout << "const std::string\n";
const std::string const_string("goodbye world");
for (auto e : enumerate(const_string)) {
std::cout << e.index << ": " << e.element << std::endl;
}
std::vector<int> vec;
for(int i = 0; i < 12; ++i) {
vec.push_back(i * i);
}
std::cout << "print vector element, set it to zero, then print it again\n";
for (auto e : enumerate(vec)) {
std::cout << e.index << ": " << e.element << std::endl;
e.element = 0;
// tests to make sure vector can be edited
std::cout << e.index << ": " << e.element << std::endl;
}
std::cout << "static array\n";
int array[] = {1, 9, 8, 11};
for (auto e : enumerate(array)) {
std::cout << e.index << ": " << e.element << '\n';
}
std::cout << "initializer list\n";
for (auto e : enumerate({0, 1, 4, 9, 16, 25})) {
std::cout << e.index << "^2 = " << e.element << '\n';
}
std::cout << "range(10, 20, 2)\n";
for (auto e : enumerate(range(10, 20, 2))) {
std::cout << e.index << ": " << e.element << '\n';
}
return 0;
}
<commit_msg>Adds enumerate test with temporaries<commit_after>#include "testbase.hpp"
#include <enumerate.hpp>
#include <range.hpp>
#include <string>
#include <iostream>
#include <vector>
using iter::enumerate;
using iter::range;
int main() {
std::cout << "const std::string\n";
const std::string const_string("goodbye world");
for (auto e : enumerate(const_string)) {
std::cout << e.index << ": " << e.element << std::endl;
}
std::vector<int> vec;
for(int i = 0; i < 12; ++i) {
vec.push_back(i * i);
}
std::cout << "print vector element, set it to zero, then print it again\n";
for (auto e : enumerate(vec)) {
std::cout << e.index << ": " << e.element << std::endl;
e.element = 0;
// tests to make sure vector can be edited
std::cout << e.index << ": " << e.element << std::endl;
}
std::cout << "static array\n";
int array[] = {1, 9, 8, 11};
for (auto e : enumerate(array)) {
std::cout << e.index << ": " << e.element << '\n';
}
std::cout << "initializer list\n";
for (auto e : enumerate({0, 1, 4, 9, 16, 25})) {
std::cout << e.index << "^2 = " << e.element << '\n';
}
std::cout << "range(10, 20, 2)\n";
for (auto e : enumerate(range(10, 20, 2))) {
std::cout << e.index << ": " << e.element << '\n';
}
std::cout << "range(10, 20, 2)\n";
for (auto e : enumerate(enumerate(range(10, 20, 2)))) {
std::cout << e.index << ": " << e.element.element << '\n';
}
std::cout << "vector temporary\n";
for (auto e : enumerate(std::vector<int>(5,2))) {
std::cout << e.index << ": " << e.element << '\n';
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Distributed memory pool in shared memory.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef SHM_DCHUNK_HXX
#define SHM_DCHUNK_HXX
#include "shm.hxx"
#include <inline/compiler.h>
#include <inline/list.h>
#include <boost/interprocess/managed_external_buffer.hpp>
#include <assert.h>
#include <stddef.h>
struct DpoolChunk {
struct list_head siblings;
boost::interprocess::managed_external_buffer m;
struct alignas(16) {
size_t data[1];
} data;
/**
* @param total_size the size of the memory allocation this
* #DpoolChunk lives in; it is used to calculate the usable chunk
* size
*/
explicit DpoolChunk(size_t total_size)
:m(boost::interprocess::create_only, &data,
total_size - sizeof(*this) + sizeof(data)) {
assert(total_size >= sizeof(*this));
}
static DpoolChunk *New(struct shm &shm, struct list_head &chunks_head) {
assert(shm_page_size(&shm) >= sizeof(DpoolChunk));
DpoolChunk *chunk;
const size_t size = shm_page_size(&shm) - sizeof(*chunk) + sizeof(chunk->data);
chunk = NewFromShm<DpoolChunk>(&shm, 1, size);
if (chunk == nullptr)
return nullptr;
list_add(&chunk->siblings, &chunks_head);
return chunk;
}
void Destroy(struct shm &shm) {
DeleteFromShm(&shm, this);
}
bool IsEmpty() const {
return const_cast<DpoolChunk *>(this)->m.all_memory_deallocated();
}
gcc_pure
bool Contains(const void *p) const {
return (const unsigned char *)p >= (const unsigned char *)&data &&
(const unsigned char *)p < (const unsigned char *)&data + m.get_size();
}
void *Allocate(size_t alloc_size) {
return m.allocate_aligned(alloc_size, 16, std::nothrow);
}
void Free(void *alloc) {
m.deallocate(alloc);
}
gcc_pure
size_t GetTotalSize() const {
return m.get_size();
}
};
#endif
<commit_msg>shm/dchunk: fix New() size calculation<commit_after>/*
* Distributed memory pool in shared memory.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef SHM_DCHUNK_HXX
#define SHM_DCHUNK_HXX
#include "shm.hxx"
#include <inline/compiler.h>
#include <inline/list.h>
#include <boost/interprocess/managed_external_buffer.hpp>
#include <assert.h>
#include <stddef.h>
struct DpoolChunk {
struct list_head siblings;
boost::interprocess::managed_external_buffer m;
struct alignas(16) {
size_t data[1];
} data;
/**
* @param total_size the size of the memory allocation this
* #DpoolChunk lives in; it is used to calculate the usable chunk
* size
*/
explicit DpoolChunk(size_t total_size)
:m(boost::interprocess::create_only, &data,
total_size - sizeof(*this) + sizeof(data)) {
assert(total_size >= sizeof(*this));
}
static DpoolChunk *New(struct shm &shm, struct list_head &chunks_head) {
assert(shm_page_size(&shm) >= sizeof(DpoolChunk));
DpoolChunk *chunk;
chunk = NewFromShm<DpoolChunk>(&shm, 1, shm_page_size(&shm));
if (chunk == nullptr)
return nullptr;
list_add(&chunk->siblings, &chunks_head);
return chunk;
}
void Destroy(struct shm &shm) {
DeleteFromShm(&shm, this);
}
bool IsEmpty() const {
return const_cast<DpoolChunk *>(this)->m.all_memory_deallocated();
}
gcc_pure
bool Contains(const void *p) const {
return (const unsigned char *)p >= (const unsigned char *)&data &&
(const unsigned char *)p < (const unsigned char *)&data + m.get_size();
}
void *Allocate(size_t alloc_size) {
return m.allocate_aligned(alloc_size, 16, std::nothrow);
}
void Free(void *alloc) {
m.deallocate(alloc);
}
gcc_pure
size_t GetTotalSize() const {
return m.get_size();
}
};
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.