text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Modular Reducer
* (C) 1999-2011 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/reducer.h>
namespace Botan {
/*
* Modular_Reducer Constructor
*/
Modular_Reducer::Modular_Reducer(const BigInt& mod)
{
if(mod <= 0)
throw Invalid_Argument("Modular_Reducer: modulus must be positive");
m_modulus = mod;
m_mod_words = m_modulus.sig_words();
m_modulus_2 = Botan::square(m_modulus);
m_mu = BigInt::power_of_2(2 * BOTAN_MP_WORD_BITS * m_mod_words) / m_modulus;
}
/*
* Barrett Reduction
*/
BigInt Modular_Reducer::reduce(const BigInt& x) const
{
if(m_mod_words == 0)
throw Invalid_State("Modular_Reducer: Never initalized");
const size_t x_sw = x.sig_words();
if(x_sw < m_mod_words || x.cmp(m_modulus, false) < 0)
{
if(x.is_negative())
return x + m_modulus; // make positive
return x;
}
else if(x.cmp(m_modulus_2, false) < 0)
{
secure_vector<word> ws;
BigInt t1(x.data() + m_mod_words - 1, x_sw - (m_mod_words - 1));
t1.mul(m_mu, ws);
t1 >>= (BOTAN_MP_WORD_BITS * (m_mod_words + 1));
t1.mul(m_modulus, ws);
t1.mask_bits(BOTAN_MP_WORD_BITS * (m_mod_words + 1));
t1.rev_sub(x.data(), std::min(x_sw, m_mod_words + 1), ws);
if(t1.is_negative())
{
t1 += BigInt::power_of_2(BOTAN_MP_WORD_BITS * (m_mod_words + 1));
}
t1.reduce_below(m_modulus, ws);
if(x.is_positive())
return t1;
else
return (m_modulus - t1);
}
else
{
// too big, fall back to normal division
return (x % m_modulus);
}
}
}
<commit_msg>In Barrett avoid creating an unnecessary temp<commit_after>/*
* Modular Reducer
* (C) 1999-2011 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/reducer.h>
namespace Botan {
/*
* Modular_Reducer Constructor
*/
Modular_Reducer::Modular_Reducer(const BigInt& mod)
{
if(mod <= 0)
throw Invalid_Argument("Modular_Reducer: modulus must be positive");
m_modulus = mod;
m_mod_words = m_modulus.sig_words();
m_modulus_2 = Botan::square(m_modulus);
m_mu = BigInt::power_of_2(2 * BOTAN_MP_WORD_BITS * m_mod_words) / m_modulus;
}
/*
* Barrett Reduction
*/
BigInt Modular_Reducer::reduce(const BigInt& x) const
{
if(m_mod_words == 0)
throw Invalid_State("Modular_Reducer: Never initalized");
const size_t x_sw = x.sig_words();
if(x_sw < m_mod_words || x.cmp(m_modulus, false) < 0)
{
if(x.is_negative())
return x + m_modulus; // make positive
return x;
}
else if(x.cmp(m_modulus_2, false) < 0)
{
secure_vector<word> ws;
BigInt t1(x.data() + m_mod_words - 1, x_sw - (m_mod_words - 1));
t1.mul(m_mu, ws);
t1 >>= (BOTAN_MP_WORD_BITS * (m_mod_words + 1));
t1.mul(m_modulus, ws);
t1.mask_bits(BOTAN_MP_WORD_BITS * (m_mod_words + 1));
t1.rev_sub(x.data(), std::min(x_sw, m_mod_words + 1), ws);
if(t1.is_negative())
{
t1 += BigInt::power_of_2(BOTAN_MP_WORD_BITS * (m_mod_words + 1));
}
t1.reduce_below(m_modulus, ws);
if(x.is_negative())
t1.rev_sub(m_modulus.data(), m_modulus.size(), ws);
return t1;
}
else
{
// too big, fall back to normal division
return (x % m_modulus);
}
}
}
<|endoftext|> |
<commit_before>/*
* Open Pixel Control server for Fadecandy
*
* Copyright (c) 2013 Micah Elizabeth Scott
*
* 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 "opcsink.h"
#include "util.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
OPCSink::OPCSink(callback_t cb, void *context, bool verbose)
: mVerbose(verbose), mCallback(cb), mContext(context) {}
void OPCSink::start(struct ev_loop *loop, struct addrinfo *listenAddr)
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
return;
}
if (bind(sock, listenAddr->ai_addr, listenAddr->ai_addrlen)) {
perror("bind");
return;
}
if (listen(sock, 4) < 0) {
perror("listen");
return;
}
// Get a callback when we're ready to accept a new connection
ev_io_init(&mIOAccept, cbAccept, sock, EV_READ);
ev_io_start(loop, &mIOAccept);
if (mVerbose) {
struct sockaddr_in *sin = (struct sockaddr_in*) listenAddr->ai_addr;
std::clog << "Listening on " << inet_ntoa(sin->sin_addr) << ":" << ntohs(sin->sin_port) << "\n";
}
}
void OPCSink::cbAccept(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
OPCSink *self = container_of(watcher, OPCSink, mIOAccept);
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof clientAddr;
int sock = accept(watcher->fd, (struct sockaddr *)&clientAddr, &clientAddrLen);
if (sock < 0) {
perror("accept");
return;
}
Client *cli = new Client();
cli->bufferPos = 0;
cli->self = self;
ev_io_init(&cli->ioRead, cbRead, sock, EV_READ);
ev_io_start(loop, &cli->ioRead);
if (self->mVerbose) {
std::clog << "Client connected from " << inet_ntoa(clientAddr.sin_addr) << "\n";
}
}
void OPCSink::cbRead(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
Client *cli = container_of(watcher, Client, ioRead);
OPCSink *self = cli->self;
int r = recv(watcher->fd, cli->bufferPos + (uint8_t*)&cli->buffer,
sizeof(cli->buffer) - cli->bufferPos, 0);
if (r < 0) {
perror("read error");
return;
}
if (r == 0) {
// Client disconnecting
if (self->mVerbose) {
std::clog << "Client disconnected\n";
}
ev_io_stop(loop, watcher);
delete cli;
return;
}
cli->bufferPos += r;
if (cli->bufferPos >= offsetof(Message, data)) {
// We have a header, at least.
unsigned length = offsetof(Message, data) + cli->buffer.length();
if (cli->bufferPos >= length) {
// Complete packet.
self->mCallback(cli->buffer, self->mContext);
// Save any part of the following packet we happened to grab.
memmove(&cli->buffer, length + (uint8_t*)&cli->buffer, cli->bufferPos - length);
cli->bufferPos -= length;
}
}
}
<commit_msg>Socket options, tcp nodelay & reuseaddr<commit_after>/*
* Open Pixel Control server for Fadecandy
*
* Copyright (c) 2013 Micah Elizabeth Scott
*
* 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 "opcsink.h"
#include "util.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <iostream>
OPCSink::OPCSink(callback_t cb, void *context, bool verbose)
: mVerbose(verbose), mCallback(cb), mContext(context) {}
void OPCSink::start(struct ev_loop *loop, struct addrinfo *listenAddr)
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
return;
}
int arg = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &arg, sizeof arg);
if (bind(sock, listenAddr->ai_addr, listenAddr->ai_addrlen)) {
perror("bind");
return;
}
if (listen(sock, 4) < 0) {
perror("listen");
return;
}
// Get a callback when we're ready to accept a new connection
ev_io_init(&mIOAccept, cbAccept, sock, EV_READ);
ev_io_start(loop, &mIOAccept);
if (mVerbose) {
struct sockaddr_in *sin = (struct sockaddr_in*) listenAddr->ai_addr;
std::clog << "Listening on " << inet_ntoa(sin->sin_addr) << ":" << ntohs(sin->sin_port) << "\n";
}
}
void OPCSink::cbAccept(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
OPCSink *self = container_of(watcher, OPCSink, mIOAccept);
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof clientAddr;
int sock = accept(watcher->fd, (struct sockaddr *)&clientAddr, &clientAddrLen);
if (sock < 0) {
perror("accept");
return;
}
int arg = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &arg, sizeof arg);
Client *cli = new Client();
cli->bufferPos = 0;
cli->self = self;
ev_io_init(&cli->ioRead, cbRead, sock, EV_READ);
ev_io_start(loop, &cli->ioRead);
if (self->mVerbose) {
std::clog << "Client connected from " << inet_ntoa(clientAddr.sin_addr) << "\n";
}
}
void OPCSink::cbRead(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
Client *cli = container_of(watcher, Client, ioRead);
OPCSink *self = cli->self;
int r = recv(watcher->fd, cli->bufferPos + (uint8_t*)&cli->buffer,
sizeof(cli->buffer) - cli->bufferPos, 0);
if (r < 0) {
perror("read error");
return;
}
if (r == 0) {
// Client disconnecting
if (self->mVerbose) {
std::clog << "Client disconnected\n";
}
ev_io_stop(loop, watcher);
delete cli;
return;
}
cli->bufferPos += r;
if (cli->bufferPos >= offsetof(Message, data)) {
// We have a header, at least.
unsigned length = offsetof(Message, data) + cli->buffer.length();
if (cli->bufferPos >= length) {
// Complete packet.
self->mCallback(cli->buffer, self->mContext);
// Save any part of the following packet we happened to grab.
memmove(&cli->buffer, length + (uint8_t*)&cli->buffer, cli->bufferPos - length);
cli->bufferPos -= length;
}
}
}
<|endoftext|> |
<commit_before>#include <QCoreApplication>
#include <QtDebug>
#include <iostream>
#include <fstream>
//#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cerrno>
#include <cmath>
#include <thread>
#include <mutex>
#define OUTPUT_FILE "./trials.csv"
#define NUMBER_THREADS 1
#define USE_MULTIPLE_THREADS
// create a mutex that is used to protect the writing of the data to
// the file.
std::mutex writeToFile;
#ifndef M_PI
#define M_PI 3.14159265359
#endif
#define SHOW_PROGRESS
//#define SHOW_INTERMEDIATE
//#define THREAD_DEBUG
#define BASE_DT 0.00001
#define RADIUS 0.06
#ifndef Q_OS_UNIX
double drand48()
{
return((double)(rand())/((double)RAND_MAX));
}
#endif
void normalDistRand(double stdDev,double* randomNumbers)
{
/* Generate a random number in polar coordinates */
double radius = sqrt(-2.0*log(drand48()));
double angle = 2.0*M_PI*drand48();
/* transform the number back into cartesian coordinates */
randomNumbers[0] = stdDev*radius*sin(angle);
randomNumbers[1] = stdDev*radius*cos(angle);
}
void printToCSVFile(double dt, double beta, double g,double tau,
double q, double theta, double h,double s,
double *x,std::ofstream *fp)
{
std::lock_guard<std::mutex> guard(writeToFile); // Make sure that
// this routine
// can only
// access the file once
// at any one time.
*fp << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< theta << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3]
<< std::endl;
(*fp).flush();
}
void linear(long steps,
double a,double gamma,double r,double d,double g,
double *x,double *y,double *z, double dt,
int n,
double beta,double tau,
std::ofstream *fp,
int q,
double h,double s,double *v,double *w, double theta)
{
long m=n-1;
long p=0;
double B[2];
int calcRandom=0;
#ifdef THREAD_DEBUG
std::cout << "My thread id: " << std::this_thread::get_id() << std::endl;
#endif
// Step through every time step.
for (long k=0;k<steps;k++)
{
// Calculate a new set of random numbers if necessary.
if(calcRandom==0)
normalDistRand(sqrt(dt),B); //noise in most recent time step
//x[0]=y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt
//x[0]=x[0]+beta*y[m]*(1-y[m])+0.5*beta*y[m]*(1-y[m])*beta*(1-2*y[m])*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Macroalgae
x[0] = y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt;
//Adds in the noise
//x[0]=x[0]+beta*y[m]*B[calcRandom]+0.5*beta*y[m]*beta*(B[calcRandom]*B[calcRandom]-dt);
x[0] += beta*y[m]*B[calcRandom]+0.5*beta*beta*y[m]*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Coral
x[1] = z[m]+(z[m]*(r-d-(a+r)*y[m]-r*z[m]))*dt;
x[2] = v[m]+(v[m]*(gamma-gamma*v[m]+(a-gamma)*w[m])-(g*v[p]/(1-w[p])))*dt;
x[2] += beta*v[m]*(1-v[m])*B[calcRandom]+0.5*beta*(1-2*v[m])*beta*v[m]*(1-v[m])*(B[calcRandom]*B[calcRandom]-dt);
x[3] = w[m]+(w[m]*(r-d-(a+r)*v[m]-r*w[m]))*dt;
/****************************************************************
Account for extinction and overgrowing!!
****************************************************************/
for(int i=0;i<4;++i)
{
if(x[i]<0.0)
x[i] = 0.0;
else if (x[i]>1.0)
x[i] = 1.0;
}
//Updates delay and cell index
m=(m+1)%n;
p=(p+1)%n;
y[m]=x[0];
z[m]=x[1];
v[m]=x[2];
w[m]=x[3];
calcRandom = (calcRandom+1)%2; // update which random number to use.
}
//printf("%f\t%f\t%f\t%f\t%f\n",dt,beta,tau,x[0],x[1]);
printToCSVFile(dt,beta,g,tau,q,theta,h,s,x,fp);
#ifdef SHOW_INTERMEDIATE
qDebug() << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3];
qDebug() << errno << EDOM << ERANGE;
#endif
}
/* ****************************************************************
main
The main function. Called at the start of the program.
**************************************************************** */
int main(int argc, char *argv[])
{
QCoreApplication b(argc, argv);
long steps; // The number of steps to take in a single simulation.
double *v,*w,*x,*y,*z; // The variables used for the state of the system.
/*
Define the constants.
These are the parameters that are used in the operator for the
differential equations.
*/
double a = 0.1;
double g ;// = 0.3;
double gamma = 0.8;
double r = 1.0;
double d = 0.44;
double tau;
double beta ;// = .5;
// double gZero = ((d*a*r+d*d)*(gamma-a))/(r*r);
// double gOne = (gamma*(a+d))/(a+r);
// double chi = r*gamma/(r+a)-gamma+a; //Intermediate Step
// double xi = -(d*gamma/(r+a)+a); //Intermediate Step
// double cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi); //Intermediate Step
// double coralSaddle = 1-cbar; //Saddle point value for coral
// double macroSaddle = (r-r*coralSaddle-d)/(r+a); //Saddle point value for macroalgae
// long numberDT; // The current iteration for the number assocated with the value of dt.
// double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
// double tauZero = (1/omega)*acos(gZero/g);
double dt = BASE_DT; // Set the initial time step
double final; // The final time for each simulation.
long trials; // The number of simulations to make.
final=50.0; // Set the final time.
trials=400; // Set the number of trials to perform.
// Set the time delay, tau
//double tau = 0.5;
// set up the variables for using different approximations on different threads.
std::thread simulation[NUMBER_THREADS];
int numberThreads = 0;
// Sets the seed for the random numbers
#ifdef Q_OS_UNIX
srand48(time(NULL));
//qDebug() << "This is a POSIX system!" ;
#else
srand(time(NULL));
#endif
// Create a CSV File
std::ofstream fp;
//String fileName = "trials-g" + std::toString(g) + "-tau" + std::toString(tau);
fp.open(OUTPUT_FILE,std::ios::out | std::ios::trunc);
fp << "dt,beta,g,tau,trial,theta,initMacro,initCoral,initTurf,macroalgae,coral,turf,lgMacro,lgCoral,lgTurf" << std::endl;
// Allocate the space for the states of the system
x=(double *) calloc(4,sizeof(double));
y=(double *) calloc(n,sizeof(double)); //macroalgae for multiplicative noise
z=(double *) calloc(n,sizeof(double)); //coral for multiplicative noise
v=(double *) calloc(n,sizeof(double)); //macroalgae for logistic noise
w=(double *) calloc(n,sizeof(double)); //coral for logistic noise
for(tau = .2; tau <= .4; tau += .2 ){
// Determine the number of time steps required to move back to the delay in time.
// The number of cells needed for the delay (changes with dt)
int n;
if(tau != 0)
n=(int)(tau/BASE_DT+0.5);
else
n = 1;
for(g=.2; g<.8; g += .2) {
//double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
// double tauZero = (1/omega)*acos(gZero/g);
// Make different approximations for different values of beta.
for(beta=.2;beta<=1; beta += .2) {
#ifdef SHOW_PROGRESS
std::cout << "dt = " << dt << std::endl;
#endif
//index = tau/dt;
//printf("%i\n",n);
steps=(long)(final/dt);
for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.025)
{
// Make an approximation for different initial conditions.
// Make an arc through 0 to pi/2 radians from the origin.
for (int k=0;k<trials;k++)
{
y[0] = RADIUS*cos(theta); //initial Macroalgae level
z[0] = RADIUS*sin(theta); //initial Coral level
v[0] = RADIUS*cos(theta);
w[0] = RADIUS*sin(theta);
for (int l=1;l<n;l++) //fills in the past times for y, z, v, and w
{
y[l]=y[0];
z[l]=z[0];
v[l]=v[0];
w[l]=w[0];
}
//fprintf(fp,"%f,%f,%f,%f,%f,%f\n",y[0],z[0],1-y[0]-z[0],v[0],w[0],1-v[0]-w[0]);
#ifdef USE_MULTIPLE_THREADS
// Make a simulation for each of the available threads.
// First check to see how many threads are running.
if(numberThreads >= NUMBER_THREADS)
{
// There are too many threads. Wait for each run to end.
while(numberThreads>0)
{
#ifdef THREAD_DEBUG
std::cout << "Waiting on thread "
<< simulation[numberThreads-1].get_id()
<< std::endl;
#endif
simulation[--numberThreads].join();
}
} // if(numberThreads)
// Make a run in a separate thread.
simulation[numberThreads++] = std::thread(linear,
steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#else
// Ignore the different threads. Just make one approximation in this one thread.
linear(steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#endif
#ifdef SHOW_PROGRESS
if(k%20 == 0)
std::cout << " Simulation number " << k << std::endl;
#endif
} // for(k<trials)
} // for(theta<pi/2
}
}
}
// Free up the allocated memory.
free(x);
free(y);
free(z);
free(v);
free(w);
fp.close();
#ifdef SHOW_PROGRESS
std::cout << "all done" << std::endl;
#endif
return b.exec();
}
<commit_msg>Moved the freeing of the vectors for the past times outside of the loops<commit_after>#include <QCoreApplication>
#include <QtDebug>
#include <iostream>
#include <fstream>
//#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cerrno>
#include <cmath>
#include <thread>
#include <mutex>
#define OUTPUT_FILE "./trials.csv"
#define NUMBER_THREADS 1
#define USE_MULTIPLE_THREADS
// create a mutex that is used to protect the writing of the data to
// the file.
std::mutex writeToFile;
#ifndef M_PI
#define M_PI 3.14159265359
#endif
#define SHOW_PROGRESS
//#define SHOW_INTERMEDIATE
//#define THREAD_DEBUG
#define BASE_DT 0.00001
#define RADIUS 0.06
#ifndef Q_OS_UNIX
double drand48()
{
return((double)(rand())/((double)RAND_MAX));
}
#endif
void normalDistRand(double stdDev,double* randomNumbers)
{
/* Generate a random number in polar coordinates */
double radius = sqrt(-2.0*log(drand48()));
double angle = 2.0*M_PI*drand48();
/* transform the number back into cartesian coordinates */
randomNumbers[0] = stdDev*radius*sin(angle);
randomNumbers[1] = stdDev*radius*cos(angle);
}
void printToCSVFile(double dt, double beta, double g,double tau,
double q, double theta, double h,double s,
double *x,std::ofstream *fp)
{
std::lock_guard<std::mutex> guard(writeToFile); // Make sure that
// this routine
// can only
// access the file once
// at any one time.
*fp << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< theta << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3]
<< std::endl;
(*fp).flush();
}
void linear(long steps,
double a,double gamma,double r,double d,double g,
double *x,double *y,double *z, double dt,
int n,
double beta,double tau,
std::ofstream *fp,
int q,
double h,double s,double *v,double *w, double theta)
{
long m=n-1;
long p=0;
double B[2];
int calcRandom=0;
#ifdef THREAD_DEBUG
std::cout << "My thread id: " << std::this_thread::get_id() << std::endl;
#endif
// Step through every time step.
for (long k=0;k<steps;k++)
{
// Calculate a new set of random numbers if necessary.
if(calcRandom==0)
normalDistRand(sqrt(dt),B); //noise in most recent time step
//x[0]=y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt
//x[0]=x[0]+beta*y[m]*(1-y[m])+0.5*beta*y[m]*(1-y[m])*beta*(1-2*y[m])*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Macroalgae
x[0] = y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt;
//Adds in the noise
//x[0]=x[0]+beta*y[m]*B[calcRandom]+0.5*beta*y[m]*beta*(B[calcRandom]*B[calcRandom]-dt);
x[0] += beta*y[m]*B[calcRandom]+0.5*beta*beta*y[m]*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Coral
x[1] = z[m]+(z[m]*(r-d-(a+r)*y[m]-r*z[m]))*dt;
x[2] = v[m]+(v[m]*(gamma-gamma*v[m]+(a-gamma)*w[m])-(g*v[p]/(1-w[p])))*dt;
x[2] += beta*v[m]*(1-v[m])*B[calcRandom]+0.5*beta*(1-2*v[m])*beta*v[m]*(1-v[m])*(B[calcRandom]*B[calcRandom]-dt);
x[3] = w[m]+(w[m]*(r-d-(a+r)*v[m]-r*w[m]))*dt;
/****************************************************************
Account for extinction and overgrowing!!
****************************************************************/
for(int i=0;i<4;++i)
{
if(x[i]<0.0)
x[i] = 0.0;
else if (x[i]>1.0)
x[i] = 1.0;
}
//Updates delay and cell index
m=(m+1)%n;
p=(p+1)%n;
y[m]=x[0];
z[m]=x[1];
v[m]=x[2];
w[m]=x[3];
calcRandom = (calcRandom+1)%2; // update which random number to use.
}
//printf("%f\t%f\t%f\t%f\t%f\n",dt,beta,tau,x[0],x[1]);
printToCSVFile(dt,beta,g,tau,q,theta,h,s,x,fp);
#ifdef SHOW_INTERMEDIATE
qDebug() << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3];
qDebug() << errno << EDOM << ERANGE;
#endif
}
/* ****************************************************************
main
The main function. Called at the start of the program.
**************************************************************** */
int main(int argc, char *argv[])
{
QCoreApplication b(argc, argv);
long steps; // The number of steps to take in a single simulation.
double *v,*w,*x,*y,*z; // The variables used for the state of the system.
/*
Define the constants.
These are the parameters that are used in the operator for the
differential equations.
*/
double a = 0.1;
double g ;// = 0.3;
double gamma = 0.8;
double r = 1.0;
double d = 0.44;
double tau;
double beta ;// = .5;
// double gZero = ((d*a*r+d*d)*(gamma-a))/(r*r);
// double gOne = (gamma*(a+d))/(a+r);
// double chi = r*gamma/(r+a)-gamma+a; //Intermediate Step
// double xi = -(d*gamma/(r+a)+a); //Intermediate Step
// double cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi); //Intermediate Step
// double coralSaddle = 1-cbar; //Saddle point value for coral
// double macroSaddle = (r-r*coralSaddle-d)/(r+a); //Saddle point value for macroalgae
// long numberDT; // The current iteration for the number assocated with the value of dt.
// double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
// double tauZero = (1/omega)*acos(gZero/g);
double dt = BASE_DT; // Set the initial time step
double final; // The final time for each simulation.
long trials; // The number of simulations to make.
final=50.0; // Set the final time.
trials=400; // Set the number of trials to perform.
// Set the time delay, tau
//double tau = 0.5;
// set up the variables for using different approximations on different threads.
std::thread simulation[NUMBER_THREADS];
int numberThreads = 0;
// Sets the seed for the random numbers
#ifdef Q_OS_UNIX
srand48(time(NULL));
//qDebug() << "This is a POSIX system!" ;
#else
srand(time(NULL));
#endif
// Create a CSV File
std::ofstream fp;
//String fileName = "trials-g" + std::toString(g) + "-tau" + std::toString(tau);
fp.open(OUTPUT_FILE,std::ios::out | std::ios::trunc);
fp << "dt,beta,g,tau,trial,theta,initMacro,initCoral,initTurf,macroalgae,coral,turf,lgMacro,lgCoral,lgTurf" << std::endl;
for(tau = .2; tau <= .4; tau += .2 ){
// Determine the number of time steps required to move back to the delay in time.
// The number of cells needed for the delay (changes with dt)
int n;
if(tau != 0)
n=(int)(tau/BASE_DT+0.5);
else
n = 1;
// Allocate the space for the states of the system
x=(double *) calloc(4,sizeof(double));
y=(double *) calloc(n,sizeof(double)); //macroalgae for multiplicative noise
z=(double *) calloc(n,sizeof(double)); //coral for multiplicative noise
v=(double *) calloc(n,sizeof(double)); //macroalgae for logistic noise
w=(double *) calloc(n,sizeof(double)); //coral for logistic noise
for(g=.2; g<.8; g += .2) {
//double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
// double tauZero = (1/omega)*acos(gZero/g);
// Make different approximations for different values of beta.
for(beta=.2;beta<=1; beta += .2) {
#ifdef SHOW_PROGRESS
std::cout << "dt = " << dt << std::endl;
#endif
//index = tau/dt;
//printf("%i\n",n);
steps=(long)(final/dt);
for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.025)
{
// Make an approximation for different initial conditions.
// Make an arc through 0 to pi/2 radians from the origin.
for (int k=0;k<trials;k++)
{
y[0] = RADIUS*cos(theta); //initial Macroalgae level
z[0] = RADIUS*sin(theta); //initial Coral level
v[0] = RADIUS*cos(theta);
w[0] = RADIUS*sin(theta);
for (int l=1;l<n;l++) //fills in the past times for y, z, v, and w
{
y[l]=y[0];
z[l]=z[0];
v[l]=v[0];
w[l]=w[0];
}
//fprintf(fp,"%f,%f,%f,%f,%f,%f\n",y[0],z[0],1-y[0]-z[0],v[0],w[0],1-v[0]-w[0]);
#ifdef USE_MULTIPLE_THREADS
// Make a simulation for each of the available threads.
// First check to see how many threads are running.
if(numberThreads >= NUMBER_THREADS)
{
// There are too many threads. Wait for each run to end.
while(numberThreads>0)
{
#ifdef THREAD_DEBUG
std::cout << "Waiting on thread "
<< simulation[numberThreads-1].get_id()
<< std::endl;
#endif
simulation[--numberThreads].join();
}
} // if(numberThreads)
// Make a run in a separate thread.
simulation[numberThreads++] = std::thread(linear,
steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#else
// Ignore the different threads. Just make one approximation in this one thread.
linear(steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#endif
#ifdef SHOW_PROGRESS
if(k%20 == 0)
std::cout << " Simulation number " << k << std::endl;
#endif
} // for(k<trials)
} // for(theta<pi/2
}
}
// Free up the allocated memory.
free(x);
free(y);
free(z);
free(v);
free(w);
}
fp.close();
#ifdef SHOW_PROGRESS
std::cout << "all done" << std::endl;
#endif
return b.exec();
}
<|endoftext|> |
<commit_before>/*
* The Biomechanical ToolKit
* Copyright (c) 2009-2011, Arnaud Barré
* 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ChartOptionsWidget.h"
#include <QPainter>
#include <QHeaderView>
#include <QColorDialog>
ChartOptionsWidget::ChartOptionsWidget(QWidget* parent)
: QWidget(parent, Qt::Popup | Qt::FramelessWindowHint)
{
this->setupUi(this);
this->setAttribute(Qt::WA_TranslucentBackground);
this->resize(150,250);
QHeaderView* header = this->plotTable->horizontalHeader();
header->setMovable(false);
header->resizeSection(1, 25);
header->setResizeMode(1, QHeaderView::Fixed);
header->setResizeMode(0, QHeaderView::Stretch);
this->gridLayout->setAlignment(Qt::AlignJustify | Qt::AlignVCenter);
#ifdef Q_OS_MAC
QFont f = this->font();
f.setPixelSize(10);
this->plotTable->setFont(f);
this->lineWidthSpinBox->setFont(f);
this->labelLineWidth->setFont(f);
this->labelLineColor->setFont(f);
this->plotTable->setAttribute(Qt::WA_MacShowFocusRect, false);
this->lineWidthSpinBox->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
this->plotTable->verticalHeader()->setDefaultSectionSize(20);
QLayout* layout = this->layout();
layout->setSpacing(6);
layout->setContentsMargins(6, 15, 6, 6);
connect(this->plotTable, SIGNAL(itemSelectionChanged()), this, SLOT(displayPlotOption()));
connect(this->lineWidthSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setLineWidth(double)));
connect(this->lineColorButton, SIGNAL(clicked()), this, SLOT(setLineColor()));
};
void ChartOptionsWidget::appendPlot(int itemId, const QString& label, int color[3], double width)
{
int rowIdx = this->plotTable->rowCount();
this->plotTable->insertRow(rowIdx);
QColor c = QColor(color[0], color[1], color[2]);
QTableWidgetItem* item = new QTableWidgetItem(this->createLineIcon(c, width), label);
item->setData(LineColor, c);
item->setData(LineWidth, width);
item->setData(ItemId, itemId);
this->plotTable->setItem(rowIdx, 0, item);
QPushButton* button = new QPushButton("", this);
button->setFlat(true);
button->setProperty("plotIndex", rowIdx);
button->setStyleSheet("QPushButton {image: url(:/Resources/Images/plot_delete.png);} QPushButton:pressed {image: url(:/Resources/Images/plot_delete-down.png);} QPushButton:flat {border: none;}");
this->plotTable->setCellWidget(rowIdx, 1, button);
connect(button, SIGNAL(clicked()), this, SLOT(removePlot()));
};
void ChartOptionsWidget::clear()
{
this->plotTable->clearContents();
this->plotTable->setRowCount(0);
this->setPlotOptionEnabled(false);
};
void ChartOptionsWidget::setPlotOptionEnabled(bool enabled)
{
this->labelLineWidth->setEnabled(enabled);
this->lineWidthSpinBox->setEnabled(enabled);
this->labelLineColor->setEnabled(enabled);
this->lineColorButton->setEnabled(enabled);
if (!enabled)
{
this->lineWidthSpinBox->clear();
this->setLineColorButtonColor(Qt::white);
}
};
void ChartOptionsWidget::displayPlotOption()
{
QList<QTableWidgetItem*> selectedItems = this->plotTable->selectedItems();
if (selectedItems.isEmpty())
this->setPlotOptionEnabled(false);
else
{
QColor lineColor;
double lineWidth = -1.0;
QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin();
while (it != selectedItems.end())
{
if ((*it)->column() == 0)
{
lineColor = (*it)->data(LineColor).value<QColor>();
lineWidth = (*it)->data(LineWidth).toDouble();
break;
}
++it;
}
while (it != selectedItems.end())
{
if ((*it)->column() == 0)
{
QColor color = (*it)->data(LineColor).value<QColor>();
double width = (*it)->data(LineWidth).toDouble();
if (lineColor != color)
lineColor = QColor();
if (lineWidth != width)
lineWidth = -1.0;
}
if (!lineColor.isValid() && (lineWidth == -1.0))
break;
++it;
}
if (!lineColor.isValid())
this->setLineColorButtonColor(Qt::white);
else
this->setLineColorButtonColor(lineColor);
this->lineWidthSpinBox->blockSignals(true);
if (lineWidth == -1.0)
this->lineWidthSpinBox->clear();
else
this->lineWidthSpinBox->setValue(lineWidth);
this->lineWidthSpinBox->blockSignals(false);
this->setPlotOptionEnabled(true);
}
};
void ChartOptionsWidget::removePlot()
{
QObject* obj = sender();
int idx = obj->property("plotIndex").toInt();
this->plotTable->removeRow(idx);
// Update the other indices
for (int i = idx ; i < this->plotTable->rowCount() ; ++i)
this->plotTable->cellWidget(i,1)->setProperty("plotIndex", i);
if (this->plotTable->rowCount() == 0)
this->setPlotOptionEnabled(false);
emit plotRemoved(idx);
};
void ChartOptionsWidget::setLineColor()
{
QList<QTableWidgetItem*> selectedItems = this->plotTable->selectedItems();
if (selectedItems.isEmpty())
return;
QColor c = selectedItems[0]->data(LineColor).value<QColor>();
for (QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if (c != (*it)->data(LineColor).value<QColor>())
{
c = Qt::white;
break;
}
}
QColor color = QColorDialog::getColor(c, this);
QList<int> indices;
if (color.isValid())
{
for (QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if ((*it)->column() == 0)
{
(*it)->setIcon(this->createLineIcon(color, (*it)->data(LineWidth).toDouble()));
(*it)->setData(LineColor, color);
indices << (*it)->row();
}
}
this->setLineColorButtonColor(color);
emit lineColorChanged(indices, color);
}
// Force the widget to be shown as it disappear when the color dialog is shown
this->setVisible(true);
};
void ChartOptionsWidget::setLineWidth(double value)
{
QList<int> indices;
QList<QTableWidgetItem*> selectedItems = this->plotTable->selectedItems();
for (QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if ((*it)->column() == 0)
{
(*it)->setIcon(this->createLineIcon((*it)->data(LineColor).value<QColor>(), value));
(*it)->setData(LineWidth, value);
indices << (*it)->row();
}
}
emit lineWidthChanged(indices, value);
};
void ChartOptionsWidget::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event)
const double midX = (double)this->width()/2.0;
const double penWidth = 0.5;
static const QPointF points[3] = {
QPointF(midX-12.0, 8.75),
QPointF(midX, 0.0),
QPointF(midX+12.0, 8.75),
};
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::white);
painter.setPen(QPen(Qt::gray, penWidth));
//painter.drawRoundedRect(QRectF(0.0, 20.0, this->width(), this->height()-20), 10.0, 10.0);
painter.drawRect(QRectF(0.0, 8.0, this->width(), this->height()-8.0));
painter.setPen(QPen(Qt::white, penWidth));
painter.drawPolygon(points,3);
painter.setPen(QPen(Qt::gray, penWidth));
painter.drawPolyline(points,3);
};
QPixmap ChartOptionsWidget::createLineIcon(const QColor& color, double width)
{
QPen p = color;
QImage lineImage(16, 16, QImage::Format_ARGB32);
QPainter painter(&lineImage);
// painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::NoBrush);
painter.setPen(Qt::NoPen);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(lineImage.rect(), Qt::transparent);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
p.setWidthF(width); painter.setPen(p);
painter.drawLine(QLineF(2.0, 8.0, 14.0, 8.0));
return QPixmap::fromImage(lineImage);
};
void ChartOptionsWidget::setLineColorButtonColor(const QColor& color)
{
this->lineColorButton->setStyleSheet("QPushButton {background-color: rgb(" + QString::number(color.red()) + "," + QString::number(color.green()) + "," + QString::number(color.blue()) + "); border: 1px solid lightgray;} QPushButton:pressed {border-color: gray;}");
};<commit_msg>[UPD] Mokka: The widget for the chart's options is wider by default.<commit_after>/*
* The Biomechanical ToolKit
* Copyright (c) 2009-2011, Arnaud Barré
* 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ChartOptionsWidget.h"
#include <QPainter>
#include <QHeaderView>
#include <QColorDialog>
ChartOptionsWidget::ChartOptionsWidget(QWidget* parent)
: QWidget(parent, Qt::Popup | Qt::FramelessWindowHint)
{
this->setupUi(this);
this->setAttribute(Qt::WA_TranslucentBackground);
this->resize(175,250);
QHeaderView* header = this->plotTable->horizontalHeader();
header->setMovable(false);
header->resizeSection(1, 25);
header->setResizeMode(1, QHeaderView::Fixed);
header->setResizeMode(0, QHeaderView::Stretch);
this->gridLayout->setAlignment(Qt::AlignJustify | Qt::AlignVCenter);
#ifdef Q_OS_MAC
QFont f = this->font();
f.setPixelSize(10);
this->plotTable->setFont(f);
this->lineWidthSpinBox->setFont(f);
this->labelLineWidth->setFont(f);
this->labelLineColor->setFont(f);
this->plotTable->setAttribute(Qt::WA_MacShowFocusRect, false);
this->lineWidthSpinBox->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
this->plotTable->verticalHeader()->setDefaultSectionSize(20);
QLayout* layout = this->layout();
layout->setSpacing(6);
layout->setContentsMargins(6, 15, 6, 6);
connect(this->plotTable, SIGNAL(itemSelectionChanged()), this, SLOT(displayPlotOption()));
connect(this->lineWidthSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setLineWidth(double)));
connect(this->lineColorButton, SIGNAL(clicked()), this, SLOT(setLineColor()));
};
void ChartOptionsWidget::appendPlot(int itemId, const QString& label, int color[3], double width)
{
int rowIdx = this->plotTable->rowCount();
this->plotTable->insertRow(rowIdx);
QColor c = QColor(color[0], color[1], color[2]);
QTableWidgetItem* item = new QTableWidgetItem(this->createLineIcon(c, width), label);
item->setData(LineColor, c);
item->setData(LineWidth, width);
item->setData(ItemId, itemId);
this->plotTable->setItem(rowIdx, 0, item);
QPushButton* button = new QPushButton("", this);
button->setFlat(true);
button->setProperty("plotIndex", rowIdx);
button->setStyleSheet("QPushButton {image: url(:/Resources/Images/plot_delete.png);} QPushButton:pressed {image: url(:/Resources/Images/plot_delete-down.png);} QPushButton:flat {border: none;}");
this->plotTable->setCellWidget(rowIdx, 1, button);
connect(button, SIGNAL(clicked()), this, SLOT(removePlot()));
};
void ChartOptionsWidget::clear()
{
this->plotTable->clearContents();
this->plotTable->setRowCount(0);
this->setPlotOptionEnabled(false);
};
void ChartOptionsWidget::setPlotOptionEnabled(bool enabled)
{
this->labelLineWidth->setEnabled(enabled);
this->lineWidthSpinBox->setEnabled(enabled);
this->labelLineColor->setEnabled(enabled);
this->lineColorButton->setEnabled(enabled);
if (!enabled)
{
this->lineWidthSpinBox->clear();
this->setLineColorButtonColor(Qt::white);
}
};
void ChartOptionsWidget::displayPlotOption()
{
QList<QTableWidgetItem*> selectedItems = this->plotTable->selectedItems();
if (selectedItems.isEmpty())
this->setPlotOptionEnabled(false);
else
{
QColor lineColor;
double lineWidth = -1.0;
QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin();
while (it != selectedItems.end())
{
if ((*it)->column() == 0)
{
lineColor = (*it)->data(LineColor).value<QColor>();
lineWidth = (*it)->data(LineWidth).toDouble();
break;
}
++it;
}
while (it != selectedItems.end())
{
if ((*it)->column() == 0)
{
QColor color = (*it)->data(LineColor).value<QColor>();
double width = (*it)->data(LineWidth).toDouble();
if (lineColor != color)
lineColor = QColor();
if (lineWidth != width)
lineWidth = -1.0;
}
if (!lineColor.isValid() && (lineWidth == -1.0))
break;
++it;
}
if (!lineColor.isValid())
this->setLineColorButtonColor(Qt::white);
else
this->setLineColorButtonColor(lineColor);
this->lineWidthSpinBox->blockSignals(true);
if (lineWidth == -1.0)
this->lineWidthSpinBox->clear();
else
this->lineWidthSpinBox->setValue(lineWidth);
this->lineWidthSpinBox->blockSignals(false);
this->setPlotOptionEnabled(true);
}
};
void ChartOptionsWidget::removePlot()
{
QObject* obj = sender();
int idx = obj->property("plotIndex").toInt();
this->plotTable->removeRow(idx);
// Update the other indices
for (int i = idx ; i < this->plotTable->rowCount() ; ++i)
this->plotTable->cellWidget(i,1)->setProperty("plotIndex", i);
if (this->plotTable->rowCount() == 0)
this->setPlotOptionEnabled(false);
emit plotRemoved(idx);
};
void ChartOptionsWidget::setLineColor()
{
QList<QTableWidgetItem*> selectedItems = this->plotTable->selectedItems();
if (selectedItems.isEmpty())
return;
QColor c = selectedItems[0]->data(LineColor).value<QColor>();
for (QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if (c != (*it)->data(LineColor).value<QColor>())
{
c = Qt::white;
break;
}
}
QColor color = QColorDialog::getColor(c, this);
QList<int> indices;
if (color.isValid())
{
for (QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if ((*it)->column() == 0)
{
(*it)->setIcon(this->createLineIcon(color, (*it)->data(LineWidth).toDouble()));
(*it)->setData(LineColor, color);
indices << (*it)->row();
}
}
this->setLineColorButtonColor(color);
emit lineColorChanged(indices, color);
}
// Force the widget to be shown as it disappear when the color dialog is shown
this->setVisible(true);
};
void ChartOptionsWidget::setLineWidth(double value)
{
QList<int> indices;
QList<QTableWidgetItem*> selectedItems = this->plotTable->selectedItems();
for (QList<QTableWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if ((*it)->column() == 0)
{
(*it)->setIcon(this->createLineIcon((*it)->data(LineColor).value<QColor>(), value));
(*it)->setData(LineWidth, value);
indices << (*it)->row();
}
}
emit lineWidthChanged(indices, value);
};
void ChartOptionsWidget::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event)
const double midX = (double)this->width()/2.0;
const double penWidth = 0.5;
static const QPointF points[3] = {
QPointF(midX-12.0, 8.75),
QPointF(midX, 0.0),
QPointF(midX+12.0, 8.75),
};
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::white);
painter.setPen(QPen(Qt::gray, penWidth));
//painter.drawRoundedRect(QRectF(0.0, 20.0, this->width(), this->height()-20), 10.0, 10.0);
painter.drawRect(QRectF(0.0, 8.0, this->width(), this->height()-8.0));
painter.setPen(QPen(Qt::white, penWidth));
painter.drawPolygon(points,3);
painter.setPen(QPen(Qt::gray, penWidth));
painter.drawPolyline(points,3);
};
QPixmap ChartOptionsWidget::createLineIcon(const QColor& color, double width)
{
QPen p = color;
QImage lineImage(16, 16, QImage::Format_ARGB32);
QPainter painter(&lineImage);
// painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::NoBrush);
painter.setPen(Qt::NoPen);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(lineImage.rect(), Qt::transparent);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
p.setWidthF(width); painter.setPen(p);
painter.drawLine(QLineF(2.0, 8.0, 14.0, 8.0));
return QPixmap::fromImage(lineImage);
};
void ChartOptionsWidget::setLineColorButtonColor(const QColor& color)
{
this->lineColorButton->setStyleSheet("QPushButton {background-color: rgb(" + QString::number(color.red()) + "," + QString::number(color.green()) + "," + QString::number(color.blue()) + "); border: 1px solid lightgray;} QPushButton:pressed {border-color: gray;}");
};<|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/plugin_list.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "build/build_config.h"
namespace {
// Return true if we're in debug-plugin-loading mode.
bool DebugPluginLoading() {
static const char kDebugPluginLoading[] = "debug-plugin-loading";
return CommandLine::ForCurrentProcess()->HasSwitch(kDebugPluginLoading);
}
// We build up a list of files and mtimes so we can sort them.
typedef std::pair<FilePath, base::Time> FileAndTime;
typedef std::vector<FileAndTime> FileTimeList;
// Comparator used to sort by descending mtime then ascending filename.
bool CompareTime(const FileAndTime& a, const FileAndTime& b) {
if (a.second == b.second) {
// Fall back on filename sorting, just to make the predicate valid.
return a.first < b.first;
}
// Sort by mtime, descending.
return a.second > b.second;
}
// Some plugins are shells around other plugins; we prefer to use the
// real plugin directly, if it's available. This function returns
// true if we should prefer other plugins over this one. We'll still
// use a "undesirable" plugin if no other option is available.
bool IsUndesirablePlugin(const WebPluginInfo& info) {
std::string filename = info.path.BaseName().value();
return (filename.find("npcxoffice") != std::string::npos || // Crossover
filename.find("npwrapper") != std::string::npos); // nspluginwrapper
}
} // anonymous namespace
namespace NPAPI {
void PluginList::PlatformInit() {
}
void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
// See http://groups.google.com/group/chromium-dev/browse_thread/thread/7a70e5fcbac786a9
// for discussion.
// We first consult Chrome-specific dirs, then fall back on the logic
// Mozilla uses.
// TODO(evanm): maybe consult our own plugins dir, like
// ~/.config/chromium/Plugins?
// The Chrome binary dir + "plugins/".
FilePath dir;
PathService::Get(base::DIR_EXE, &dir);
plugin_dirs->push_back(dir.Append("plugins"));
// Mozilla code to reference:
// http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
// and tens of accompanying files (mxr is very helpful).
// This code carefully matches their behavior for compat reasons.
// 1) MOZ_PLUGIN_PATH env variable.
const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
if (moz_plugin_path) {
std::vector<std::string> paths;
SplitString(moz_plugin_path, ':', &paths);
for (size_t i = 0; i < paths.size(); ++i)
plugin_dirs->push_back(FilePath(paths[i]));
}
// 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
// This is a de-facto standard, so even though we're not Mozilla, let's
// look in there too.
const char* home = getenv("HOME");
if (home)
plugin_dirs->push_back(FilePath(home).Append(".mozilla/plugins"));
// 3) NS_SYSTEM_PLUGINS_DIR:
// This varies across different versions of Firefox, so check 'em all.
plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib/firefox/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib/xulrunner-addons/plugins"));
#if defined(ARCH_CPU_64_BITS)
// On my Ubuntu system, /usr/lib64 is a symlink to /usr/lib.
// But a user reported on their Fedora system they are separate.
plugin_dirs->push_back(FilePath("/usr/lib64/mozilla/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib64/firefox/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib64/xulrunner-addons/plugins"));
#endif
}
void PluginList::LoadPluginsFromDir(const FilePath& path,
std::vector<WebPluginInfo>* plugins) {
// See ScanPluginsDirectory near
// http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginHostImpl.cpp#5052
// Construct and stat a list of all filenames under consideration, for
// later sorting by mtime.
FileTimeList files;
file_util::FileEnumerator enumerator(path,
false, // not recursive
file_util::FileEnumerator::FILES);
for (FilePath path = enumerator.Next(); !path.value().empty();
path = enumerator.Next()) {
// Skip over Mozilla .xpt files.
if (path.MatchesExtension(FILE_PATH_LITERAL(".xpt")))
continue;
// Java doesn't like being loaded through a symlink, since it uses
// its path to find dependent data files.
// file_util::AbsolutePath calls through to realpath(), which resolves
// symlinks.
FilePath orig_path = path;
file_util::AbsolutePath(&path);
if (DebugPluginLoading())
LOG(ERROR) << "Resolved " << orig_path.value() << " -> " << path.value();
// Flash stops working if the containing directory involves 'netscape'.
// No joke. So use the other path if it's better.
static const char kFlashPlayerFilename[] = "libflashplayer.so";
static const char kNetscapeInPath[] = "/netscape/";
if (path.BaseName().value() == kFlashPlayerFilename &&
path.value().find(kNetscapeInPath) != std::string::npos) {
if (orig_path.value().find(kNetscapeInPath) == std::string::npos) {
// Go back to the old path.
path = orig_path;
} else {
LOG(ERROR) << "Flash misbehaves when used from a directory containing "
<< kNetscapeInPath << ", so skipping " << orig_path.value();
continue;
}
}
// Get mtime.
file_util::FileInfo info;
if (!file_util::GetFileInfo(path, &info))
continue;
// Skip duplicates of the same file in our list.
bool skip = false;
for (size_t i = 0; i < plugins->size(); ++i) {
if (plugins->at(i).path == path) {
skip = true;
break;
}
}
if (skip) {
if (DebugPluginLoading())
LOG(ERROR) << "Skipping duplicate instance of " << path.value();
continue;
}
files.push_back(std::make_pair(path, info.last_modified));
}
// Sort the file list by time (and filename).
std::sort(files.begin(), files.end(), CompareTime);
// Load the files in order.
for (FileTimeList::const_iterator i = files.begin(); i != files.end(); ++i) {
LoadPlugin(i->first, plugins);
}
}
bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info,
std::vector<WebPluginInfo>* plugins) {
if (DebugPluginLoading()) {
LOG(ERROR) << "Considering " << info.path.value()
<< " (" << info.name << ")";
}
if (IsUndesirablePlugin(info)) {
if (DebugPluginLoading())
LOG(ERROR) << info.path.value() << " is undesirable.";
// See if we have a better version of this plugin.
for (size_t i = 0; i < plugins->size(); ++i) {
if (plugins->at(i).name == info.name &&
!IsUndesirablePlugin(plugins->at(i))) {
// Skip the current undesirable one so we can use the better one
// we just found.
if (DebugPluginLoading()) {
LOG(ERROR) << "Skipping " << info.path.value() << ", preferring "
<< plugins->at(i).path.value();
}
return false;
}
}
}
// TODO(evanm): prefer the newest version of flash, etc. here?
if (DebugPluginLoading())
LOG(ERROR) << "Using " << info.path.value();
return true;
}
} // namespace NPAPI
<commit_msg>linux: add another path to plugin search path list<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/plugin_list.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "build/build_config.h"
namespace {
// Return true if we're in debug-plugin-loading mode.
bool DebugPluginLoading() {
static const char kDebugPluginLoading[] = "debug-plugin-loading";
return CommandLine::ForCurrentProcess()->HasSwitch(kDebugPluginLoading);
}
// We build up a list of files and mtimes so we can sort them.
typedef std::pair<FilePath, base::Time> FileAndTime;
typedef std::vector<FileAndTime> FileTimeList;
// Comparator used to sort by descending mtime then ascending filename.
bool CompareTime(const FileAndTime& a, const FileAndTime& b) {
if (a.second == b.second) {
// Fall back on filename sorting, just to make the predicate valid.
return a.first < b.first;
}
// Sort by mtime, descending.
return a.second > b.second;
}
// Some plugins are shells around other plugins; we prefer to use the
// real plugin directly, if it's available. This function returns
// true if we should prefer other plugins over this one. We'll still
// use a "undesirable" plugin if no other option is available.
bool IsUndesirablePlugin(const WebPluginInfo& info) {
std::string filename = info.path.BaseName().value();
return (filename.find("npcxoffice") != std::string::npos || // Crossover
filename.find("npwrapper") != std::string::npos); // nspluginwrapper
}
} // anonymous namespace
namespace NPAPI {
void PluginList::PlatformInit() {
}
void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
// See http://groups.google.com/group/chromium-dev/browse_thread/thread/7a70e5fcbac786a9
// for discussion.
// We first consult Chrome-specific dirs, then fall back on the logic
// Mozilla uses.
// TODO(evanm): maybe consult our own plugins dir, like
// ~/.config/chromium/Plugins?
// The Chrome binary dir + "plugins/".
FilePath dir;
PathService::Get(base::DIR_EXE, &dir);
plugin_dirs->push_back(dir.Append("plugins"));
// Mozilla code to reference:
// http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
// and tens of accompanying files (mxr is very helpful).
// This code carefully matches their behavior for compat reasons.
// 1) MOZ_PLUGIN_PATH env variable.
const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
if (moz_plugin_path) {
std::vector<std::string> paths;
SplitString(moz_plugin_path, ':', &paths);
for (size_t i = 0; i < paths.size(); ++i)
plugin_dirs->push_back(FilePath(paths[i]));
}
// 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
// This is a de-facto standard, so even though we're not Mozilla, let's
// look in there too.
const char* home = getenv("HOME");
if (home)
plugin_dirs->push_back(FilePath(home).Append(".mozilla/plugins"));
// 3) NS_SYSTEM_PLUGINS_DIR:
// This varies across different browsers and versions, so check 'em all.
plugin_dirs->push_back(FilePath("/usr/lib/browser-plugins"));
plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib/firefox/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib/xulrunner-addons/plugins"));
#if defined(ARCH_CPU_64_BITS)
// On my Ubuntu system, /usr/lib64 is a symlink to /usr/lib.
// But a user reported on their Fedora system they are separate.
plugin_dirs->push_back(FilePath("/usr/lib64/browser-plugins"));
plugin_dirs->push_back(FilePath("/usr/lib64/mozilla/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib64/firefox/plugins"));
plugin_dirs->push_back(FilePath("/usr/lib64/xulrunner-addons/plugins"));
#endif
}
void PluginList::LoadPluginsFromDir(const FilePath& path,
std::vector<WebPluginInfo>* plugins) {
// See ScanPluginsDirectory near
// http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginHostImpl.cpp#5052
// Construct and stat a list of all filenames under consideration, for
// later sorting by mtime.
FileTimeList files;
file_util::FileEnumerator enumerator(path,
false, // not recursive
file_util::FileEnumerator::FILES);
for (FilePath path = enumerator.Next(); !path.value().empty();
path = enumerator.Next()) {
// Skip over Mozilla .xpt files.
if (path.MatchesExtension(FILE_PATH_LITERAL(".xpt")))
continue;
// Java doesn't like being loaded through a symlink, since it uses
// its path to find dependent data files.
// file_util::AbsolutePath calls through to realpath(), which resolves
// symlinks.
FilePath orig_path = path;
file_util::AbsolutePath(&path);
if (DebugPluginLoading())
LOG(ERROR) << "Resolved " << orig_path.value() << " -> " << path.value();
// Flash stops working if the containing directory involves 'netscape'.
// No joke. So use the other path if it's better.
static const char kFlashPlayerFilename[] = "libflashplayer.so";
static const char kNetscapeInPath[] = "/netscape/";
if (path.BaseName().value() == kFlashPlayerFilename &&
path.value().find(kNetscapeInPath) != std::string::npos) {
if (orig_path.value().find(kNetscapeInPath) == std::string::npos) {
// Go back to the old path.
path = orig_path;
} else {
LOG(ERROR) << "Flash misbehaves when used from a directory containing "
<< kNetscapeInPath << ", so skipping " << orig_path.value();
continue;
}
}
// Get mtime.
file_util::FileInfo info;
if (!file_util::GetFileInfo(path, &info))
continue;
// Skip duplicates of the same file in our list.
bool skip = false;
for (size_t i = 0; i < plugins->size(); ++i) {
if (plugins->at(i).path == path) {
skip = true;
break;
}
}
if (skip) {
if (DebugPluginLoading())
LOG(ERROR) << "Skipping duplicate instance of " << path.value();
continue;
}
files.push_back(std::make_pair(path, info.last_modified));
}
// Sort the file list by time (and filename).
std::sort(files.begin(), files.end(), CompareTime);
// Load the files in order.
for (FileTimeList::const_iterator i = files.begin(); i != files.end(); ++i) {
LoadPlugin(i->first, plugins);
}
}
bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info,
std::vector<WebPluginInfo>* plugins) {
if (DebugPluginLoading()) {
LOG(ERROR) << "Considering " << info.path.value()
<< " (" << info.name << ")";
}
if (IsUndesirablePlugin(info)) {
if (DebugPluginLoading())
LOG(ERROR) << info.path.value() << " is undesirable.";
// See if we have a better version of this plugin.
for (size_t i = 0; i < plugins->size(); ++i) {
if (plugins->at(i).name == info.name &&
!IsUndesirablePlugin(plugins->at(i))) {
// Skip the current undesirable one so we can use the better one
// we just found.
if (DebugPluginLoading()) {
LOG(ERROR) << "Skipping " << info.path.value() << ", preferring "
<< plugins->at(i).path.value();
}
return false;
}
}
}
// TODO(evanm): prefer the newest version of flash, etc. here?
if (DebugPluginLoading())
LOG(ERROR) << "Using " << info.path.value();
return true;
}
} // namespace NPAPI
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2017 Axel Waggershauser
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 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 "common/DngOpcodes.h"
#include "common/Common.h" // for uint32, ushort16, make_unique
#include "common/Point.h" // for iPoint2D, iRectangle2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getHostEndianness, Endiann...
#include "tiff/TiffEntry.h" // for TiffEntry
#include <algorithm> // for fill_n
#include <cmath> // for pow
using std::vector;
using std::fill_n;
namespace rawspeed {
class DngOpcodes::DngOpcode {
public:
virtual ~DngOpcode() = default;
// Will be called once before processing.
// Can be used for preparing pre-calculated values, etc.
virtual void setup(const RawImage& ri) {
// NOP by default. child class shall override this if needed.
}
// Will be called for actual processing.
virtual void apply(RawImage& ri) = 0;
};
// ****************************************************************************
class DngOpcodes::FixBadPixelsConstant final : public DngOpcodes::DngOpcode {
uint32 value;
public:
explicit FixBadPixelsConstant(ByteStream& bs) {
value = bs.getU32();
bs.getU32(); // Bayer Phase not used
}
void setup(const RawImage& ri) override {
// These limitations are present within the DNG SDK as well.
if (ri->getDataType() != TYPE_USHORT16)
ThrowRDE("Only 16 bit images supported");
if (ri->getCpp() > 1)
ThrowRDE("Only 1 component images supported");
}
void apply(RawImage& ri) override {
iPoint2D crop = ri->getCropOffset();
uint32 offset = crop.x | (crop.y << 16);
for (auto y = 0; y < ri->dim.y; ++y) {
auto* src = reinterpret_cast<ushort16*>(ri->getData(0, y));
for (auto x = 0; x < ri->dim.x; ++x) {
if (src[x] == value)
ri->mBadPixelPositions.push_back(offset + (y << 16 | x));
}
}
}
};
// ****************************************************************************
class DngOpcodes::FixBadPixelsList final : public DngOpcodes::DngOpcode {
std::vector<uint32> badPixels;
public:
explicit FixBadPixelsList(ByteStream& bs) {
bs.getU32(); // Skip phase - we don't care
auto badPointCount = bs.getU32();
auto badRectCount = bs.getU32();
// Read points
for (auto i = 0U; i < badPointCount; ++i) {
auto y = bs.getU32();
auto x = bs.getU32();
badPixels.push_back(y << 16 | x);
}
// Read rects
for (auto i = 0U; i < badRectCount; ++i) {
auto top = bs.getU32();
auto left = bs.getU32();
auto bottom = bs.getU32();
auto right = bs.getU32();
for (auto y = top; y <= bottom; ++y) {
for (auto x = left; x <= right; ++x) {
badPixels.push_back(y << 16 | x);
}
}
}
}
void apply(RawImage& ri) override {
ri->mBadPixelPositions.insert(ri->mBadPixelPositions.begin(),
badPixels.begin(), badPixels.end());
}
};
// ****************************************************************************
class DngOpcodes::ROIOpcode : public DngOpcodes::DngOpcode {
protected:
uint32 top, left, bottom, right;
explicit ROIOpcode(ByteStream& bs) {
top = bs.getU32();
left = bs.getU32();
bottom = bs.getU32();
right = bs.getU32();
}
void setup(const RawImage& ri) override {
iRectangle2D roi(left, top, right - left, bottom - top);
iRectangle2D fullImage(0, 0, ri->dim.x, ri->dim.y);
if (!roi.isThisInside(fullImage))
ThrowRDE("Area of interest not inside image.");
}
};
// ****************************************************************************
class DngOpcodes::TrimBounds final : public ROIOpcode {
public:
explicit TrimBounds(ByteStream& bs) : ROIOpcode(bs) {}
void apply(RawImage& ri) override {
ri->subFrame(iRectangle2D(left, top, right - left, bottom - top));
}
};
// ****************************************************************************
class DngOpcodes::PixelOpcode : public ROIOpcode {
protected:
uint32 firstPlane, planes, rowPitch, colPitch;
explicit PixelOpcode(ByteStream& bs) : ROIOpcode(bs) {
firstPlane = bs.getU32();
planes = bs.getU32();
rowPitch = bs.getU32();
colPitch = bs.getU32();
if (planes == 0)
ThrowRDE("Zero planes");
if (rowPitch == 0 || colPitch == 0)
ThrowRDE("Invalid pitch");
}
void setup(const RawImage& ri) override {
ROIOpcode::setup(ri);
if (firstPlane + planes > ri->getCpp())
ThrowRDE("Not that many planes in actual image");
}
// traverses the current ROI and applies the operation OP to each pixel,
// i.e. each pixel value v is replaced by op(x, y, v), where x/y are the
// coordinates of the pixel value v.
template <typename T, typename OP> void applyOP(RawImage& ri, OP op) {
int cpp = ri->getCpp();
for (auto y = top; y < bottom; y += rowPitch) {
auto* src = reinterpret_cast<T*>(ri->getData(0, y));
// Add offset, so this is always first plane
src += firstPlane;
for (auto x = left; x < right; x += colPitch) {
for (auto p = 0U; p < planes; ++p)
src[x * cpp + p] = op(x, y, src[x * cpp + p]);
}
}
}
};
// ****************************************************************************
class DngOpcodes::LookupOpcode : public PixelOpcode {
protected:
vector<ushort16> lookup;
explicit LookupOpcode(ByteStream& bs) : PixelOpcode(bs), lookup(65536) {}
void setup(const RawImage& ri) override {
PixelOpcode::setup(ri);
if (ri->getDataType() != TYPE_USHORT16)
ThrowRDE("Only 16 bit images supported");
}
void apply(RawImage& ri) override {
applyOP<ushort16>(
ri, [this](uint32 x, uint32 y, ushort16 v) { return lookup[v]; });
}
};
// ****************************************************************************
class DngOpcodes::TableMap final : public LookupOpcode {
public:
explicit TableMap(ByteStream& bs) : LookupOpcode(bs) {
auto count = bs.getU32();
if (count == 0 || count > 65536)
ThrowRDE("Invalid size of lookup table");
for (auto i = 0U; i < count; ++i)
lookup[i] = bs.getU16();
if (count < lookup.size())
fill_n(&lookup[count], lookup.size() - count, lookup[count - 1]);
}
};
// ****************************************************************************
class DngOpcodes::PolynomialMap final : public LookupOpcode {
public:
explicit PolynomialMap(ByteStream& bs) : LookupOpcode(bs) {
vector<double> polynomial;
polynomial.resize(bs.getU32() + 1UL);
if (polynomial.size() > 9)
ThrowRDE("A polynomial with more than 8 degrees not allowed");
for (auto& coeff : polynomial)
coeff = bs.get<double>();
// Create lookup
lookup.resize(65536);
for (auto i = 0U; i < lookup.size(); ++i) {
double val = polynomial[0];
for (auto j = 1U; j < polynomial.size(); ++j)
val += polynomial[j] * pow(i / 65536.0, j);
lookup[i] = (clampBits(static_cast<int>(val * 65535.5), 16));
}
}
};
// ****************************************************************************
class DngOpcodes::DeltaRowOrColBase : public PixelOpcode {
public:
struct SelectX {
static inline uint32 select(uint32 x, uint32 y) { return x; }
};
struct SelectY {
static inline uint32 select(uint32 x, uint32 y) { return y; }
};
protected:
vector<float> deltaF;
vector<int> deltaI;
DeltaRowOrColBase(ByteStream& bs, float f2iScale) : PixelOpcode(bs) {
deltaF.resize(bs.getU32());
for (auto& f : deltaF)
f = bs.get<float>();
deltaI.reserve(deltaF.size());
for (auto f : deltaF)
deltaI.emplace_back(static_cast<int>(f2iScale * f));
}
};
// ****************************************************************************
template <typename S>
class DngOpcodes::OffsetPerRowOrCol final : public DeltaRowOrColBase {
public:
explicit OffsetPerRowOrCol(ByteStream& bs)
: DeltaRowOrColBase(bs, 65535.0F) {}
void apply(RawImage& ri) override {
if (ri->getDataType() == TYPE_USHORT16) {
applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
return clampBits(deltaI[S::select(x, y)] + v, 16);
});
} else {
applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
return deltaF[S::select(x, y)] + v;
});
}
}
};
template <typename S>
class DngOpcodes::ScalePerRowOrCol final : public DeltaRowOrColBase {
public:
explicit ScalePerRowOrCol(ByteStream& bs) : DeltaRowOrColBase(bs, 1024.0F) {}
void apply(RawImage& ri) override {
if (ri->getDataType() == TYPE_USHORT16) {
applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
return clampBits((deltaI[S::select(x, y)] * v + 512) >> 10, 16);
});
} else {
applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
return deltaF[S::select(x, y)] * v;
});
}
}
};
// ****************************************************************************
DngOpcodes::DngOpcodes(TiffEntry* entry) {
ByteStream bs = entry->getData();
// DNG opcodes seem to be always stored in big endian
bs.setInNativeByteOrder(getHostEndianness() == big);
using OffsetPerRow = OffsetPerRowOrCol<DeltaRowOrColBase::SelectY>;
using OffsetPerCol = OffsetPerRowOrCol<DeltaRowOrColBase::SelectX>;
using ScalePerRow = ScalePerRowOrCol<DeltaRowOrColBase::SelectY>;
using ScalePerCol = ScalePerRowOrCol<DeltaRowOrColBase::SelectX>;
auto opcode_count = bs.getU32();
for (auto i = 0U; i < opcode_count; i++) {
auto code = bs.getU32();
bs.getU32(); // ignore version
auto flags = bs.getU32();
auto expected_pos = bs.getU32() + bs.getPosition();
switch (code) {
case 4:
opcodes.push_back(make_unique<FixBadPixelsConstant>(bs));
break;
case 5:
opcodes.push_back(make_unique<FixBadPixelsList>(bs));
break;
case 6:
opcodes.push_back(make_unique<TrimBounds>(bs));
break;
case 7:
opcodes.push_back(make_unique<TableMap>(bs));
break;
case 8:
opcodes.push_back(make_unique<PolynomialMap>(bs));
break;
case 10:
opcodes.push_back(make_unique<OffsetPerRow>(bs));
break;
case 11:
opcodes.push_back(make_unique<OffsetPerCol>(bs));
break;
case 12:
opcodes.push_back(make_unique<ScalePerRow>(bs));
break;
case 13:
opcodes.push_back(make_unique<ScalePerCol>(bs));
break;
default:
// Throw Error if not marked as optional
if (!(flags & 1))
ThrowRDE("Unsupported Opcode: %d", code);
}
if (bs.getPosition() != expected_pos)
ThrowRDE("Inconsistent length of opcode");
}
}
// defined here as empty destrutor, otherwise we'd need a complete definition
// of the the DngOpcode type in DngOpcodes.h
DngOpcodes::~DngOpcodes() = default;
void DngOpcodes::applyOpCodes(RawImage& ri) {
for (const auto& code : opcodes) {
code->setup(ri);
code->apply(ri);
}
}
} // namespace rawspeed
<commit_msg>DngOpcodes::DeltaRowOrColBase(): remove unused function parameter<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2017 Axel Waggershauser
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 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 "common/DngOpcodes.h"
#include "common/Common.h" // for uint32, ushort16, make_unique
#include "common/Point.h" // for iPoint2D, iRectangle2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getHostEndianness, Endiann...
#include "tiff/TiffEntry.h" // for TiffEntry
#include <algorithm> // for fill_n
#include <cmath> // for pow
using std::vector;
using std::fill_n;
namespace rawspeed {
class DngOpcodes::DngOpcode {
public:
virtual ~DngOpcode() = default;
// Will be called once before processing.
// Can be used for preparing pre-calculated values, etc.
virtual void setup(const RawImage& ri) {
// NOP by default. child class shall override this if needed.
}
// Will be called for actual processing.
virtual void apply(RawImage& ri) = 0;
};
// ****************************************************************************
class DngOpcodes::FixBadPixelsConstant final : public DngOpcodes::DngOpcode {
uint32 value;
public:
explicit FixBadPixelsConstant(ByteStream& bs) {
value = bs.getU32();
bs.getU32(); // Bayer Phase not used
}
void setup(const RawImage& ri) override {
// These limitations are present within the DNG SDK as well.
if (ri->getDataType() != TYPE_USHORT16)
ThrowRDE("Only 16 bit images supported");
if (ri->getCpp() > 1)
ThrowRDE("Only 1 component images supported");
}
void apply(RawImage& ri) override {
iPoint2D crop = ri->getCropOffset();
uint32 offset = crop.x | (crop.y << 16);
for (auto y = 0; y < ri->dim.y; ++y) {
auto* src = reinterpret_cast<ushort16*>(ri->getData(0, y));
for (auto x = 0; x < ri->dim.x; ++x) {
if (src[x] == value)
ri->mBadPixelPositions.push_back(offset + (y << 16 | x));
}
}
}
};
// ****************************************************************************
class DngOpcodes::FixBadPixelsList final : public DngOpcodes::DngOpcode {
std::vector<uint32> badPixels;
public:
explicit FixBadPixelsList(ByteStream& bs) {
bs.getU32(); // Skip phase - we don't care
auto badPointCount = bs.getU32();
auto badRectCount = bs.getU32();
// Read points
for (auto i = 0U; i < badPointCount; ++i) {
auto y = bs.getU32();
auto x = bs.getU32();
badPixels.push_back(y << 16 | x);
}
// Read rects
for (auto i = 0U; i < badRectCount; ++i) {
auto top = bs.getU32();
auto left = bs.getU32();
auto bottom = bs.getU32();
auto right = bs.getU32();
for (auto y = top; y <= bottom; ++y) {
for (auto x = left; x <= right; ++x) {
badPixels.push_back(y << 16 | x);
}
}
}
}
void apply(RawImage& ri) override {
ri->mBadPixelPositions.insert(ri->mBadPixelPositions.begin(),
badPixels.begin(), badPixels.end());
}
};
// ****************************************************************************
class DngOpcodes::ROIOpcode : public DngOpcodes::DngOpcode {
protected:
uint32 top, left, bottom, right;
explicit ROIOpcode(ByteStream& bs) {
top = bs.getU32();
left = bs.getU32();
bottom = bs.getU32();
right = bs.getU32();
}
void setup(const RawImage& ri) override {
iRectangle2D roi(left, top, right - left, bottom - top);
iRectangle2D fullImage(0, 0, ri->dim.x, ri->dim.y);
if (!roi.isThisInside(fullImage))
ThrowRDE("Area of interest not inside image.");
}
};
// ****************************************************************************
class DngOpcodes::TrimBounds final : public ROIOpcode {
public:
explicit TrimBounds(ByteStream& bs) : ROIOpcode(bs) {}
void apply(RawImage& ri) override {
ri->subFrame(iRectangle2D(left, top, right - left, bottom - top));
}
};
// ****************************************************************************
class DngOpcodes::PixelOpcode : public ROIOpcode {
protected:
uint32 firstPlane, planes, rowPitch, colPitch;
explicit PixelOpcode(ByteStream& bs) : ROIOpcode(bs) {
firstPlane = bs.getU32();
planes = bs.getU32();
rowPitch = bs.getU32();
colPitch = bs.getU32();
if (planes == 0)
ThrowRDE("Zero planes");
if (rowPitch == 0 || colPitch == 0)
ThrowRDE("Invalid pitch");
}
void setup(const RawImage& ri) override {
ROIOpcode::setup(ri);
if (firstPlane + planes > ri->getCpp())
ThrowRDE("Not that many planes in actual image");
}
// traverses the current ROI and applies the operation OP to each pixel,
// i.e. each pixel value v is replaced by op(x, y, v), where x/y are the
// coordinates of the pixel value v.
template <typename T, typename OP> void applyOP(RawImage& ri, OP op) {
int cpp = ri->getCpp();
for (auto y = top; y < bottom; y += rowPitch) {
auto* src = reinterpret_cast<T*>(ri->getData(0, y));
// Add offset, so this is always first plane
src += firstPlane;
for (auto x = left; x < right; x += colPitch) {
for (auto p = 0U; p < planes; ++p)
src[x * cpp + p] = op(x, y, src[x * cpp + p]);
}
}
}
};
// ****************************************************************************
class DngOpcodes::LookupOpcode : public PixelOpcode {
protected:
vector<ushort16> lookup;
explicit LookupOpcode(ByteStream& bs) : PixelOpcode(bs), lookup(65536) {}
void setup(const RawImage& ri) override {
PixelOpcode::setup(ri);
if (ri->getDataType() != TYPE_USHORT16)
ThrowRDE("Only 16 bit images supported");
}
void apply(RawImage& ri) override {
applyOP<ushort16>(
ri, [this](uint32 x, uint32 y, ushort16 v) { return lookup[v]; });
}
};
// ****************************************************************************
class DngOpcodes::TableMap final : public LookupOpcode {
public:
explicit TableMap(ByteStream& bs) : LookupOpcode(bs) {
auto count = bs.getU32();
if (count == 0 || count > 65536)
ThrowRDE("Invalid size of lookup table");
for (auto i = 0U; i < count; ++i)
lookup[i] = bs.getU16();
if (count < lookup.size())
fill_n(&lookup[count], lookup.size() - count, lookup[count - 1]);
}
};
// ****************************************************************************
class DngOpcodes::PolynomialMap final : public LookupOpcode {
public:
explicit PolynomialMap(ByteStream& bs) : LookupOpcode(bs) {
vector<double> polynomial;
polynomial.resize(bs.getU32() + 1UL);
if (polynomial.size() > 9)
ThrowRDE("A polynomial with more than 8 degrees not allowed");
for (auto& coeff : polynomial)
coeff = bs.get<double>();
// Create lookup
lookup.resize(65536);
for (auto i = 0U; i < lookup.size(); ++i) {
double val = polynomial[0];
for (auto j = 1U; j < polynomial.size(); ++j)
val += polynomial[j] * pow(i / 65536.0, j);
lookup[i] = (clampBits(static_cast<int>(val * 65535.5), 16));
}
}
};
// ****************************************************************************
class DngOpcodes::DeltaRowOrColBase : public PixelOpcode {
public:
struct SelectX {
static inline uint32 select(uint32 x, uint32 /*y*/) { return x; }
};
struct SelectY {
static inline uint32 select(uint32 /*x*/, uint32 y) { return y; }
};
protected:
vector<float> deltaF;
vector<int> deltaI;
DeltaRowOrColBase(ByteStream& bs, float f2iScale) : PixelOpcode(bs) {
deltaF.resize(bs.getU32());
for (auto& f : deltaF)
f = bs.get<float>();
deltaI.reserve(deltaF.size());
for (auto f : deltaF)
deltaI.emplace_back(static_cast<int>(f2iScale * f));
}
};
// ****************************************************************************
template <typename S>
class DngOpcodes::OffsetPerRowOrCol final : public DeltaRowOrColBase {
public:
explicit OffsetPerRowOrCol(ByteStream& bs)
: DeltaRowOrColBase(bs, 65535.0F) {}
void apply(RawImage& ri) override {
if (ri->getDataType() == TYPE_USHORT16) {
applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
return clampBits(deltaI[S::select(x, y)] + v, 16);
});
} else {
applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
return deltaF[S::select(x, y)] + v;
});
}
}
};
template <typename S>
class DngOpcodes::ScalePerRowOrCol final : public DeltaRowOrColBase {
public:
explicit ScalePerRowOrCol(ByteStream& bs) : DeltaRowOrColBase(bs, 1024.0F) {}
void apply(RawImage& ri) override {
if (ri->getDataType() == TYPE_USHORT16) {
applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
return clampBits((deltaI[S::select(x, y)] * v + 512) >> 10, 16);
});
} else {
applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
return deltaF[S::select(x, y)] * v;
});
}
}
};
// ****************************************************************************
DngOpcodes::DngOpcodes(TiffEntry* entry) {
ByteStream bs = entry->getData();
// DNG opcodes seem to be always stored in big endian
bs.setInNativeByteOrder(getHostEndianness() == big);
using OffsetPerRow = OffsetPerRowOrCol<DeltaRowOrColBase::SelectY>;
using OffsetPerCol = OffsetPerRowOrCol<DeltaRowOrColBase::SelectX>;
using ScalePerRow = ScalePerRowOrCol<DeltaRowOrColBase::SelectY>;
using ScalePerCol = ScalePerRowOrCol<DeltaRowOrColBase::SelectX>;
auto opcode_count = bs.getU32();
for (auto i = 0U; i < opcode_count; i++) {
auto code = bs.getU32();
bs.getU32(); // ignore version
auto flags = bs.getU32();
auto expected_pos = bs.getU32() + bs.getPosition();
switch (code) {
case 4:
opcodes.push_back(make_unique<FixBadPixelsConstant>(bs));
break;
case 5:
opcodes.push_back(make_unique<FixBadPixelsList>(bs));
break;
case 6:
opcodes.push_back(make_unique<TrimBounds>(bs));
break;
case 7:
opcodes.push_back(make_unique<TableMap>(bs));
break;
case 8:
opcodes.push_back(make_unique<PolynomialMap>(bs));
break;
case 10:
opcodes.push_back(make_unique<OffsetPerRow>(bs));
break;
case 11:
opcodes.push_back(make_unique<OffsetPerCol>(bs));
break;
case 12:
opcodes.push_back(make_unique<ScalePerRow>(bs));
break;
case 13:
opcodes.push_back(make_unique<ScalePerCol>(bs));
break;
default:
// Throw Error if not marked as optional
if (!(flags & 1))
ThrowRDE("Unsupported Opcode: %d", code);
}
if (bs.getPosition() != expected_pos)
ThrowRDE("Inconsistent length of opcode");
}
}
// defined here as empty destrutor, otherwise we'd need a complete definition
// of the the DngOpcode type in DngOpcodes.h
DngOpcodes::~DngOpcodes() = default;
void DngOpcodes::applyOpCodes(RawImage& ri) {
for (const auto& code : opcodes) {
code->setup(ri);
code->apply(ri);
}
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
vcyou may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/hexagon/hexagon_ops_definitions.h"
#include <unordered_map>
#include "tensorflow/core/framework/types.h"
namespace tensorflow {
enum class SupportedOpType {
INPUT,
OUTPUT,
NOP,
CONST,
CHECK,
CLOSE_FLOAT32,
CLOSE_QINT8,
CLOSE_Q_QINT8,
CLOSE_INT32,
CLOSE_QINT32,
PPRINT_8,
PPRINT_32,
PPRINT_FLOAT,
PREFREE,
FLATTEN,
QUANTIZEDCONV2D_8X8TO32,
QUANTIZEDCONV2D_8X8TO32_REF,
QUANTIZEDMATMUL_8X8TO32,
QUANTIZEDMATMUL_8X8TO32_REF,
QUANTIZEDOWNANDSHRINKRANGE_32TO8,
QUANTIZEDOWNANDSHRINKRANGE_32TO8_REF,
QUANTIZEDRELU_8,
QUANTIZEDRELU_8_REF,
QUANTIZEDRELUX_8,
QUANTIZEDRELUX_8_REF,
QUANTIZEDMAXPOOL_8,
QUANTIZEDMAXPOOL_8_REF,
QUANTIZEDAVGPOOL_8,
QUANTIZEDAVGPOOL_8_REF,
QUANTIZEDCONCAT_8,
QUANTIZEDCONCAT_8_REF,
QUANTIZEDBIASADD_8P8TO32,
QUANTIZEDBIASADD_8P8TO32_REF,
MIN_F,
MIN_F_REF,
MAX_F,
MAX_F_REF,
QUANTIZE,
QUANTIZE_REF,
DEQUANTIZE,
DEQUANTIZE_REF,
SUPERNODE_8X8P8TO8,
SUPERNODE_8X8P8TO8_REF,
QUANTIZEDFLATTEN,
SUPPORTED_OP_TYPE_COUNT,
};
static const std::unordered_map<string, SupportedOpType>
OP_NAME_TO_SOC_OP_TYPE_MAP{
// Custom Op name
{IGraphTransferOpsDefinitions::INPUT_OP_NAME, SupportedOpType::INPUT},
{IGraphTransferOpsDefinitions::OUTPUT_OP_NAME, SupportedOpType::OUTPUT},
// Tensorflow op name
{"QuantizedConv2D", SupportedOpType::QUANTIZEDCONV2D_8X8TO32},
{"QuantizedMatMul", SupportedOpType::QUANTIZEDMATMUL_8X8TO32},
{"QuantizeDownAndShrinkRange",
SupportedOpType::QUANTIZEDOWNANDSHRINKRANGE_32TO8},
{"QuantizedRelu", SupportedOpType::QUANTIZEDRELU_8},
{"QuantizedReluX", SupportedOpType::QUANTIZEDRELUX_8},
{"QuantizedMaxPool", SupportedOpType::QUANTIZEDMAXPOOL_8},
{"QuantizedAvgPool", SupportedOpType::QUANTIZEDAVGPOOL_8},
{"QuantizedConcat", SupportedOpType::QUANTIZEDCONCAT_8},
{"QuantizedBiasAdd", SupportedOpType::QUANTIZEDBIASADD_8P8TO32},
{"Min", SupportedOpType::MIN_F},
{"Max", SupportedOpType::MAX_F},
{"QuantizeV2", SupportedOpType::QUANTIZE},
};
/* static */ const IGraphTransferOpsDefinitions&
HexagonOpsDefinitions::getInstance() {
const static HexagonOpsDefinitions instance{};
return instance;
}
int HexagonOpsDefinitions::GetTotalOpsCount() const {
return static_cast<int>(SupportedOpType::SUPPORTED_OP_TYPE_COUNT);
}
int HexagonOpsDefinitions::GetInputNodeOpId() const {
return static_cast<int>(SupportedOpType::INPUT);
}
int HexagonOpsDefinitions::GetOutputNodeOpId() const {
return static_cast<int>(SupportedOpType::OUTPUT);
}
int HexagonOpsDefinitions::GetOpIdFor(const string& op_type) const {
if (OP_NAME_TO_SOC_OP_TYPE_MAP.count(op_type) > 0) {
return static_cast<int>(OP_NAME_TO_SOC_OP_TYPE_MAP.at(op_type));
}
return IGraphTransferOpsDefinitions::INVALID_OP_ID;
}
};
<commit_msg>Fix windows cmake build by replacing enum class by enum Change: 138409704<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
vcyou may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/hexagon/hexagon_ops_definitions.h"
#include <unordered_map>
#include "tensorflow/core/framework/types.h"
namespace tensorflow {
enum class SupportedOpType {
INPUT,
OUTPUT,
NOP,
OP_CONST, /* OP_ is required to avoid compilation error on windows */
CHECK,
CLOSE_FLOAT32,
CLOSE_QINT8,
CLOSE_Q_QINT8,
CLOSE_INT32,
CLOSE_QINT32,
PPRINT_8,
PPRINT_32,
PPRINT_FLOAT,
PREFREE,
FLATTEN,
QUANTIZEDCONV2D_8X8TO32,
QUANTIZEDCONV2D_8X8TO32_REF,
QUANTIZEDMATMUL_8X8TO32,
QUANTIZEDMATMUL_8X8TO32_REF,
QUANTIZEDOWNANDSHRINKRANGE_32TO8,
QUANTIZEDOWNANDSHRINKRANGE_32TO8_REF,
QUANTIZEDRELU_8,
QUANTIZEDRELU_8_REF,
QUANTIZEDRELUX_8,
QUANTIZEDRELUX_8_REF,
QUANTIZEDMAXPOOL_8,
QUANTIZEDMAXPOOL_8_REF,
QUANTIZEDAVGPOOL_8,
QUANTIZEDAVGPOOL_8_REF,
QUANTIZEDCONCAT_8,
QUANTIZEDCONCAT_8_REF,
QUANTIZEDBIASADD_8P8TO32,
QUANTIZEDBIASADD_8P8TO32_REF,
MIN_F,
MIN_F_REF,
MAX_F,
MAX_F_REF,
QUANTIZE,
QUANTIZE_REF,
DEQUANTIZE,
DEQUANTIZE_REF,
SUPERNODE_8X8P8TO8,
SUPERNODE_8X8P8TO8_REF,
QUANTIZEDFLATTEN,
SUPPORTED_OP_TYPE_COUNT,
};
static const std::unordered_map<string, SupportedOpType>
OP_NAME_TO_SOC_OP_TYPE_MAP{
// Custom Op name
{IGraphTransferOpsDefinitions::INPUT_OP_NAME, SupportedOpType::INPUT},
{IGraphTransferOpsDefinitions::OUTPUT_OP_NAME, SupportedOpType::OUTPUT},
// Tensorflow op name
{"QuantizedConv2D", SupportedOpType::QUANTIZEDCONV2D_8X8TO32},
{"QuantizedMatMul", SupportedOpType::QUANTIZEDMATMUL_8X8TO32},
{"QuantizeDownAndShrinkRange",
SupportedOpType::QUANTIZEDOWNANDSHRINKRANGE_32TO8},
{"QuantizedRelu", SupportedOpType::QUANTIZEDRELU_8},
{"QuantizedReluX", SupportedOpType::QUANTIZEDRELUX_8},
{"QuantizedMaxPool", SupportedOpType::QUANTIZEDMAXPOOL_8},
{"QuantizedAvgPool", SupportedOpType::QUANTIZEDAVGPOOL_8},
{"QuantizedConcat", SupportedOpType::QUANTIZEDCONCAT_8},
{"QuantizedBiasAdd", SupportedOpType::QUANTIZEDBIASADD_8P8TO32},
{"Min", SupportedOpType::MIN_F},
{"Max", SupportedOpType::MAX_F},
{"QuantizeV2", SupportedOpType::QUANTIZE},
};
/* static */ const IGraphTransferOpsDefinitions&
HexagonOpsDefinitions::getInstance() {
const static HexagonOpsDefinitions instance{};
return instance;
}
int HexagonOpsDefinitions::GetTotalOpsCount() const {
return static_cast<int>(SupportedOpType::SUPPORTED_OP_TYPE_COUNT);
}
int HexagonOpsDefinitions::GetInputNodeOpId() const {
return static_cast<int>(SupportedOpType::INPUT);
}
int HexagonOpsDefinitions::GetOutputNodeOpId() const {
return static_cast<int>(SupportedOpType::OUTPUT);
}
int HexagonOpsDefinitions::GetOpIdFor(const string& op_type) const {
if (OP_NAME_TO_SOC_OP_TYPE_MAP.count(op_type) > 0) {
return static_cast<int>(OP_NAME_TO_SOC_OP_TYPE_MAP.at(op_type));
}
return IGraphTransferOpsDefinitions::INVALID_OP_ID;
}
};
<|endoftext|> |
<commit_before>/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Jean-David Gadina - www.xs-labs.com / www.digidna.net
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
/*!
* @copyright (c) 2015 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
* @brief ...
*/
/* Disabled warnings for GoogleMock */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic push
#if __clang_major__ >= 7
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
#include <GoogleMock/GoogleMock.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <XS/Atomic-Functions.hpp>
using namespace testing;
TEST( XS_Atomic_Functions, AtomicIncrement32 )
{
int32_t i = 0;
ASSERT_EQ( XS::AtomicIncrement32( &i ), 1 );
ASSERT_EQ( i, 1 );
}
TEST( XS_Atomic_Functions, AtomicIncrement64 )
{
int64_t i = 0;
ASSERT_EQ( XS::AtomicIncrement64( &i ), 1 );
ASSERT_EQ( i, 1 );
}
TEST( XS_Atomic_Functions, AtomicDecrement32 )
{
int32_t i = 0;
ASSERT_EQ( XS::AtomicDecrement32( &i ), -1 );
ASSERT_EQ( i, -1 );
}
TEST( XS_Atomic_Functions, AtomicDecrement64 )
{
int64_t i = 0;
ASSERT_EQ( XS::AtomicDecrement64( &i ), -1 );
ASSERT_EQ( i, -1 );
}
TEST( XS_Atomic_Functions, AtomicAdd32 )
{
int32_t i = 0;
ASSERT_EQ( XS::AtomicAdd32( 2, &i ), 2 );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicAdd64 )
{
int64_t i = 0;
ASSERT_EQ( XS::AtomicAdd64( 2, &i ), 2 );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicCompareAndSwap32 )
{
int32_t i = 0;
ASSERT_FALSE( XS::AtomicCompareAndSwap32( 1, 2, &i ) );
ASSERT_TRUE( XS::AtomicCompareAndSwap32( 0, 2, &i ) );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicCompareAndSwap64 )
{
int64_t i = 0;
ASSERT_FALSE( XS::AtomicCompareAndSwap64( 1, 2, &i ) );
ASSERT_TRUE( XS::AtomicCompareAndSwap64( 0, 2, &i ) );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicCompareAndSwapPointer )
{
void * p = nullptr;
ASSERT_FALSE( XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 1 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
ASSERT_TRUE( XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 0 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
ASSERT_EQ( p, reinterpret_cast< void * >( 2 ) );
}
<commit_msg>Unit tests...<commit_after>/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Jean-David Gadina - www.xs-labs.com / www.digidna.net
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
/*!
* @copyright (c) 2015 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
* @brief ...
*/
/* Disabled warnings for GoogleMock */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic push
#if __clang_major__ >= 7
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
#include <GoogleMock/GoogleMock.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <XS/Atomic-Functions.hpp>
using namespace testing;
TEST( XS_Atomic_Functions, AtomicIncrement32 )
{
int32_t i = 0;
ASSERT_EQ( XS::AtomicIncrement32( &i ), 1 );
ASSERT_EQ( i, 1 );
}
TEST( XS_Atomic_Functions, AtomicIncrement64 )
{
int64_t i = 0;
ASSERT_EQ( XS::AtomicIncrement64( &i ), 1 );
ASSERT_EQ( i, 1 );
}
TEST( XS_Atomic_Functions, AtomicDecrement32 )
{
int32_t i = 0;
ASSERT_EQ( XS::AtomicDecrement32( &i ), -1 );
ASSERT_EQ( i, -1 );
}
TEST( XS_Atomic_Functions, AtomicDecrement64 )
{
int64_t i = 0;
ASSERT_EQ( XS::AtomicDecrement64( &i ), -1 );
ASSERT_EQ( i, -1 );
}
TEST( XS_Atomic_Functions, AtomicAdd32 )
{
int32_t i = 0;
ASSERT_EQ( XS::AtomicAdd32( 2, &i ), 2 );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicAdd64 )
{
int64_t i = 0;
ASSERT_EQ( XS::AtomicAdd64( 2, &i ), 2 );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicCompareAndSwap32 )
{
int32_t i = 0;
ASSERT_FALSE( XS::AtomicCompareAndSwap32( 1, 2, &i ) );
ASSERT_TRUE( XS::AtomicCompareAndSwap32( 0, 2, &i ) );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicCompareAndSwap64 )
{
int64_t i = 0;
ASSERT_FALSE( XS::AtomicCompareAndSwap64( 1, 2, &i ) );
ASSERT_TRUE( XS::AtomicCompareAndSwap64( 0, 2, &i ) );
ASSERT_EQ( i, 2 );
}
TEST( XS_Atomic_Functions, AtomicCompareAndSwapPointer )
{
void * p = nullptr;
ASSERT_FALSE( XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 1 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
ASSERT_TRUE( XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 0 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
ASSERT_EQ( p, reinterpret_cast< void * >( 2 ) );
}
TEST( XS_Atomic_Functions, MemoryBarrier )
{
XS::MemoryBarrier();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/app/api_access.hpp>
#include <graphene/net/node.hpp>
#include <graphene/chain/database.hpp>
#include <boost/program_options.hpp>
namespace graphene { namespace app {
namespace detail { class application_impl; }
using std::string;
class abstract_plugin;
class application_options
{
public:
// TODO change default to false when GUI is ready
bool enable_subscribe_to_all = true;
bool has_market_history_plugin = false;
};
class application
{
public:
application();
~application();
void set_program_options( boost::program_options::options_description& command_line_options,
boost::program_options::options_description& configuration_file_options )const;
void initialize(const fc::path& data_dir, const boost::program_options::variables_map&options);
void initialize_plugins( const boost::program_options::variables_map& options );
void startup();
void shutdown();
void startup_plugins();
void shutdown_plugins();
template<typename PluginType>
std::shared_ptr<PluginType> register_plugin()
{
auto plug = std::make_shared<PluginType>();
plug->plugin_set_app(this);
boost::program_options::options_description plugin_cli_options(plug->plugin_name() + " plugin. " + plug->plugin_description() + "\nOptions"), plugin_cfg_options;
//boost::program_options::options_description plugin_cli_options("Options for plugin " + plug->plugin_name()), plugin_cfg_options;
plug->plugin_set_program_options(plugin_cli_options, plugin_cfg_options);
if( !plugin_cli_options.options().empty() )
_cli_options.add(plugin_cli_options);
if( !plugin_cfg_options.options().empty() )
_cfg_options.add(plugin_cfg_options);
add_available_plugin( plug );
return plug;
}
std::shared_ptr<abstract_plugin> get_plugin( const string& name )const;
template<typename PluginType>
std::shared_ptr<PluginType> get_plugin( const string& name ) const
{
std::shared_ptr<abstract_plugin> abs_plugin = get_plugin( name );
std::shared_ptr<PluginType> result = std::dynamic_pointer_cast<PluginType>( abs_plugin );
FC_ASSERT( result != std::shared_ptr<PluginType>() );
return result;
}
net::node_ptr p2p_node();
std::shared_ptr<chain::database> chain_database()const;
void set_block_production(bool producing_blocks);
fc::optional< api_access_info > get_api_access_info( const string& username )const;
void set_api_access_info(const string& username, api_access_info&& permissions);
bool is_finished_syncing()const;
/// Emitted when syncing finishes (is_finished_syncing will return true)
boost::signals2::signal<void()> syncing_finished;
const application_options& get_options();
private:
void enable_plugin( const string& name );
void add_available_plugin( std::shared_ptr<abstract_plugin> p );
std::shared_ptr<detail::application_impl> my;
boost::program_options::options_description _cli_options;
boost::program_options::options_description _cfg_options;
};
} }
<commit_msg>Added message to FC_ASSERT in application.hpp<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/app/api_access.hpp>
#include <graphene/net/node.hpp>
#include <graphene/chain/database.hpp>
#include <boost/program_options.hpp>
namespace graphene { namespace app {
namespace detail { class application_impl; }
using std::string;
class abstract_plugin;
class application_options
{
public:
// TODO change default to false when GUI is ready
bool enable_subscribe_to_all = true;
bool has_market_history_plugin = false;
};
class application
{
public:
application();
~application();
void set_program_options( boost::program_options::options_description& command_line_options,
boost::program_options::options_description& configuration_file_options )const;
void initialize(const fc::path& data_dir, const boost::program_options::variables_map&options);
void initialize_plugins( const boost::program_options::variables_map& options );
void startup();
void shutdown();
void startup_plugins();
void shutdown_plugins();
template<typename PluginType>
std::shared_ptr<PluginType> register_plugin()
{
auto plug = std::make_shared<PluginType>();
plug->plugin_set_app(this);
boost::program_options::options_description plugin_cli_options(plug->plugin_name() + " plugin. " + plug->plugin_description() + "\nOptions"), plugin_cfg_options;
//boost::program_options::options_description plugin_cli_options("Options for plugin " + plug->plugin_name()), plugin_cfg_options;
plug->plugin_set_program_options(plugin_cli_options, plugin_cfg_options);
if( !plugin_cli_options.options().empty() )
_cli_options.add(plugin_cli_options);
if( !plugin_cfg_options.options().empty() )
_cfg_options.add(plugin_cfg_options);
add_available_plugin( plug );
return plug;
}
std::shared_ptr<abstract_plugin> get_plugin( const string& name )const;
template<typename PluginType>
std::shared_ptr<PluginType> get_plugin( const string& name ) const
{
std::shared_ptr<abstract_plugin> abs_plugin = get_plugin( name );
std::shared_ptr<PluginType> result = std::dynamic_pointer_cast<PluginType>( abs_plugin );
FC_ASSERT( result != std::shared_ptr<PluginType>(), "Unable to load plugin '${p}'", ("p",name) );
return result;
}
net::node_ptr p2p_node();
std::shared_ptr<chain::database> chain_database()const;
void set_block_production(bool producing_blocks);
fc::optional< api_access_info > get_api_access_info( const string& username )const;
void set_api_access_info(const string& username, api_access_info&& permissions);
bool is_finished_syncing()const;
/// Emitted when syncing finishes (is_finished_syncing will return true)
boost::signals2::signal<void()> syncing_finished;
const application_options& get_options();
private:
void enable_plugin( const string& name );
void add_available_plugin( std::shared_ptr<abstract_plugin> p );
std::shared_ptr<detail::application_impl> my;
boost::program_options::options_description _cli_options;
boost::program_options::options_description _cfg_options;
};
} }
<|endoftext|> |
<commit_before>#include "imgui.h"
#include <babylon/babylon_fwd.h>
#include <babylon/buffers/vertex_buffer.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/core/random.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/morph/morph_target_manager.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
FWD_CLASS_SPTR(Mesh)
FWD_CLASS_SPTR(MorphTarget)
namespace Samples {
/**
* @brief Morph Targets Scene. Example demonstrating how to morph a mesh between multiple targets
* @see https://www.babylonjs-playground.com/#2JDN66#7
* @see https://doc.babylonjs.com/how_to/how_to_use_morphtargets
*/
struct MorphTargetsScene : public IRenderableSceneWithHud {
MorphTargetsScene(ICanvas* iCanvas = nullptr) : IRenderableSceneWithHud(iCanvas)
{
}
~MorphTargetsScene() override = default;
const char* getName() override
{
return "Materials Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// This creates and positions a free camera (non-mesh)
auto camera
= ArcRotateCamera::New(std::string("camera1"), 1.14f, 1.13f, 10.f, Vector3::Zero(), scene);
// This targets the camera to scene origin
camera->setTarget(Vector3::Zero());
// This attaches the camera to the canvas
camera->attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);
// Default intensity is 1. Let's dim the light a small amount
light->intensity = 0.f;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
auto sphere = Mesh::CreateSphere("sphere1", 16, 2.f, scene);
auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);
auto exposure = 0.6f;
auto contrast = 1.6f;
auto glass = PBRMaterial::New("glass", scene);
glass->reflectionTexture = hdrTexture;
glass->refractionTexture = hdrTexture;
glass->linkRefractionWithTransparency = true;
glass->indexOfRefraction = 0.52f;
glass->alpha = 0.f;
glass->cameraExposure = exposure;
glass->cameraContrast = contrast;
glass->microSurface = 1.f;
glass->reflectivityColor = Color3(0.2f, 0.2f, 0.2f);
glass->albedoColor = Color3(0.85f, 0.85f, 0.85f);
sphere->material = glass;
auto sphere2 = Mesh::CreateSphere("sphere2", 16, 2.f, scene);
sphere2->setEnabled(false);
_addSpike(sphere2);
auto sphere3 = Mesh::CreateSphere("sphere3", 16, 2.f, scene);
sphere3->setEnabled(false);
_addSpike(sphere3);
auto sphere4 = Mesh::CreateSphere("sphere4", 16, 2.f, scene);
sphere4->setEnabled(false);
_addSpike(sphere4);
auto sphere5 = Mesh::CreateSphere("sphere5", 16, 2.f, scene);
sphere5->setEnabled(false);
_addSpike(sphere5);
auto manager = MorphTargetManager::New();
sphere->morphTargetManager = manager;
_target0 = MorphTarget::FromMesh(sphere2, "sphere2", 0.25f);
manager->addTarget(_target0);
_target1 = MorphTarget::FromMesh(sphere3, "sphere3", 0.25f);
manager->addTarget(_target1);
_target2 = MorphTarget::FromMesh(sphere4, "sphere4", 0.25f);
manager->addTarget(_target2);
_target3 = MorphTarget::FromMesh(sphere5, "sphere5", 0.25f);
manager->addTarget(_target3);
// Set influences
_target0->influence = 0.25f;
_target1->influence = 0.50f;
_target2->influence = 0.75f;
_target3->influence = 1.00f;
hudGui = [=]() {
auto addSlider
= [](const std::string& label, auto& floatProperty, float min = 0.f, float max = 1.f) {
float currentValue = floatProperty;
if (ImGui::SliderFloat(label.c_str(), ¤tValue, min, max))
floatProperty = currentValue;
};
addSlider("Influence #1", _target0->influence);
addSlider("Influence #2", _target1->influence);
addSlider("Influence #3", _target2->influence);
addSlider("Influence #4", _target3->influence);
addSlider("cameraContrast", glass->cameraContrast);
addSlider("cameraExposure", glass->cameraExposure, 0., 2.);
addSlider("microSurface", glass->microSurface, 0., 2.);
addSlider("indexOfRefraction", glass->indexOfRefraction, 0., 2.);
addSlider("alpha", glass->alpha, 0., 2.);
};
}
private:
void _addSpike(const MeshPtr& mesh)
{
auto positions = mesh->getVerticesData(VertexBuffer::PositionKind);
auto normals = mesh->getVerticesData(VertexBuffer::NormalKind);
auto indices = mesh->getIndices();
for (size_t index = 0; index < 5; ++index) {
auto randomVertexID = static_cast<unsigned int>(mesh->getTotalVertices() * Math::random());
auto position = Vector3::FromArray(positions, randomVertexID * 3);
auto normal = Vector3::FromArray(normals, randomVertexID * 3);
position.addInPlace(normal);
position.toArray(positions, randomVertexID * 3);
}
VertexData::ComputeNormals(positions, indices, normals);
mesh->updateVerticesData(VertexBuffer::PositionKind, positions, false, false);
mesh->updateVerticesData(VertexBuffer::NormalKind, normals, false, false);
}
private:
using MeshPtr = std::shared_ptr<Mesh>;
using MorphTargetPtr = std::shared_ptr<MorphTarget>;
MorphTargetPtr _target0;
MorphTargetPtr _target1;
MorphTargetPtr _target2;
MorphTargetPtr _target3;
};
std::shared_ptr<BABYLON::IRenderableScene> MakeMorphTargetsScene(ICanvas* iCanvas)
{
return std::make_shared<MorphTargetsScene>(iCanvas);
}
BABYLON_REGISTER_SAMPLE("Animations", MorphTargetsScene)
} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Removed duplicate code<commit_after>#include "imgui.h"
#include <babylon/babylon_fwd.h>
#include <babylon/buffers/vertex_buffer.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/core/random.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/morph/morph_target_manager.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
FWD_CLASS_SPTR(Mesh)
FWD_CLASS_SPTR(MorphTarget)
namespace Samples {
/**
* @brief Morph Targets Scene. Example demonstrating how to morph a mesh between multiple targets
* @see https://www.babylonjs-playground.com/#2JDN66#7
* @see https://doc.babylonjs.com/how_to/how_to_use_morphtargets
*/
struct MorphTargetsScene : public IRenderableSceneWithHud {
MorphTargetsScene(ICanvas* iCanvas = nullptr) : IRenderableSceneWithHud(iCanvas)
{
}
~MorphTargetsScene() override = default;
const char* getName() override
{
return "Materials Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// This creates and positions a free camera (non-mesh)
auto camera
= ArcRotateCamera::New(std::string("camera1"), 1.14f, 1.13f, 10.f, Vector3::Zero(), scene);
// This targets the camera to scene origin
camera->setTarget(Vector3::Zero());
// This attaches the camera to the canvas
camera->attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);
// Default intensity is 1. Let's dim the light a small amount
light->intensity = 0.f;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
auto sphere = Mesh::CreateSphere("sphere1", 16, 2.f, scene);
auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);
auto exposure = 0.6f;
auto contrast = 1.6f;
auto glass = PBRMaterial::New("glass", scene);
glass->reflectionTexture = hdrTexture;
glass->refractionTexture = hdrTexture;
glass->linkRefractionWithTransparency = true;
glass->indexOfRefraction = 0.52f;
glass->alpha = 0.f;
glass->cameraExposure = exposure;
glass->cameraContrast = contrast;
glass->microSurface = 1.f;
glass->reflectivityColor = Color3(0.2f, 0.2f, 0.2f);
glass->albedoColor = Color3(0.85f, 0.85f, 0.85f);
sphere->material = glass;
auto sphere2 = Mesh::CreateSphere("sphere2", 16, 2.f, scene);
sphere2->setEnabled(false);
_addSpike(sphere2);
auto sphere3 = Mesh::CreateSphere("sphere3", 16, 2.f, scene);
sphere3->setEnabled(false);
_addSpike(sphere3);
auto sphere4 = Mesh::CreateSphere("sphere4", 16, 2.f, scene);
sphere4->setEnabled(false);
_addSpike(sphere4);
auto sphere5 = Mesh::CreateSphere("sphere5", 16, 2.f, scene);
sphere5->setEnabled(false);
_addSpike(sphere5);
auto manager = MorphTargetManager::New();
sphere->morphTargetManager = manager;
_target0 = MorphTarget::FromMesh(sphere2, "sphere2", 0.25f);
manager->addTarget(_target0);
_target1 = MorphTarget::FromMesh(sphere3, "sphere3", 0.25f);
manager->addTarget(_target1);
_target2 = MorphTarget::FromMesh(sphere4, "sphere4", 0.25f);
manager->addTarget(_target2);
_target3 = MorphTarget::FromMesh(sphere5, "sphere5", 0.25f);
manager->addTarget(_target3);
// Set influences
_target0->influence = 0.25f;
_target1->influence = 0.50f;
_target2->influence = 0.75f;
_target3->influence = 1.00f;
hudGui = [=]() {
auto addSlider
= [](const std::string& label, auto& floatProperty, float min = 0.f, float max = 1.f) {
float currentValue = floatProperty;
if (ImGui::SliderFloat(label.c_str(), ¤tValue, min, max))
floatProperty = currentValue;
};
addSlider("Influence #1", _target0->influence);
addSlider("Influence #2", _target1->influence);
addSlider("Influence #3", _target2->influence);
addSlider("Influence #4", _target3->influence);
addSlider("cameraContrast", glass->cameraContrast);
addSlider("cameraExposure", glass->cameraExposure, 0., 2.);
addSlider("microSurface", glass->microSurface, 0., 2.);
addSlider("indexOfRefraction", glass->indexOfRefraction, 0., 2.);
addSlider("alpha", glass->alpha, 0., 2.);
};
}
private:
void _addSpike(const MeshPtr& mesh)
{
auto positions = mesh->getVerticesData(VertexBuffer::PositionKind);
auto normals = mesh->getVerticesData(VertexBuffer::NormalKind);
auto indices = mesh->getIndices();
for (size_t index = 0; index < 5; ++index) {
auto randomVertexID = static_cast<unsigned int>(mesh->getTotalVertices() * Math::random());
auto position = Vector3::FromArray(positions, randomVertexID * 3);
auto normal = Vector3::FromArray(normals, randomVertexID * 3);
position.addInPlace(normal);
position.toArray(positions, randomVertexID * 3);
}
VertexData::ComputeNormals(positions, indices, normals);
mesh->updateVerticesData(VertexBuffer::PositionKind, positions, false, false);
mesh->updateVerticesData(VertexBuffer::NormalKind, normals, false, false);
}
private:
MorphTargetPtr _target0;
MorphTargetPtr _target1;
MorphTargetPtr _target2;
MorphTargetPtr _target3;
};
std::shared_ptr<BABYLON::IRenderableScene> MakeMorphTargetsScene(ICanvas* iCanvas)
{
return std::make_shared<MorphTargetsScene>(iCanvas);
}
BABYLON_REGISTER_SAMPLE("Animations", MorphTargetsScene)
} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|> |
<commit_before><commit_msg>kill last (ab)user of SetRanges()<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <raindance/Core/Headers.hh>
#include <raindance/Core/Clock.hh>
#include <raindance/Core/Camera/Camera.hh>
#include <raindance/Core/Primitives/Quad.hh>
#include <raindance/Core/Resources/Texture.hh>
#include <graphiti/Entities/MVC.hh>
#include <graphiti/Visualizers/Network/GPUGraph.hh>
class NetworkView : public GraphView
{
public:
NetworkView()
{
LOG("[NETWORK] Creating network view ...\n");
m_GraphEntity = NULL;
m_Font = new Font();
m_Graph = new GPUGraph();
}
virtual ~NetworkView()
{
SAFE_DELETE(m_Font);
SAFE_DELETE(m_Graph);
}
virtual const char* name() const { return "network"; }
virtual bool bind(Entity* entity)
{
if (entity->type() != Entity::GRAPH)
{
LOG("[NETWORK] Couldn't bind entity to view : Wrong entity type!\n");
return false;
}
m_Camera2D.setOrthographicProjection(0.0f, getViewport().getDimension()[0], 0.0f, getViewport().getDimension()[1], 0.001f, 100.f);
m_Camera2D.lookAt(glm::vec3(0, 0, 10), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
m_Camera3D.setPerspectiveProjection(60.0f, getViewport().getDimension()[0] / getViewport().getDimension()[1], 0.1f, 1024.0f);
m_Camera3D.lookAt(glm::vec3(0, 0, 30), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
m_GraphEntity = static_cast<GraphEntity*>(entity);
m_GraphEntity->views().push_back(this);
m_GraphEntity->listeners().push_back(this);
return true;
}
inline Camera* getCamera3D()
{
return &m_Camera3D;
}
void draw() override
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);
Transformation transformation;
m_Graph->draw(context(), m_Camera3D, transformation);
}
void idle() override
{
static bool m_Initialized = false;
if (!m_Initialized)
{
m_Graph->initialize(context());
m_Initialized = true;
}
m_Graph->idle(context());
}
void notify(IMessage* message)
{
(void) message;
}
// ----- Helpers -----
void checkNodeUID(GPUGraph::Node::ID uid)
{
if (!m_NodeMap.containsRemoteID(uid))
{
LOG("Node UID %u not found !\n", uid);
throw;
}
}
void checkEdgeUID(GPUGraph::Edge::ID uid)
{
if (!m_EdgeMap.containsRemoteID(uid))
{
LOG("Edge UID %u not found !\n", uid);
throw;
}
}
// ----- Graph Events -----
void onSetAttribute(const std::string& name, VariableType type, const std::string& value) override
{
LOG("onSetAttribute(%s, %i, %s)\n", name.c_str(), (int)type, value.c_str());
}
void onAddNode(Node::ID uid, const char* label) override // TODO : Attributes in Variables object
{
LOG("onAddNode(%lu, %s)\n", uid, label);
GPUGraph::Node node;
// TODO : Emitter system? (Define where particles appear)
node.Position = 10.0f * glm::vec4
(
RANDOM_FLOAT(-1.0, 1.0),
RANDOM_FLOAT(-1.0, 1.0),
RANDOM_FLOAT(-1.0, 1.0),
0.0
);
node.Color = glm::vec4(1.0, 1.0, 1.0, 1.0);
node.Size = 1.0;
m_Graph->addNode(node);
static unsigned int node_count = 0;
GPUGraph::Node::ID nid = node_count;
m_NodeMap.addRemoteID(uid, nid);
node_count++;
}
void onRemoveNode(Node::ID uid) override
{
LOG("onRemoveNode(%lu)\n", uid);
}
void onSetNodeAttribute(Node::ID uid, const std::string& name, VariableType type, const std::string& value) override
{
LOG("onSetNodeAttribute(%lu, %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());
BooleanVariable vbool;
Vec3Variable vvec3;
Vec4Variable vvec4;
FloatVariable vfloat;
checkNodeUID(uid);
GPUGraph::Node::ID id = m_NodeMap.getLocalID(uid);
if ((name == "space:position" || name == "particles:position") && type == RD_VEC3)
{
vvec3.set(value);
GPUGraph::Node node = m_Graph->getNode(id);
node.Position = glm::vec4(vvec3.value(), 0.0);
m_Graph->setNode(id, node);
}
else if (name == "space:color" && (type == RD_VEC3 || type == RD_VEC4))
{
glm::vec4 c;
if (type == RD_VEC3)
{
vvec3.set(value);
c = glm::vec4(vvec3.value(), 0.0);
}
else
{
vvec4.set(value);
c = vvec4.value();
}
GPUGraph::Node node = m_Graph->getNode(id);
node.Color = vvec4.value();
m_Graph->setNode(id, node);
}
else if (name == "space:size" && type == RD_FLOAT)
{
vfloat.set(value);
GPUGraph::Node node = m_Graph->getNode(id);
node.Size = vfloat.value();
m_Graph->setNode(id, node);
}
}
void onAddEdge(Edge::ID uid, Node::ID uid1, Node::ID uid2) override
{
LOG("onAddEdge(%lu, %lu, %lu)\n", uid, uid1, uid2);
GPUGraph::Node::ID nid1 = m_NodeMap.getLocalID(uid1);
GPUGraph::Node::ID nid2 = m_NodeMap.getLocalID(uid2);
GPUGraph::Edge edge;
GPUGraph::Node n1 = m_Graph->getNode(nid1);
GPUGraph::Node n2 = m_Graph->getNode(nid2);
edge.SourcePosition = n1.Position;
edge.SourceColor = n1.Color;
edge.TargetPosition = n2.Position;
edge.TargetColor = n2.Color;
edge.Width = 0.5; // NOTE : Half of the node size
m_Graph->addEdge(edge);
static unsigned int edge_count = 0;
GPUGraph::Edge::ID eid = edge_count;
m_EdgeMap.addRemoteID(uid, eid);
edge_count++;
}
void onRemoveEdge(Edge::ID uid) override
{
LOG("onRemoveEdge(%lu)\n", uid);
}
void onSetEdgeAttribute(Edge::ID uid, const std::string& name, VariableType type, const std::string& value) override
{
LOG("onSetEdgeAttribute(%lu %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());
FloatVariable vfloat;
Vec3Variable vvec3;
Vec4Variable vvec4;
StringVariable vstring;
checkEdgeUID(uid);
GPUGraph::Edge::ID id = m_EdgeMap.getLocalID(uid);
if (name == "space:color" && type == RD_VEC4)
{
vvec4.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.SourceColor = vvec4.value();
edge.TargetColor = vvec4.value();
m_Graph->setEdge(id, edge);
}
else if (name == "space:color1" && type == RD_VEC4)
{
vvec4.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.SourceColor = vvec4.value();
m_Graph->setEdge(id, edge);
}
else if (name == "space:color2" && type == RD_VEC4)
{
vvec4.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.TargetColor = vvec4.value();
m_Graph->setEdge(id, edge);
}
else if (name == "space:width" && type == RD_FLOAT)
{
vfloat.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.Width = vfloat.value();
m_Graph->setEdge(id, edge);
}
}
virtual IVariable* getAttribute(const std::string& name)
{
(void) name;
return NULL;
}
virtual IVariable* getNodeAttribute(Node::ID id, std::string& name)
{
(void) id;
(void) name;
return NULL;
}
virtual IVariable* getEdgeAttribute(Edge::ID id, std::string& name)
{
(void) id;
(void) name;
return NULL;
}
inline GraphContext* context() { return static_cast<GraphContext*>(m_GraphEntity->context()); }
inline GraphModel* model() { return static_cast<GraphModel*>(m_GraphEntity->model()); }
private:
GraphEntity* m_GraphEntity;
Camera m_Camera2D;
Camera m_Camera3D;
Font* m_Font;
GPUGraph* m_Graph;
TranslationMap<GPUGraph::Node::ID, unsigned int> m_NodeMap;
TranslationMap<GPUGraph::Edge::ID, unsigned int> m_EdgeMap;
};
<commit_msg>Integrating OpenCL physics<commit_after>#pragma once
#include <raindance/Core/Headers.hh>
#include <raindance/Core/Clock.hh>
#include <raindance/Core/Camera/Camera.hh>
#include <raindance/Core/Primitives/Quad.hh>
#include <raindance/Core/Resources/Texture.hh>
#include <graphiti/Entities/MVC.hh>
#include <graphiti/Visualizers/Network/GPUGraph.hh>
class NetworkView : public GraphView
{
public:
NetworkView()
{
LOG("[NETWORK] Creating network view ...\n");
m_GraphEntity = NULL;
m_Font = new Font();
m_Graph = new GPUGraph();
}
virtual ~NetworkView()
{
SAFE_DELETE(m_Font);
SAFE_DELETE(m_Graph);
}
virtual const char* name() const { return "network"; }
virtual bool bind(Entity* entity)
{
if (entity->type() != Entity::GRAPH)
{
LOG("[NETWORK] Couldn't bind entity to view : Wrong entity type!\n");
return false;
}
m_Camera2D.setOrthographicProjection(0.0f, getViewport().getDimension()[0], 0.0f, getViewport().getDimension()[1], 0.001f, 100.f);
m_Camera2D.lookAt(glm::vec3(0, 0, 10), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
m_Camera3D.setPerspectiveProjection(60.0f, getViewport().getDimension()[0] / getViewport().getDimension()[1], 0.1f, 1024.0f);
m_Camera3D.lookAt(glm::vec3(0, 0, 30), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
m_GraphEntity = static_cast<GraphEntity*>(entity);
m_GraphEntity->views().push_back(this);
m_GraphEntity->listeners().push_back(this);
return true;
}
inline Camera* getCamera3D()
{
return &m_Camera3D;
}
void draw() override
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);
Transformation transformation;
m_Graph->draw(context(), m_Camera3D, transformation);
}
void idle() override
{
static bool m_Initialized = false;
if (!m_Initialized)
{
m_Graph->initialize(context());
m_Initialized = true;
}
m_Graph->idle(context());
}
void notify(IMessage* message)
{
(void) message;
}
// ----- Helpers -----
void checkNodeUID(GPUGraph::Node::ID uid)
{
if (!m_NodeMap.containsRemoteID(uid))
{
LOG("Node UID %u not found !\n", uid);
throw;
}
}
void checkEdgeUID(GPUGraph::Edge::ID uid)
{
if (!m_EdgeMap.containsRemoteID(uid))
{
LOG("Edge UID %u not found !\n", uid);
throw;
}
}
// ----- Graph Events -----
void onSetAttribute(const std::string& name, VariableType type, const std::string& value) override
{
LOG("onSetAttribute(%s, %i, %s)\n", name.c_str(), (int)type, value.c_str());
}
void onAddNode(Node::ID uid, const char* label) override // TODO : Attributes in Variables object
{
LOG("onAddNode(%lu, %s)\n", uid, label);
GPUGraph::Node node;
// TODO : Emitter system? (Define where particles appear)
node.Position = 10.0f * glm::vec4
(
RANDOM_FLOAT(-1.0, 1.0),
RANDOM_FLOAT(-1.0, 1.0),
RANDOM_FLOAT(-1.0, 1.0),
0.0
);
node.Color = glm::vec4(1.0, 1.0, 1.0, 1.0);
node.Size = 1.0;
m_Graph->addNode(node);
static unsigned int node_count = 0;
GPUGraph::Node::ID nid = node_count;
m_NodeMap.addRemoteID(uid, nid);
node_count++;
}
void onRemoveNode(Node::ID uid) override
{
LOG("onRemoveNode(%lu)\n", uid);
}
void onSetNodeAttribute(Node::ID uid, const std::string& name, VariableType type, const std::string& value) override
{
// LOG("onSetNodeAttribute(%lu, %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());
BooleanVariable vbool;
Vec3Variable vvec3;
Vec4Variable vvec4;
FloatVariable vfloat;
checkNodeUID(uid);
GPUGraph::Node::ID id = m_NodeMap.getLocalID(uid);
if ((name == "space:position" || name == "particles:position") && type == RD_VEC3)
{
vvec3.set(value);
GPUGraph::Node node = m_Graph->getNode(id);
node.Position = glm::vec4(vvec3.value(), 0.0);
m_Graph->setNode(id, node);
}
else if (name == "space:color" && (type == RD_VEC3 || type == RD_VEC4))
{
glm::vec4 c;
if (type == RD_VEC3)
{
vvec3.set(value);
c = glm::vec4(vvec3.value(), 0.0);
}
else
{
vvec4.set(value);
c = vvec4.value();
}
GPUGraph::Node node = m_Graph->getNode(id);
node.Color = vvec4.value();
m_Graph->setNode(id, node);
}
else if (name == "space:size" && type == RD_FLOAT)
{
vfloat.set(value);
GPUGraph::Node node = m_Graph->getNode(id);
node.Size = vfloat.value();
m_Graph->setNode(id, node);
}
}
void onAddEdge(Edge::ID uid, Node::ID uid1, Node::ID uid2) override
{
// LOG("onAddEdge(%lu, %lu, %lu)\n", uid, uid1, uid2);
GPUGraph::Node::ID nid1 = m_NodeMap.getLocalID(uid1);
GPUGraph::Node::ID nid2 = m_NodeMap.getLocalID(uid2);
GPUGraph::Edge edge;
GPUGraph::Node n1 = m_Graph->getNode(nid1);
GPUGraph::Node n2 = m_Graph->getNode(nid2);
edge.SourcePosition = n1.Position;
edge.SourceColor = n1.Color;
edge.TargetPosition = n2.Position;
edge.TargetColor = n2.Color;
edge.Width = 0.5; // NOTE : Half of the node size
m_Graph->addEdge(edge);
static unsigned int edge_count = 0;
GPUGraph::Edge::ID eid = edge_count;
m_EdgeMap.addRemoteID(uid, eid);
edge_count++;
}
void onRemoveEdge(Edge::ID uid) override
{
// LOG("onRemoveEdge(%lu)\n", uid);
}
void onSetEdgeAttribute(Edge::ID uid, const std::string& name, VariableType type, const std::string& value) override
{
// LOG("onSetEdgeAttribute(%lu %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());
FloatVariable vfloat;
Vec3Variable vvec3;
Vec4Variable vvec4;
StringVariable vstring;
checkEdgeUID(uid);
GPUGraph::Edge::ID id = m_EdgeMap.getLocalID(uid);
if (name == "space:color" && type == RD_VEC4)
{
vvec4.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.SourceColor = vvec4.value();
edge.TargetColor = vvec4.value();
m_Graph->setEdge(id, edge);
}
else if (name == "space:color1" && type == RD_VEC4)
{
vvec4.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.SourceColor = vvec4.value();
m_Graph->setEdge(id, edge);
}
else if (name == "space:color2" && type == RD_VEC4)
{
vvec4.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.TargetColor = vvec4.value();
m_Graph->setEdge(id, edge);
}
else if (name == "space:width" && type == RD_FLOAT)
{
vfloat.set(value);
GPUGraph::Edge edge = m_Graph->getEdge(id);
edge.Width = vfloat.value();
m_Graph->setEdge(id, edge);
}
}
virtual IVariable* getAttribute(const std::string& name)
{
(void) name;
return NULL;
}
virtual IVariable* getNodeAttribute(Node::ID id, std::string& name)
{
(void) id;
(void) name;
return NULL;
}
virtual IVariable* getEdgeAttribute(Edge::ID id, std::string& name)
{
(void) id;
(void) name;
return NULL;
}
inline GraphContext* context() { return static_cast<GraphContext*>(m_GraphEntity->context()); }
inline GraphModel* model() { return static_cast<GraphModel*>(m_GraphEntity->model()); }
private:
GraphEntity* m_GraphEntity;
Camera m_Camera2D;
Camera m_Camera3D;
Font* m_Font;
GPUGraph* m_Graph;
TranslationMap<GPUGraph::Node::ID, unsigned int> m_NodeMap;
TranslationMap<GPUGraph::Edge::ID, unsigned int> m_EdgeMap;
};
<|endoftext|> |
<commit_before>#include <random>
#include <iostream>
using namespace std;
void
printIntVector( vector<int> &numbers ) {
for( vector<int>::iterator it=numbers.begin(); it!=numbers.end(); it++) {
cout << *it << " " ;
}
cout << endl;
}
bool comp( const int &n1, const int &n2 ) {
return ( n1 > n2 );
}
vector<int>
sortUsingHeapApi( vector<int> &numbers) {
vector<int> output;
make_heap( numbers.begin(), numbers.end(), comp );
while( not numbers.empty() ) {
// CRITICAL
pop_heap( numbers.begin(), numbers.end(), comp );
output.push_back( numbers.back() );
numbers.pop_back();
}
return output;
}
int main() {
vector<int> numbers;
vector<int> sorted;
for(int i=0; i<10; i++) {
numbers.push_back( rand() % 2048 );
}
printIntVector(numbers);
sorted = sortUsingHeapApi(numbers);
printIntVector(sorted);
}
<commit_msg>pop_back needs comp function<commit_after>#include <random>
#include <iostream>
using namespace std;
void
printIntVector( vector<int> &numbers ) {
for( vector<int>::iterator it=numbers.begin(); it!=numbers.end(); it++) {
cout << *it << " " ;
}
cout << endl;
}
bool comp( const int &n1, const int &n2 ) {
return ( n1 > n2 );
}
vector<int>
sortUsingHeapApi( vector<int> &numbers) {
vector<int> output;
make_heap( numbers.begin(), numbers.end(), comp );
while( not numbers.empty() ) {
// CRITICAL COMMENT
// pop_heap needs comp function to re-arrange
// properly.
pop_heap( numbers.begin(), numbers.end(), comp );
output.push_back( numbers.back() );
numbers.pop_back();
}
return output;
}
int main() {
vector<int> numbers;
vector<int> sorted;
for(int i=0; i<10; i++) {
numbers.push_back( rand() % 2048 );
}
printIntVector(numbers);
sorted = sortUsingHeapApi(numbers);
printIntVector(sorted);
}
<|endoftext|> |
<commit_before>/*
Library EDK - How to use Extensible Development Kit
Copyright (C) 2013 Eduardo Moura Sales Martins
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
email: [email protected]
AV: Walmor M. de Souza 392 Casa
Gravatai RS Brazil 94065100
*/
//Include the edk::vector::Array
#include "edk/vector/Array.h"
int main(){
edk::int32 size1 = 5;
//create an array with 32 bit integer where can alocate five positions
edk::vector::Array<edk::int32> n1(size1);
//fill the array with values
for(edk::int32 i=0;i<size1;i++){
//set the value
n1.set(i,i+1);
}
//print the array values
printf("\nArray N1 with size %u have values: ",n1.size());
for(edk::int32 i=0;i<size1;i++){
//set the value
printf(" [%d]",n1.get(i));
}
printf(";");fflush(stdout);
//Create a new array
edk::int32 size2 = 4;
//create the new array with 4 positions
edk::vector::Array<edk::int32> n2(size2);
//fill the second array
for(edk::int32 i=0;i<size2;i++){
//set the value
n2.set(i,size2-i);
}
//print the array values
printf("\nArray N2 with size %u have values: ",n2.size());
for(edk::int32 i=0;i<size2;i++){
//set the value
printf(" [%d]",n2.get(i));
}
printf(";");fflush(stdout);
//copy the vector 1 to vector 2
n2 = n1;
//print the array values
//print the array values
printf("\nAfter copy N1 to N2. The array N2 with size %u have values: ",n2.size());
size2 = n2.size();
for(edk::int32 i=0;i<size2;i++){
//set the value
printf(" [%d]",n2.get(i));
}
printf(";");fflush(stdout);
printf("\n\n");
return 0;
}
<commit_msg>I change the copy from the classes but I forgot to change this on the example<commit_after>/*
Library EDK - How to use Extensible Development Kit
Copyright (C) 2013 Eduardo Moura Sales Martins
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
email: [email protected]
AV: Walmor M. de Souza 392 Casa
Gravatai RS Brazil 94065100
*/
//Include the edk::vector::Array
#include "edk/vector/Array.h"
int main(){
edk::int32 size1 = 5;
//create an array with 32 bit integer where can alocate five positions
edk::vector::Array<edk::int32> n1(size1);
//fill the array with values
for(edk::int32 i=0;i<size1;i++){
//set the value
n1.set(i,i+1);
}
//print the array values
printf("\nArray N1 with size %u have values: ",n1.size());
for(edk::int32 i=0;i<size1;i++){
//set the value
printf(" [%d]",n1.get(i));
}
printf(";");fflush(stdout);
//Create a new array
edk::int32 size2 = 4;
//create the new array with 4 positions
edk::vector::Array<edk::int32> n2(size2);
//fill the second array
for(edk::int32 i=0;i<size2;i++){
//set the value
n2.set(i,size2-i);
}
//print the array values
printf("\nArray N2 with size %u have values: ",n2.size());
for(edk::int32 i=0;i<size2;i++){
//set the value
printf(" [%d]",n2.get(i));
}
printf(";");fflush(stdout);
//copy the vector 1 to vector 2
n2.cloneFrom(n1);
//print the array values
//print the array values
printf("\nAfter copy N1 to N2. The array N2 with size %u have values: ",n2.size());
size2 = n2.size();
for(edk::int32 i=0;i<size2;i++){
//set the value
printf(" [%d]",n2.get(i));
}
printf(";");fflush(stdout);
printf("\n\n");
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file LatentSvmDetector_.cpp
* @brief mex interface for LatentSvmDetector
* @author Kota Yamaguchi
* @date 2012
*/
#include "mexopencv.hpp"
using namespace std;
using namespace cv;
namespace {
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,LatentSvmDetector> obj_;
/// Alias for argument number check
inline void nargchk(bool cond)
{
if (!cond)
mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
}
/** Convert object detections to struct array
* @param vo vector of detections
*/
mxArray* ObjectDetection2Struct(
const vector<LatentSvmDetector::ObjectDetection> vo,
const vector<string>& classNames)
{
const char* fields[] = {"rect","score","class"};
MxArray m(fields,3,1,vo.size());
for (int i=0; i<vo.size(); ++i) {
m.set("rect", vo[i].rect, i);
m.set("score", vo[i].score, i);
m.set("class", classNames[vo[i].classID], i);
}
return m;
}
} // local scope
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
nargchk(nrhs>=2 && nlhs<=2);
vector<MxArray> rhs(prhs,prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor call
if (method == "new") {
nargchk(nlhs<=1 && nrhs<=4);
obj_[++last_id] = LatentSvmDetector();
// Due to the buggy implementation of LatentSvmDetector in OpenCV
// we cannot use the constructor syntax other than empty args.
plhs[0] = MxArray(last_id);
return;
}
// Big operation switch
LatentSvmDetector& obj = obj_[id];
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
}
else if (method == "clear") {
nargchk(nrhs==2 && nlhs==0);
obj.clear();
}
else if (method == "empty") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj.empty());
}
else if (method == "load") {
nargchk(nrhs<=4 && nlhs<=1);
plhs[0] = (nrhs==3) ? MxArray(obj.load(rhs[2].toVector<string>())) :
MxArray(obj.load(rhs[2].toVector<string>(), rhs[3].toVector<string>()));
}
else if (method == "detect") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
Mat image((rhs[2].isUint8()) ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
vector<LatentSvmDetector::ObjectDetection> objectDetections;
float overlapThreshold=0.5f;
int numThreads=-1;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key=="OverlapThreshold")
overlapThreshold = rhs[i+1].toDouble();
else if (key=="NumThreads")
numThreads = rhs[i+1].toInt();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
obj.detect(image,objectDetections,overlapThreshold,numThreads);
plhs[0] = ObjectDetection2Struct(objectDetections, obj.getClassNames());
}
else if (method == "getClassNames") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj.getClassNames());
}
else if (method == "getClassCount") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(static_cast<int>(obj.getClassCount()));
}
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation %s", method.c_str());
}
<commit_msg>fix opencv_contrib/latentsvm module functions<commit_after>/**
* @file LSVMDetector_.cpp
* @brief mex interface for LSVMDetector
* @author Kota Yamaguchi
* @date 2012
*/
#include "mexopencv.hpp"
#include "opencv2/latentsvm.hpp"
using namespace std;
using namespace cv;
using namespace cv::lsvm;
namespace {
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,Ptr<LSVMDetector> > obj_;
/// Alias for argument number check
inline void nargchk(bool cond)
{
if (!cond)
mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
}
/** Convert object detections to struct array
* @param vo vector of detections
*/
mxArray* ObjectDetection2Struct(
const vector<LSVMDetector::ObjectDetection>& vo,
const vector<string>& classNames)
{
const char* fields[] = {"rect", "score", "class"};
MxArray m(fields, 3, 1, vo.size());
for (size_t i=0; i<vo.size(); ++i) {
m.set("rect", vo[i].rect, i);
m.set("score", vo[i].score, i);
m.set("class", classNames[vo[i].classID], i);
}
return m;
}
} // local scope
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
nargchk(nrhs>=2 && nlhs<=2);
vector<MxArray> rhs(prhs,prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor call
if (method == "new") {
nargchk((nrhs==3 || nrhs==4) && nlhs<=1);
obj_[++last_id] = (nrhs == 3) ?
LSVMDetector::create(rhs[2].toVector<string>()) :
LSVMDetector::create(rhs[2].toVector<string>(), rhs[3].toVector<string>());
plhs[0] = MxArray(last_id);
return;
}
// Big operation switch
Ptr<LSVMDetector> obj = obj_[id];
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
}
else if (method == "isEmpty") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj->isEmpty());
}
else if (method == "detect") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
float overlapThreshold = 0.5f;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key=="OverlapThreshold")
overlapThreshold = rhs[i+1].toDouble();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
Mat image(rhs[2].toMat(rhs[2].isUint8() ? CV_8U : CV_32F));
vector<LSVMDetector::ObjectDetection> objects;
obj->detect(image, objects, overlapThreshold);
plhs[0] = ObjectDetection2Struct(objects, obj->getClassNames());
}
else if (method == "getClassNames") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj->getClassNames());
}
else if (method == "getClassCount") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(static_cast<int>(obj->getClassCount()));
}
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation %s", method.c_str());
}
<|endoftext|> |
<commit_before>#include <agency/execution_policy.hpp>
#include <mutex>
#include <iostream>
#include <thread>
int main()
{
int ball = 0;
std::string names[2] = {"ping", "pong"};
std::mutex mut;
// create two concurrent agents
agency::bulk_invoke(agency::con(2), [&](agency::concurrent_agent& self)
{
auto name = names[self.index()];
// play for 20 volleys
for(int next_state = self.index();
next_state < 20;
next_state += 2)
{
// wait for the next volley
while(ball != next_state)
{
mut.lock();
std::cout << name << " waiting for return" << std::endl;
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// return the ball
mut.lock();
ball += 1;
std::cout << name << "! ball is now " << ball << std::endl;
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
return 0;
}
<commit_msg>tweak formatting<commit_after>#include <agency/execution_policy.hpp>
#include <mutex>
#include <iostream>
#include <thread>
int main()
{
int ball = 0;
std::string names[2] = {"ping", "pong"};
std::mutex mut;
// create two concurrent agents
agency::bulk_invoke(agency::con(2), [&](agency::concurrent_agent& self)
{
auto name = names[self.index()];
// play for 20 volleys
for(int next_state = self.index(); next_state < 20; next_state += 2)
{
// wait for the next volley
while(ball != next_state)
{
mut.lock();
std::cout << name << " waiting for return" << std::endl;
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// return the ball
mut.lock();
ball += 1;
std::cout << name << "! ball is now " << ball << std::endl;
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
return 0;
}
<|endoftext|> |
<commit_before>/*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* ``The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is SimpleAmqpClient for RabbitMQ.
*
* The Initial Developer of the Original Code is Alan Antonuk.
* Original code is Copyright (C) Alan Antonuk.
*
* All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License Version 2 or later (the "GPL"), in
* which case the provisions of the GPL are applicable instead of those
* above. If you wish to allow use of your version of this file only
* under the terms of the GPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the
* notice and other provisions required by the GPL. If you do not
* delete the provisions above, a recipient may use your version of
* this file under the terms of any one of the MPL or the GPL.
*
* ***** END LICENSE BLOCK *****
*/
#include "SimpleAmqpClient.h"
#define BOOST_ALL_NO_LIB
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/utility.hpp>
#include <iostream>
#include <stdlib.h>
using namespace AmqpClient;
class thread_body : boost::noncopyable
{
public:
thread_body()
{
char* szBroker = getenv("AMQP_BROKER");
Channel::ptr_t channel;
if (szBroker != NULL)
channel = Channel::Create(szBroker);
else
channel = Channel::Create();
server = SimpleRpcServer::Create(channel);
m_thread =
boost::make_shared<boost::thread>(boost::bind(&thread_body::run,
this));
}
virtual ~thread_body()
{
std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
m_thread->interrupt();
std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
m_thread->join();
}
void run()
{
while (!boost::this_thread::interruption_requested())
{
std::cout << "Waiting for message... " << std::flush;
BasicMessage::ptr_t message;
if (server->GetNextIncomingMessage(message, 1))
{
std::cout << "message received.\n";
}
else
{
std::cout << "message not received.\n";
}
}
}
SimpleRpcServer::ptr_t server;
boost::shared_ptr<boost::thread> m_thread;
};
int main()
{
boost::shared_ptr<thread_body> body = boost::make_shared<thread_body>();
boost::this_thread::sleep(boost::posix_time::seconds(3));
return 0;
}
<commit_msg>Adding more complete consume with timeout example<commit_after>/*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* ``The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is SimpleAmqpClient for RabbitMQ.
*
* The Initial Developer of the Original Code is Alan Antonuk.
* Original code is Copyright (C) Alan Antonuk.
*
* All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License Version 2 or later (the "GPL"), in
* which case the provisions of the GPL are applicable instead of those
* above. If you wish to allow use of your version of this file only
* under the terms of the GPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the
* notice and other provisions required by the GPL. If you do not
* delete the provisions above, a recipient may use your version of
* this file under the terms of any one of the MPL or the GPL.
*
* ***** END LICENSE BLOCK *****
*/
#include <SimpleAmqpClient.h>
#include <SimpleAmqpClient/SimpleRpcClient.h>
#include <SimpleAmqpClient/SimpleRpcServer.h>
#define BOOST_ALL_NO_LIB
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/utility.hpp>
#include <iostream>
#include <stdlib.h>
using namespace AmqpClient;
class thread_body : boost::noncopyable
{
public:
thread_body()
{
char* szBroker = getenv("AMQP_BROKER");
Channel::ptr_t channel;
if (szBroker != NULL)
channel = Channel::Create(szBroker);
else
channel = Channel::Create();
server = SimpleRpcServer::Create(channel, "consume_timeout_test");
m_thread =
boost::make_shared<boost::thread>(boost::bind(&thread_body::run,
this));
}
virtual ~thread_body()
{
std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
m_thread->interrupt();
std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
m_thread->join();
}
void run()
{
while (!boost::this_thread::interruption_requested())
{
std::cout << "Waiting for message... " << std::flush;
BasicMessage::ptr_t message;
if (server->GetNextIncomingMessage(message, 1))
{
std::cout << "message received.\n";
server->RespondToMessage(message, "this is a response");
}
else
{
std::cout << "message not received.\n";
}
}
}
SimpleRpcServer::ptr_t server;
boost::shared_ptr<boost::thread> m_thread;
};
int main()
{
boost::shared_ptr<thread_body> body = boost::make_shared<thread_body>();
boost::this_thread::sleep(boost::posix_time::seconds(1));
char* szBroker = getenv("AMQP_BROKER");
Channel::ptr_t channel;
if (szBroker != NULL)
channel = Channel::Create(szBroker);
else
channel = Channel::Create();
SimpleRpcClient::ptr_t client = SimpleRpcClient::Create(channel, "consume_timeout_test");
std::string str = client->Call("Here is my message");
std::cout << "Got response: " << str << std::endl;
boost::this_thread::sleep(boost::posix_time::seconds(2));
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
#define IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
#include "iceoryx_posh/capro/service_description.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp"
#include "iceoryx_posh/internal/popo/ports/application_port.hpp"
#include "iceoryx_posh/internal/popo/ports/interface_port.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp"
#include "iceoryx_posh/internal/runtime/ipc_runtime_interface.hpp"
#include "iceoryx_posh/internal/runtime/node_property.hpp"
#include "iceoryx_posh/popo/subscriber_options.hpp"
#include "iceoryx_posh/runtime/port_config_info.hpp"
#include <atomic>
namespace iox
{
namespace roudi
{
class RuntimeTestInterface;
} // namespace roudi
namespace runtime
{
class Node;
class NodeData;
enum class FindServiceError
{
INVALID_STATE,
UNABLE_TO_WRITE_TO_ROUDI_CHANNEL,
INSTANCE_CONTAINER_OVERFLOW
};
/// @brief The runtime that is needed for each application to communicate with the RouDi daemon
class PoshRuntime
{
public:
PoshRuntime(const PoshRuntime&) = delete;
PoshRuntime& operator=(const PoshRuntime&) = delete;
PoshRuntime(PoshRuntime&&) = delete;
PoshRuntime& operator=(PoshRuntime&&) = delete;
virtual ~PoshRuntime() noexcept = default;
/// @brief returns active runtime
///
/// @return active runtime
static PoshRuntime& getInstance() noexcept;
/// @brief creates the runtime with given name
///
/// @param[in] name used for registering the process with the RouDi daemon
///
/// @return active runtime
static PoshRuntime& initRuntime(const RuntimeName_t& name) noexcept;
/// @brief get the name that was used to register with RouDi
/// @return name of the registered application
RuntimeName_t getInstanceName() const noexcept;
/// @brief initiates the shutdown of the runtime to unblock all potentially blocking publisher
/// with the SubscriberTooSlowPolicy::WAIT_FOR_SUBSCRIBER option set
void shutdown() noexcept;
/// @brief find all services that match the provided service description
/// @param[in] serviceDescription service to search for
/// @return cxx::expected<InstanceContainer, FindServiceError>
/// InstanceContainer: on success, container that is filled with all matching instances
/// FindServiceError: if any, encountered during the operation
virtual cxx::expected<InstanceContainer, FindServiceError>
findService(const capro::ServiceDescription& serviceDescription) noexcept = 0;
/// @brief offer the provided service, sends the offer from application to RouDi daemon
/// @param[in] serviceDescription service to offer
/// @return bool, if service is offered returns true else false
virtual bool offerService(const capro::ServiceDescription& serviceDescription) noexcept = 0;
/// @brief stop offering the provided service
/// @param[in] serviceDescription of the service that shall be no more offered
virtual void stopOfferService(const capro::ServiceDescription& serviceDescription) noexcept = 0;
/// @brief request the RouDi daemon to create a publisher port
/// @param[in] serviceDescription service description for the new publisher port
/// @param[in] publisherOptions like the history capacity of a publisher
/// @param[in] portConfigInfo configuration information for the port
/// (i.e. what type of port is requested, device where its payload memory is located on etc.)
/// @return pointer to a created publisher port user
virtual PublisherPortUserType::MemberType_t*
getMiddlewarePublisher(const capro::ServiceDescription& service,
const popo::PublisherOptions& publisherOptions = popo::PublisherOptions(),
const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;
/// @brief request the RouDi daemon to create a subscriber port
/// @param[in] serviceDescription service description for the new subscriber port
/// @param[in] subscriberOptions like the queue capacity and history requested by a subscriber
/// @param[in] portConfigInfo configuration information for the port
/// (what type of port is requested, device where its payload memory is located on etc.)
/// @return pointer to a created subscriber port data
virtual SubscriberPortUserType::MemberType_t*
getMiddlewareSubscriber(const capro::ServiceDescription& service,
const popo::SubscriberOptions& subscriberOptions = popo::SubscriberOptions(),
const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;
/// @brief request the RouDi daemon to create an interface port
/// @param[in] interface interface to create
/// @param[in] nodeName name of the node where the interface should belong to
/// @return pointer to a created interface port data
virtual popo::InterfacePortData* getMiddlewareInterface(const capro::Interfaces interface,
const NodeName_t& nodeName = {""}) noexcept = 0;
/// @brief request the RouDi daemon to create an application port
/// @return pointer to a created application port data
virtual popo::ApplicationPortData* getMiddlewareApplication() noexcept = 0;
/// @brief request the RouDi daemon to create a condition variable
/// @return pointer to a created condition variable data
virtual popo::ConditionVariableData* getMiddlewareConditionVariable() noexcept = 0;
/// @brief request the RouDi daemon to create a node
/// @param[in] nodeProperty class which contains all properties which the node should have
/// @return pointer to the data of the node
virtual NodeData* createNode(const NodeProperty& nodeProperty) noexcept = 0;
/// @brief requests the serviceRegistryChangeCounter from the shared memory
/// @return pointer to the serviceRegistryChangeCounter
virtual const std::atomic<uint64_t>* getServiceRegistryChangeCounter() noexcept = 0;
/// @brief send a request to the RouDi daemon and get the response
/// currently each request is followed by a response
/// @param[in] msg request message to send
/// @param[out] response from the RouDi daemon
/// @return true if sucessful request/response, false on error
virtual bool sendRequestToRouDi(const IpcMessage& msg, IpcMessage& answer) noexcept = 0;
protected:
using factory_t = PoshRuntime& (*)(cxx::optional<const RuntimeName_t*>);
// Protected constructor for derived classes
PoshRuntime(cxx::optional<const RuntimeName_t*> name) noexcept;
static PoshRuntime& defaultRuntimeFactory(cxx::optional<const RuntimeName_t*> name) noexcept;
static RuntimeName_t& defaultRuntimeInstanceName() noexcept;
/// @brief gets current runtime factory. If the runtime factory is not yet initialized it is set to
/// defaultRuntimeFactory.
///
/// @return current runtime factory
static factory_t& getRuntimeFactory() noexcept;
/// @brief sets runtime factory, terminates if given factory is empty
///
/// @param[in] factory std::function to which the runtime factory should be set
static void setRuntimeFactory(const factory_t& factory) noexcept;
/// @brief creates the runtime or returns the already existing one -> Singleton
///
/// @param[in] name optional containing the name used for registering with the RouDi daemon
///
/// @return active runtime
static PoshRuntime& getInstance(cxx::optional<const RuntimeName_t*> name) noexcept;
/// @brief checks the given application name for certain constraints like length or if is empty
const RuntimeName_t& verifyInstanceName(cxx::optional<const RuntimeName_t*> name) noexcept;
const RuntimeName_t m_appName;
std::atomic<bool> m_shutdownRequested{false};
};
} // namespace runtime
} // namespace iox
#endif // IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
<commit_msg>iox-#449 Fix build with latest clang<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
#define IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
#include "iceoryx_posh/capro/service_description.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp"
#include "iceoryx_posh/internal/popo/ports/application_port.hpp"
#include "iceoryx_posh/internal/popo/ports/interface_port.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp"
#include "iceoryx_posh/internal/runtime/ipc_runtime_interface.hpp"
#include "iceoryx_posh/internal/runtime/node_property.hpp"
#include "iceoryx_posh/popo/subscriber_options.hpp"
#include "iceoryx_posh/runtime/port_config_info.hpp"
#include <atomic>
namespace iox
{
namespace roudi
{
class RuntimeTestInterface;
} // namespace roudi
namespace runtime
{
class Node;
class NodeData;
enum class FindServiceError
{
INVALID_STATE,
UNABLE_TO_WRITE_TO_ROUDI_CHANNEL,
INSTANCE_CONTAINER_OVERFLOW
};
/// @brief The runtime that is needed for each application to communicate with the RouDi daemon
class PoshRuntime
{
public:
PoshRuntime(const PoshRuntime&) = delete;
PoshRuntime& operator=(const PoshRuntime&) = delete;
PoshRuntime(PoshRuntime&&) = delete;
PoshRuntime& operator=(PoshRuntime&&) = delete;
virtual ~PoshRuntime() noexcept = default;
/// @brief returns active runtime
///
/// @return active runtime
static PoshRuntime& getInstance() noexcept;
/// @brief creates the runtime with given name
///
/// @param[in] name used for registering the process with the RouDi daemon
///
/// @return active runtime
static PoshRuntime& initRuntime(const RuntimeName_t& name) noexcept;
/// @brief get the name that was used to register with RouDi
/// @return name of the registered application
RuntimeName_t getInstanceName() const noexcept;
/// @brief initiates the shutdown of the runtime to unblock all potentially blocking publisher
/// with the SubscriberTooSlowPolicy::WAIT_FOR_SUBSCRIBER option set
void shutdown() noexcept;
/// @brief find all services that match the provided service description
/// @param[in] serviceDescription service to search for
/// @return cxx::expected<InstanceContainer, FindServiceError>
/// InstanceContainer: on success, container that is filled with all matching instances
/// FindServiceError: if any, encountered during the operation
virtual cxx::expected<InstanceContainer, FindServiceError>
findService(const capro::ServiceDescription& serviceDescription) noexcept = 0;
/// @brief offer the provided service, sends the offer from application to RouDi daemon
/// @param[in] serviceDescription service to offer
/// @return bool, if service is offered returns true else false
virtual bool offerService(const capro::ServiceDescription& serviceDescription) noexcept = 0;
/// @brief stop offering the provided service
/// @param[in] serviceDescription of the service that shall be no more offered
virtual void stopOfferService(const capro::ServiceDescription& serviceDescription) noexcept = 0;
/// @brief request the RouDi daemon to create a publisher port
/// @param[in] serviceDescription service description for the new publisher port
/// @param[in] publisherOptions like the history capacity of a publisher
/// @param[in] portConfigInfo configuration information for the port
/// (i.e. what type of port is requested, device where its payload memory is located on etc.)
/// @return pointer to a created publisher port user
virtual PublisherPortUserType::MemberType_t*
getMiddlewarePublisher(const capro::ServiceDescription& service,
const popo::PublisherOptions& publisherOptions = popo::PublisherOptions(),
const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;
/// @brief request the RouDi daemon to create a subscriber port
/// @param[in] serviceDescription service description for the new subscriber port
/// @param[in] subscriberOptions like the queue capacity and history requested by a subscriber
/// @param[in] portConfigInfo configuration information for the port
/// (what type of port is requested, device where its payload memory is located on etc.)
/// @return pointer to a created subscriber port data
virtual SubscriberPortUserType::MemberType_t*
getMiddlewareSubscriber(const capro::ServiceDescription& service,
const popo::SubscriberOptions& subscriberOptions = popo::SubscriberOptions(),
const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;
/// @brief request the RouDi daemon to create an interface port
/// @param[in] interface interface to create
/// @param[in] nodeName name of the node where the interface should belong to
/// @return pointer to a created interface port data
virtual popo::InterfacePortData* getMiddlewareInterface(const capro::Interfaces interface,
const NodeName_t& nodeName = {""}) noexcept = 0;
/// @brief request the RouDi daemon to create an application port
/// @return pointer to a created application port data
virtual popo::ApplicationPortData* getMiddlewareApplication() noexcept = 0;
/// @brief request the RouDi daemon to create a condition variable
/// @return pointer to a created condition variable data
virtual popo::ConditionVariableData* getMiddlewareConditionVariable() noexcept = 0;
/// @brief request the RouDi daemon to create a node
/// @param[in] nodeProperty class which contains all properties which the node should have
/// @return pointer to the data of the node
virtual NodeData* createNode(const NodeProperty& nodeProperty) noexcept = 0;
/// @brief requests the serviceRegistryChangeCounter from the shared memory
/// @return pointer to the serviceRegistryChangeCounter
virtual const std::atomic<uint64_t>* getServiceRegistryChangeCounter() noexcept = 0;
/// @brief send a request to the RouDi daemon and get the response
/// currently each request is followed by a response
/// @param[in] msg request message to send
/// @param[out] response from the RouDi daemon
/// @return true if sucessful request/response, false on error
virtual bool sendRequestToRouDi(const IpcMessage& msg, IpcMessage& answer) noexcept = 0;
protected:
friend class roudi::RuntimeTestInterface;
using factory_t = PoshRuntime& (*)(cxx::optional<const RuntimeName_t*>);
// Protected constructor for derived classes
PoshRuntime(cxx::optional<const RuntimeName_t*> name) noexcept;
static PoshRuntime& defaultRuntimeFactory(cxx::optional<const RuntimeName_t*> name) noexcept;
static RuntimeName_t& defaultRuntimeInstanceName() noexcept;
/// @brief gets current runtime factory. If the runtime factory is not yet initialized it is set to
/// defaultRuntimeFactory.
///
/// @return current runtime factory
static factory_t& getRuntimeFactory() noexcept;
/// @brief sets runtime factory, terminates if given factory is empty
///
/// @param[in] factory std::function to which the runtime factory should be set
static void setRuntimeFactory(const factory_t& factory) noexcept;
/// @brief creates the runtime or returns the already existing one -> Singleton
///
/// @param[in] name optional containing the name used for registering with the RouDi daemon
///
/// @return active runtime
static PoshRuntime& getInstance(cxx::optional<const RuntimeName_t*> name) noexcept;
/// @brief checks the given application name for certain constraints like length or if is empty
const RuntimeName_t& verifyInstanceName(cxx::optional<const RuntimeName_t*> name) noexcept;
const RuntimeName_t m_appName;
std::atomic<bool> m_shutdownRequested{false};
};
} // namespace runtime
} // namespace iox
#endif // IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 - 2012 by //
// Simon Pratt //
// (All rights reserved) //
///////////////////////////////////////////////////////////////////////////////
// //
// FILE: test_polygonal_subdivision.cpp //
// //
// MODULE: Polygonal Subdivision //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iterator>
#include <ctime>
#include "../Point2D.hpp"
#include "../LineSegment.hpp"
#include "../PolygonalSubdivision.hpp"
using namespace std;
using namespace geometry;
int main(int argc, char** argv) {
// if not enough parameters provided, print a helpful message and quit
if(argc < 3) {
cout << "usage: " << argv[0] << " [segments file] [points file]" << endl
<< "\t where [segments file] is a file containing line segments" << endl
<< "\t and [points file] is a file containing query points" << endl;
return 0;
}
time_t start = time(0);
time_t last = start;
// for segment input
ifstream segment_file(argv[1]);
istream_iterator<LineSegment> segment_begin(segment_file);
istream_iterator<LineSegment> segment_end;
// for point input
ifstream point_file(argv[2]);
istream_iterator<Point2D> point_begin(point_file);
istream_iterator<Point2D> point_end;
PolygonalSubdivision ps;
// read in the segments
while(segment_begin != segment_end) {
ps.addLineSegment(*segment_begin);
++segment_begin;
}
// ready the structure for queries
ps.lock();
time_t now = time(0);
cout << "Build took: " << difftime(now,last) << endl;
last = now;
// locate and print the containing polygon for each point
while(point_begin != point_end) {
try{
cout << ps.locate_point(*point_begin) << endl;
}catch(char const* str) {
cout << "=== ERROR === " << str << endl;
return 1;
}
++point_begin;
}
now = time(0);
cout << "Queries took: " << difftime(now,last) << endl;
cout << "Total time: " << difftime(now,start) << endl;
last = now;
return 0;
}
<commit_msg>Now printing query points<commit_after>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 - 2012 by //
// Simon Pratt //
// (All rights reserved) //
///////////////////////////////////////////////////////////////////////////////
// //
// FILE: test_polygonal_subdivision.cpp //
// //
// MODULE: Polygonal Subdivision //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iterator>
#include <ctime>
#include "../Point2D.hpp"
#include "../LineSegment.hpp"
#include "../PolygonalSubdivision.hpp"
using namespace std;
using namespace geometry;
int main(int argc, char** argv) {
// if not enough parameters provided, print a helpful message and quit
if(argc < 3) {
cout << "usage: " << argv[0] << " [segments file] [points file]" << endl
<< "\t where [segments file] is a file containing line segments" << endl
<< "\t and [points file] is a file containing query points" << endl;
return 0;
}
time_t start = time(0);
time_t last = start;
// for segment input
ifstream segment_file(argv[1]);
istream_iterator<LineSegment> segment_begin(segment_file);
istream_iterator<LineSegment> segment_end;
// for point input
ifstream point_file(argv[2]);
istream_iterator<Point2D> point_begin(point_file);
istream_iterator<Point2D> point_end;
PolygonalSubdivision ps;
// read in the segments
while(segment_begin != segment_end) {
ps.addLineSegment(*segment_begin);
++segment_begin;
}
// ready the structure for queries
ps.lock();
time_t now = time(0);
cout << "Build took: " << difftime(now,last) << endl;
last = now;
// locate and print the containing polygon for each point
while(point_begin != point_end) {
try{
cout << "Point " << *point_begin << ": "
<< ps.locate_point(*point_begin) << endl;
}catch(char const* str) {
cout << "=== ERROR === " << str << endl;
return 1;
}
++point_begin;
}
now = time(0);
cout << "Queries took: " << difftime(now,last) << endl;
cout << "Total time: " << difftime(now,start) << endl;
last = now;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>`SettingMaster::set_and_print`: print message if Entity name is invalid.<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#if defined(WNT)
#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable: 4917)
#endif
#include "msdasc.h" // OLE DB Service Component header
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include "stdio.h"
#include <initguid.h> // Include only once in your application
#include <adoid.h> // needed for CLSID_CADOConnection
#include <adoint.h> // needed for ADOConnection
#include "adodatalinks.hxx"
BSTR PromptEdit(long hWnd,BSTR connstr);
BSTR PromptNew(long hWnd);
::rtl::OUString getAdoDatalink(long hWnd,::rtl::OUString& oldLink)
{
::rtl::OUString dataLink;
if (oldLink.getLength())
{
dataLink=reinterpret_cast<sal_Unicode *>(PromptEdit(hWnd,(BSTR)oldLink.getStr()));
}
else
dataLink=reinterpret_cast<sal_Unicode *>(PromptNew(hWnd));
return dataLink;
}
BSTR PromptNew(long hWnd)
{
BSTR connstr=NULL;
HRESULT hr;
IDataSourceLocator* dlPrompt = NULL;
ADOConnection* piTmpConnection = NULL;
BSTR _result=NULL;
// Initialize COM
::CoInitialize( NULL );
// Instantiate DataLinks object.
hr = CoCreateInstance(
CLSID_DataLinks, //clsid -- Data Links UI
NULL, //pUnkOuter
CLSCTX_INPROC_SERVER, //dwClsContext
IID_IDataSourceLocator, //riid
(void**)&dlPrompt //ppvObj
);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
dlPrompt->put_hWnd(hWnd);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
// Prompt for connection information.
hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);
if( FAILED( hr ) || !piTmpConnection )
{
dlPrompt->Release( );
return connstr;
}
hr = piTmpConnection->get_ConnectionString(&_result);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
piTmpConnection->Release( );
dlPrompt->Release( );
CoUninitialize();
return _result;
}
BSTR PromptEdit(long hWnd,BSTR connstr)
{
HRESULT hr;
IDataSourceLocator* dlPrompt = NULL;
ADOConnection* piTmpConnection = NULL;
BSTR _result=NULL;
// Initialize COM
::CoInitialize( NULL );
hr = CoCreateInstance(CLSID_CADOConnection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IADOConnection,
(LPVOID *)&piTmpConnection);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
return connstr;
}
hr = piTmpConnection->put_ConnectionString(connstr);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
return connstr;
}
// Instantiate DataLinks object.
hr = CoCreateInstance(
CLSID_DataLinks, //clsid -- Data Links UI
NULL, //pUnkOuter
CLSCTX_INPROC_SERVER, //dwClsContext
IID_IDataSourceLocator, //riid
(void**)&dlPrompt //ppvObj
);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
dlPrompt->put_hWnd(hWnd);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
VARIANT_BOOL pbSuccess;
// Prompt for connection information.
hr = dlPrompt->PromptEdit((IDispatch **)&piTmpConnection,&pbSuccess);
if( SUCCEEDED( hr ) && sal_False == pbSuccess ) //if user press cancel then sal_False == pbSuccess
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
if( FAILED( hr ) )
{
// Prompt for new connection information.
piTmpConnection->Release( );
piTmpConnection = NULL;
hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);
if( FAILED( hr ) || !piTmpConnection )
{
dlPrompt->Release( );
return connstr;
}
}
hr = piTmpConnection->get_ConnectionString(&_result);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
piTmpConnection->Release( );
dlPrompt->Release( );
CoUninitialize();
return _result;
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Plug MinGW gaps<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#if defined(WNT)
#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable: 4917)
#endif
#include "msdasc.h" // OLE DB Service Component header
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include "stdio.h"
#include <initguid.h> // Include only once in your application
#include <adoid.h> // needed for CLSID_CADOConnection
#include <adoint.h> // needed for ADOConnection
#include "adodatalinks.hxx"
#ifdef __MINGW32__
const IID IID_IDataSourceLocator = { 0x2206CCB2, 0x19C1, 0x11D1, { 0x89, 0xE0, 0x00, 0xC0, 0x4F, 0xD7, 0xA8, 0x29 } };
const CLSID CLSID_DataLinks = { 0x2206CDB2, 0x19C1, 0x11D1, { 0x89, 0xE0, 0x00, 0xC0, 0x4F, 0xD7, 0xA8, 0x29 } };
#endif
BSTR PromptEdit(long hWnd,BSTR connstr);
BSTR PromptNew(long hWnd);
::rtl::OUString getAdoDatalink(long hWnd,::rtl::OUString& oldLink)
{
::rtl::OUString dataLink;
if (oldLink.getLength())
{
dataLink=reinterpret_cast<sal_Unicode *>(PromptEdit(hWnd,(BSTR)oldLink.getStr()));
}
else
dataLink=reinterpret_cast<sal_Unicode *>(PromptNew(hWnd));
return dataLink;
}
BSTR PromptNew(long hWnd)
{
BSTR connstr=NULL;
HRESULT hr;
IDataSourceLocator* dlPrompt = NULL;
ADOConnection* piTmpConnection = NULL;
BSTR _result=NULL;
// Initialize COM
::CoInitialize( NULL );
// Instantiate DataLinks object.
hr = CoCreateInstance(
CLSID_DataLinks, //clsid -- Data Links UI
NULL, //pUnkOuter
CLSCTX_INPROC_SERVER, //dwClsContext
IID_IDataSourceLocator, //riid
(void**)&dlPrompt //ppvObj
);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
dlPrompt->put_hWnd(hWnd);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
// Prompt for connection information.
hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);
if( FAILED( hr ) || !piTmpConnection )
{
dlPrompt->Release( );
return connstr;
}
hr = piTmpConnection->get_ConnectionString(&_result);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
piTmpConnection->Release( );
dlPrompt->Release( );
CoUninitialize();
return _result;
}
BSTR PromptEdit(long hWnd,BSTR connstr)
{
HRESULT hr;
IDataSourceLocator* dlPrompt = NULL;
ADOConnection* piTmpConnection = NULL;
BSTR _result=NULL;
// Initialize COM
::CoInitialize( NULL );
hr = CoCreateInstance(CLSID_CADOConnection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IADOConnection,
(LPVOID *)&piTmpConnection);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
return connstr;
}
hr = piTmpConnection->put_ConnectionString(connstr);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
return connstr;
}
// Instantiate DataLinks object.
hr = CoCreateInstance(
CLSID_DataLinks, //clsid -- Data Links UI
NULL, //pUnkOuter
CLSCTX_INPROC_SERVER, //dwClsContext
IID_IDataSourceLocator, //riid
(void**)&dlPrompt //ppvObj
);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
dlPrompt->put_hWnd(hWnd);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
VARIANT_BOOL pbSuccess;
// Prompt for connection information.
hr = dlPrompt->PromptEdit((IDispatch **)&piTmpConnection,&pbSuccess);
if( SUCCEEDED( hr ) && sal_False == pbSuccess ) //if user press cancel then sal_False == pbSuccess
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
if( FAILED( hr ) )
{
// Prompt for new connection information.
piTmpConnection->Release( );
piTmpConnection = NULL;
hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);
if( FAILED( hr ) || !piTmpConnection )
{
dlPrompt->Release( );
return connstr;
}
}
hr = piTmpConnection->get_ConnectionString(&_result);
if( FAILED( hr ) )
{
piTmpConnection->Release( );
dlPrompt->Release( );
return connstr;
}
piTmpConnection->Release( );
dlPrompt->Release( );
CoUninitialize();
return _result;
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>Bugfix: added missing `#include` line.<commit_after><|endoftext|> |
<commit_before>#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h>
#include "graphics/gatherer_graphics.h"
#include "GLContextWindow.h"
#include "OGLESGPGPUTest.h"
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
int main(int argc, char **argv)
{
cv::VideoCapture capture(0);
cv::Size size(int(capture.get(cv::CAP_PROP_FRAME_WIDTH)), int(capture.get(cv::CAP_PROP_FRAME_HEIGHT)));
size = size / 4;
// Create the context
gatherer::graphics::GLContextWindow window(size, "display");
gatherer::graphics::OEGLGPGPUTest test(&window, window.getResolution().x);
while( /*capture */ true )
{
cv::Mat frame;
capture >> frame;
cv::resize(frame, frame, size);
cv::cvtColor(frame, frame, cv::COLOR_BGR2BGRA);
test.captureOutput(frame);
window.swapBuffers();
}
}
<commit_msg>display full resolution video in ogles_gpgpu_test sample<commit_after>#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h>
#include "graphics/gatherer_graphics.h"
#include "GLContextWindow.h"
#include "OGLESGPGPUTest.h"
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
int main(int argc, char **argv)
{
cv::VideoCapture capture(0);
cv::Size size(int(capture.get(cv::CAP_PROP_FRAME_WIDTH)), int(capture.get(cv::CAP_PROP_FRAME_HEIGHT)));
//size = size / 4;
// Create the context
gatherer::graphics::GLContextWindow window(size, "display");
gatherer::graphics::OEGLGPGPUTest test(&window, window.getResolution().x);
while( /*capture */ true )
{
cv::Mat frame;
capture >> frame;
cv::resize(frame, frame, size);
cv::cvtColor(frame, frame, cv::COLOR_BGR2BGRA);
test.captureOutput(frame);
window.swapBuffers();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: javamaker.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:17:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include "sal/main.h"
#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#include <codemaker/typemanager.hxx>
#endif
#include "codemaker/generatedtypeset.hxx"
#include "javaoptions.hxx"
#include "javatype.hxx"
using namespace rtl;
sal_Bool produceAllTypes(RegistryKey& rTypeKey, sal_Bool bIsExtraType,
TypeManager const & typeMgr,
codemaker::GeneratedTypeSet & generated,
JavaOptions* pOptions,
sal_Bool bFullScope)
throw( CannotDumpException )
{
OString typeName = typeMgr.getTypeName(rTypeKey);
if (!produceType(rTypeKey, bIsExtraType, typeMgr, generated, pOptions))
{
fprintf(stderr, "%s ERROR: %s\n",
pOptions->getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
RegistryKeyList::const_iterator iter = typeKeys.begin();
RegistryKey key, subKey;
RegistryKeyArray subKeys;
while (iter != typeKeys.end())
{
key = (*iter).first;
if (!(*iter).second && !key.openSubKeys(OUString(), subKeys))
{
for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
{
subKey = subKeys.getElement(i);
if (bFullScope)
{
if (!produceAllTypes(
subKey, (*iter).second,
typeMgr, generated, pOptions, sal_True))
return sal_False;
} else
{
if (!produceType(subKey, (*iter).second,
typeMgr, generated, pOptions))
return sal_False;
}
}
}
++iter;
}
return sal_True;
}
sal_Bool produceAllTypes(const OString& typeName,
TypeManager const & typeMgr,
codemaker::GeneratedTypeSet & generated,
JavaOptions* pOptions,
sal_Bool bFullScope)
throw( CannotDumpException )
{
if (!produceType(typeName, typeMgr, generated, pOptions))
{
fprintf(stderr, "%s ERROR: %s\n",
pOptions->getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
RegistryKeyList::const_iterator iter = typeKeys.begin();
RegistryKey key, subKey;
RegistryKeyArray subKeys;
while (iter != typeKeys.end())
{
key = (*iter).first;
if (!(*iter).second && !key.openSubKeys(OUString(), subKeys))
{
for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
{
subKey = subKeys.getElement(i);
if (bFullScope)
{
if (!produceAllTypes(
subKey, (*iter).second,
typeMgr, generated, pOptions, sal_True))
return sal_False;
} else
{
if (!produceType(subKey, (*iter).second,
typeMgr, generated, pOptions))
return sal_False;
}
}
}
++iter;
}
return sal_True;
}
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
JavaOptions options;
try
{
if (!options.initOptions(argc, argv))
{
exit(1);
}
}
catch( IllegalArgument& e)
{
fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
exit(99);
}
RegistryTypeManager typeMgr;
if (!typeMgr.init(options.getInputFiles(), options.getExtraInputFiles()))
{
fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
exit(99);
}
if (options.isValid("-B"))
{
typeMgr.setBase(options.getOption("-B"));
}
try
{
if (options.isValid("-T"))
{
OString tOption(options.getOption("-T"));
sal_Int32 nIndex = 0;
codemaker::GeneratedTypeSet generated;
OString typeName, tmpName;
sal_Bool ret = sal_False;
do
{
typeName = tOption.getToken(0, ';', nIndex);
sal_Int32 nPos = typeName.lastIndexOf( '.' );
tmpName = typeName.copy( nPos != -1 ? nPos+1 : 0 );
if (tmpName == "*")
{
// produce this type and his scope.
if (typeName.equals("*"))
{
tmpName = "/";
} else
{
tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
if (tmpName.getLength() == 0)
tmpName = "/";
else
tmpName.replace('.', '/');
}
// related to task #116780# the scope is recursively
// generated. bFullScope = true
ret = produceAllTypes(
tmpName, typeMgr, generated, &options, sal_True);
} else
{
// produce only this type
ret = produceType(
typeName.replace('.', '/'), typeMgr, generated,
&options);
}
if (!ret)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
} while( nIndex != -1 );
} else
{
// produce all types
codemaker::GeneratedTypeSet generated;
if (!produceAllTypes("/", typeMgr, generated, &options, sal_True))
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
"an error occurs while dumping all types.");
exit(99);
}
}
}
catch( CannotDumpException& e)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
e.m_message.getStr());
exit(99);
}
return 0;
}
<commit_msg>INTEGRATION: CWS jsc3 (1.7.16); FILE MERGED 2006/01/20 13:02:25 jsc 1.7.16.1: #i56247# unify include guards<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: javamaker.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2006-03-15 09:16:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include "sal/main.h"
#include "codemaker/typemanager.hxx"
#include "codemaker/generatedtypeset.hxx"
#include "javaoptions.hxx"
#include "javatype.hxx"
using namespace rtl;
sal_Bool produceAllTypes(RegistryKey& rTypeKey, sal_Bool bIsExtraType,
TypeManager const & typeMgr,
codemaker::GeneratedTypeSet & generated,
JavaOptions* pOptions,
sal_Bool bFullScope)
throw( CannotDumpException )
{
OString typeName = typeMgr.getTypeName(rTypeKey);
if (!produceType(rTypeKey, bIsExtraType, typeMgr, generated, pOptions))
{
fprintf(stderr, "%s ERROR: %s\n",
pOptions->getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
RegistryKeyList::const_iterator iter = typeKeys.begin();
RegistryKey key, subKey;
RegistryKeyArray subKeys;
while (iter != typeKeys.end())
{
key = (*iter).first;
if (!(*iter).second && !key.openSubKeys(OUString(), subKeys))
{
for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
{
subKey = subKeys.getElement(i);
if (bFullScope)
{
if (!produceAllTypes(
subKey, (*iter).second,
typeMgr, generated, pOptions, sal_True))
return sal_False;
} else
{
if (!produceType(subKey, (*iter).second,
typeMgr, generated, pOptions))
return sal_False;
}
}
}
++iter;
}
return sal_True;
}
sal_Bool produceAllTypes(const OString& typeName,
TypeManager const & typeMgr,
codemaker::GeneratedTypeSet & generated,
JavaOptions* pOptions,
sal_Bool bFullScope)
throw( CannotDumpException )
{
if (!produceType(typeName, typeMgr, generated, pOptions))
{
fprintf(stderr, "%s ERROR: %s\n",
pOptions->getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
RegistryKeyList::const_iterator iter = typeKeys.begin();
RegistryKey key, subKey;
RegistryKeyArray subKeys;
while (iter != typeKeys.end())
{
key = (*iter).first;
if (!(*iter).second && !key.openSubKeys(OUString(), subKeys))
{
for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
{
subKey = subKeys.getElement(i);
if (bFullScope)
{
if (!produceAllTypes(
subKey, (*iter).second,
typeMgr, generated, pOptions, sal_True))
return sal_False;
} else
{
if (!produceType(subKey, (*iter).second,
typeMgr, generated, pOptions))
return sal_False;
}
}
}
++iter;
}
return sal_True;
}
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
JavaOptions options;
try
{
if (!options.initOptions(argc, argv))
{
exit(1);
}
}
catch( IllegalArgument& e)
{
fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
exit(99);
}
RegistryTypeManager typeMgr;
if (!typeMgr.init(options.getInputFiles(), options.getExtraInputFiles()))
{
fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
exit(99);
}
if (options.isValid("-B"))
{
typeMgr.setBase(options.getOption("-B"));
}
try
{
if (options.isValid("-T"))
{
OString tOption(options.getOption("-T"));
sal_Int32 nIndex = 0;
codemaker::GeneratedTypeSet generated;
OString typeName, tmpName;
sal_Bool ret = sal_False;
do
{
typeName = tOption.getToken(0, ';', nIndex);
sal_Int32 nPos = typeName.lastIndexOf( '.' );
tmpName = typeName.copy( nPos != -1 ? nPos+1 : 0 );
if (tmpName == "*")
{
// produce this type and his scope.
if (typeName.equals("*"))
{
tmpName = "/";
} else
{
tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
if (tmpName.getLength() == 0)
tmpName = "/";
else
tmpName.replace('.', '/');
}
// related to task #116780# the scope is recursively
// generated. bFullScope = true
ret = produceAllTypes(
tmpName, typeMgr, generated, &options, sal_True);
} else
{
// produce only this type
ret = produceType(
typeName.replace('.', '/'), typeMgr, generated,
&options);
}
if (!ret)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
} while( nIndex != -1 );
} else
{
// produce all types
codemaker::GeneratedTypeSet generated;
if (!produceAllTypes("/", typeMgr, generated, &options, sal_True))
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
"an error occurs while dumping all types.");
exit(99);
}
}
}
catch( CannotDumpException& e)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
e.m_message.getStr());
exit(99);
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2012 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt/PendingCaptchas>
#include "TelepathyQt/debug-internal.h"
#include "TelepathyQt/_gen/pending-captchas.moc.hpp"
#include <TelepathyQt/Captcha>
#include <TelepathyQt/captcha-authentication-internal.h>
namespace Tp {
struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
Private(PendingCaptchas *parent);
~Private();
CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
void appendCaptchaResult(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id);
// Public object
PendingCaptchas *parent;
CaptchaAuthentication::ChallengeTypes preferredTypes;
QStringList preferredMimeTypes;
bool multipleRequired;
QList<Captcha> captchas;
int captchasLeft;
CaptchaAuthenticationPtr captchaAuthentication;
ChannelPtr channel;
};
PendingCaptchas::Private::Private(PendingCaptchas *parent)
: parent(parent)
{
}
PendingCaptchas::Private::~Private()
{
}
CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
if (string == QLatin1String("audio_recog")) {
return CaptchaAuthentication::AudioRecognitionChallenge;
} else if (string == QLatin1String("ocr")) {
return CaptchaAuthentication::OCRChallenge;
} else if (string == QLatin1String("picture_q")) {
return CaptchaAuthentication::PictureQuestionChallenge;
} else if (string == QLatin1String("picture_recog")) {
return CaptchaAuthentication::PictureRecognitionChallenge;
} else if (string == QLatin1String("qa")) {
return CaptchaAuthentication::TextQuestionChallenge;
} else if (string == QLatin1String("speech_q")) {
return CaptchaAuthentication::SpeechQuestionChallenge;
} else if (string == QLatin1String("speech_recog")) {
return CaptchaAuthentication::SpeechRecognitionChallenge;
} else if (string == QLatin1String("video_q")) {
return CaptchaAuthentication::VideoQuestionChallenge;
} else if (string == QLatin1String("video_recog")) {
return CaptchaAuthentication::VideoRecognitionChallenge;
}
// Not really making sense...
return CaptchaAuthentication::UnknownChallenge;
}
void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id)
{
// Add to the list
Captcha captchaItem(mimeType, label, data, type, id);
captchas.append(captchaItem);
--captchasLeft;
if (!captchasLeft) {
parent->setFinished();
}
}
/**
* \class PendingCaptchas
* \ingroup client
* \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
*
* \brief The PendingCaptchas class represents an asynchronous
* operation for retrieving a captcha challenge from a connection manager.
*
* See \ref async_model
*/
PendingCaptchas::PendingCaptchas(
const QDBusPendingCall &call,
const QStringList &preferredMimeTypes,
CaptchaAuthentication::ChallengeTypes preferredTypes,
const CaptchaAuthenticationPtr &captchaAuthentication)
: PendingOperation(captchaAuthentication),
mPriv(new Private(this))
{
mPriv->captchaAuthentication = captchaAuthentication;
mPriv->channel = captchaAuthentication->channel();
mPriv->preferredMimeTypes = preferredMimeTypes;
mPriv->preferredTypes = preferredTypes;
/* keep track of channel invalidation */
connect(mPriv->channel.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));
connect(new QDBusPendingCallWatcher(call),
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}
PendingCaptchas::PendingCaptchas(
const QString& errorName,
const QString& errorMessage,
const CaptchaAuthenticationPtr &captchaAuthentication)
: PendingOperation(captchaAuthentication),
mPriv(new PendingCaptchas::Private(this))
{
warning() << "PendingCaptchas created with instant failure";
setFinishedWithError(errorName, errorMessage);
}
/**
* Class destructor.
*/
PendingCaptchas::~PendingCaptchas()
{
delete mPriv;
}
void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
const QString &errorName, const QString &errorMessage)
{
Q_UNUSED(proxy);
if (isFinished()) {
return;
}
warning().nospace() << "PendingCaptchas failed because channel was invalidated with " <<
errorName << ": " << errorMessage;
setFinishedWithError(errorName, errorMessage);
}
void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;
if (reply.isError()) {
debug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
debug() << "Got reply to PendingDBusCall";
Tp::CaptchaInfoList list = qdbus_cast<Tp::CaptchaInfoList>(reply.argumentAt(0));
int howManyRequired = reply.argumentAt(1).toUInt();
// Compute which captchas are required
QList<QPair<Tp::CaptchaInfo,QString> > finalList;
foreach (const Tp::CaptchaInfo &info, list) {
// First of all, mimetype check
QString mimeType;
if (info.availableMIMETypes.isEmpty()) {
// If it's one of the types which might not have a payload, go for it
CaptchaAuthentication::ChallengeTypes noPayloadChallenges(
CaptchaAuthentication::TextQuestionChallenge |
CaptchaAuthentication::UnknownChallenge);
if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) {
// Ok, move on
} else {
// In this case, there's something wrong
warning() << "Got a captcha with type " << info.type << " which does not "
"expose any available mimetype for its payload. Something might be "
"wrong with the connection manager.";
continue;
}
} else if (mPriv->preferredMimeTypes.isEmpty()) {
// No preference, let's take the first of the list
mimeType = info.availableMIMETypes.first();
} else {
QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
mPriv->preferredMimeTypes.toSet());
if (supportedMimeTypes.isEmpty()) {
// Apparently our handler does not support any of this captcha's mimetypes, skip
continue;
}
// Ok, use the first one
mimeType = *supportedMimeTypes.constBegin();
}
// If it's required, easy
if (info.flags & CaptchaFlagRequired) {
finalList.append(qMakePair(info, mimeType));
continue;
}
// Otherwise, let's see if the mimetype matches
if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
finalList.append(qMakePair(info, mimeType));
}
if (finalList.size() == howManyRequired) {
break;
}
}
if (finalList.size() != howManyRequired) {
warning() << "No captchas available matching the specified preferences";
setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
QLatin1String("No captchas matching the handler's request"));
return;
}
// Now, get the infos for all the required captchas in our final list.
mPriv->captchasLeft = finalList.size();
mPriv->multipleRequired = howManyRequired > 1 ? true : false;
for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
i != finalList.constEnd(); ++i) {
// If the captcha does not have a mimetype, we can add it straight
if ((*i).second.isEmpty()) {
mPriv->appendCaptchaResult((*i).second, (*i).first.label, QByteArray(),
mPriv->stringToChallengeType((*i).first.type), (*i).first.ID);
continue;
}
QDBusPendingCall call =
mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
(*i).first.ID, (*i).second);
QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
dataWatcher->setProperty("__Tp_Qt_CaptchaID", (*i).first.ID);
dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", (*i).second);
dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", (*i).first.label);
dataWatcher->setProperty("__Tp_Qt_CaptchaType",
mPriv->stringToChallengeType((*i).first.type));
connect(dataWatcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
}
watcher->deleteLater();
}
void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QByteArray> reply = *watcher;
if (reply.isError()) {
debug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
debug() << "Got reply to PendingDBusCall";
// Add to the list
mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(),
watcher->property("__Tp_Qt_CaptchaLabel").toString(),
reply.value(), static_cast<CaptchaAuthentication::ChallengeType>(
watcher->property("__Tp_Qt_CaptchaType").toUInt()),
watcher->property("__Tp_Qt_CaptchaID").toUInt());
watcher->deleteLater();
}
/**
* Return the main captcha of the request. This captcha is guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* This is a convenience method which should be used when requiresMultipleCaptchas()
* is false - otherwise, you should use captchaList.
*
* The returned Captcha can be answered through CaptchaAuthentication::answer() by
* using its id.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
*
* \sa captchaList()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
Captcha PendingCaptchas::captcha() const
{
if (!isFinished()) {
return Captcha();
}
return mPriv->captchas.first();
}
/**
* Return all the captchas of the request. These captchas are guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* If requiresMultipleCaptchas() is false, you probably want to use the convenience method
* captcha() instead.
*
* The returned Captchas can be answered through CaptchaAuthentication::answer() by
* using their ids.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return All the captchas for the pending request.
*
* \sa captcha()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
QList<Captcha> PendingCaptchas::captchaList() const
{
if (!isFinished()) {
return QList<Captcha>();
}
return mPriv->captchas;
}
/**
* Return whether this request requires more than one captcha to be answered or not.
*
* This method should always be checked before answering to find out what the
* connection manager expects. Depending on the result, you might want to use the
* result from captcha() if just a single answer is required, or from captchaList()
* otherwise.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
*
* \sa captcha()
* captchaList()
*/
bool PendingCaptchas::requiresMultipleCaptchas() const
{
return mPriv->multipleRequired;
}
}
<commit_msg>captcha-authentication: For clarity, use temporary variables to identify members of a hash when iterating<commit_after>/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2012 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt/PendingCaptchas>
#include "TelepathyQt/debug-internal.h"
#include "TelepathyQt/_gen/pending-captchas.moc.hpp"
#include <TelepathyQt/Captcha>
#include <TelepathyQt/captcha-authentication-internal.h>
namespace Tp {
struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
Private(PendingCaptchas *parent);
~Private();
CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
void appendCaptchaResult(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id);
// Public object
PendingCaptchas *parent;
CaptchaAuthentication::ChallengeTypes preferredTypes;
QStringList preferredMimeTypes;
bool multipleRequired;
QList<Captcha> captchas;
int captchasLeft;
CaptchaAuthenticationPtr captchaAuthentication;
ChannelPtr channel;
};
PendingCaptchas::Private::Private(PendingCaptchas *parent)
: parent(parent)
{
}
PendingCaptchas::Private::~Private()
{
}
CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
if (string == QLatin1String("audio_recog")) {
return CaptchaAuthentication::AudioRecognitionChallenge;
} else if (string == QLatin1String("ocr")) {
return CaptchaAuthentication::OCRChallenge;
} else if (string == QLatin1String("picture_q")) {
return CaptchaAuthentication::PictureQuestionChallenge;
} else if (string == QLatin1String("picture_recog")) {
return CaptchaAuthentication::PictureRecognitionChallenge;
} else if (string == QLatin1String("qa")) {
return CaptchaAuthentication::TextQuestionChallenge;
} else if (string == QLatin1String("speech_q")) {
return CaptchaAuthentication::SpeechQuestionChallenge;
} else if (string == QLatin1String("speech_recog")) {
return CaptchaAuthentication::SpeechRecognitionChallenge;
} else if (string == QLatin1String("video_q")) {
return CaptchaAuthentication::VideoQuestionChallenge;
} else if (string == QLatin1String("video_recog")) {
return CaptchaAuthentication::VideoRecognitionChallenge;
}
// Not really making sense...
return CaptchaAuthentication::UnknownChallenge;
}
void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id)
{
// Add to the list
Captcha captchaItem(mimeType, label, data, type, id);
captchas.append(captchaItem);
--captchasLeft;
if (!captchasLeft) {
parent->setFinished();
}
}
/**
* \class PendingCaptchas
* \ingroup client
* \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
*
* \brief The PendingCaptchas class represents an asynchronous
* operation for retrieving a captcha challenge from a connection manager.
*
* See \ref async_model
*/
PendingCaptchas::PendingCaptchas(
const QDBusPendingCall &call,
const QStringList &preferredMimeTypes,
CaptchaAuthentication::ChallengeTypes preferredTypes,
const CaptchaAuthenticationPtr &captchaAuthentication)
: PendingOperation(captchaAuthentication),
mPriv(new Private(this))
{
mPriv->captchaAuthentication = captchaAuthentication;
mPriv->channel = captchaAuthentication->channel();
mPriv->preferredMimeTypes = preferredMimeTypes;
mPriv->preferredTypes = preferredTypes;
/* keep track of channel invalidation */
connect(mPriv->channel.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));
connect(new QDBusPendingCallWatcher(call),
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}
PendingCaptchas::PendingCaptchas(
const QString& errorName,
const QString& errorMessage,
const CaptchaAuthenticationPtr &captchaAuthentication)
: PendingOperation(captchaAuthentication),
mPriv(new PendingCaptchas::Private(this))
{
warning() << "PendingCaptchas created with instant failure";
setFinishedWithError(errorName, errorMessage);
}
/**
* Class destructor.
*/
PendingCaptchas::~PendingCaptchas()
{
delete mPriv;
}
void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
const QString &errorName, const QString &errorMessage)
{
Q_UNUSED(proxy);
if (isFinished()) {
return;
}
warning().nospace() << "PendingCaptchas failed because channel was invalidated with " <<
errorName << ": " << errorMessage;
setFinishedWithError(errorName, errorMessage);
}
void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;
if (reply.isError()) {
debug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
debug() << "Got reply to PendingDBusCall";
Tp::CaptchaInfoList list = qdbus_cast<Tp::CaptchaInfoList>(reply.argumentAt(0));
int howManyRequired = reply.argumentAt(1).toUInt();
// Compute which captchas are required
QList<QPair<Tp::CaptchaInfo,QString> > finalList;
foreach (const Tp::CaptchaInfo &info, list) {
// First of all, mimetype check
QString mimeType;
if (info.availableMIMETypes.isEmpty()) {
// If it's one of the types which might not have a payload, go for it
CaptchaAuthentication::ChallengeTypes noPayloadChallenges(
CaptchaAuthentication::TextQuestionChallenge |
CaptchaAuthentication::UnknownChallenge);
if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) {
// Ok, move on
} else {
// In this case, there's something wrong
warning() << "Got a captcha with type " << info.type << " which does not "
"expose any available mimetype for its payload. Something might be "
"wrong with the connection manager.";
continue;
}
} else if (mPriv->preferredMimeTypes.isEmpty()) {
// No preference, let's take the first of the list
mimeType = info.availableMIMETypes.first();
} else {
QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
mPriv->preferredMimeTypes.toSet());
if (supportedMimeTypes.isEmpty()) {
// Apparently our handler does not support any of this captcha's mimetypes, skip
continue;
}
// Ok, use the first one
mimeType = *supportedMimeTypes.constBegin();
}
// If it's required, easy
if (info.flags & CaptchaFlagRequired) {
finalList.append(qMakePair(info, mimeType));
continue;
}
// Otherwise, let's see if the mimetype matches
if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
finalList.append(qMakePair(info, mimeType));
}
if (finalList.size() == howManyRequired) {
break;
}
}
if (finalList.size() != howManyRequired) {
warning() << "No captchas available matching the specified preferences";
setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
QLatin1String("No captchas matching the handler's request"));
return;
}
// Now, get the infos for all the required captchas in our final list.
mPriv->captchasLeft = finalList.size();
mPriv->multipleRequired = howManyRequired > 1 ? true : false;
for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
i != finalList.constEnd(); ++i) {
QString mimeType = (*i).second;
Tp::CaptchaInfo captchaInfo = (*i).first;
// If the captcha does not have a mimetype, we can add it straight
if (mimeType.isEmpty()) {
mPriv->appendCaptchaResult(mimeType, captchaInfo.label, QByteArray(),
mPriv->stringToChallengeType(captchaInfo.type), captchaInfo.ID);
continue;
}
QDBusPendingCall call =
mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
captchaInfo.ID, mimeType);
QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
dataWatcher->setProperty("__Tp_Qt_CaptchaID", captchaInfo.ID);
dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", mimeType);
dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", captchaInfo.label);
dataWatcher->setProperty("__Tp_Qt_CaptchaType",
mPriv->stringToChallengeType(captchaInfo.type));
connect(dataWatcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
}
watcher->deleteLater();
}
void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QByteArray> reply = *watcher;
if (reply.isError()) {
debug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
debug() << "Got reply to PendingDBusCall";
// Add to the list
mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(),
watcher->property("__Tp_Qt_CaptchaLabel").toString(),
reply.value(), static_cast<CaptchaAuthentication::ChallengeType>(
watcher->property("__Tp_Qt_CaptchaType").toUInt()),
watcher->property("__Tp_Qt_CaptchaID").toUInt());
watcher->deleteLater();
}
/**
* Return the main captcha of the request. This captcha is guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* This is a convenience method which should be used when requiresMultipleCaptchas()
* is false - otherwise, you should use captchaList.
*
* The returned Captcha can be answered through CaptchaAuthentication::answer() by
* using its id.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
*
* \sa captchaList()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
Captcha PendingCaptchas::captcha() const
{
if (!isFinished()) {
return Captcha();
}
return mPriv->captchas.first();
}
/**
* Return all the captchas of the request. These captchas are guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* If requiresMultipleCaptchas() is false, you probably want to use the convenience method
* captcha() instead.
*
* The returned Captchas can be answered through CaptchaAuthentication::answer() by
* using their ids.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return All the captchas for the pending request.
*
* \sa captcha()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
QList<Captcha> PendingCaptchas::captchaList() const
{
if (!isFinished()) {
return QList<Captcha>();
}
return mPriv->captchas;
}
/**
* Return whether this request requires more than one captcha to be answered or not.
*
* This method should always be checked before answering to find out what the
* connection manager expects. Depending on the result, you might want to use the
* result from captcha() if just a single answer is required, or from captchaList()
* otherwise.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
*
* \sa captcha()
* captchaList()
*/
bool PendingCaptchas::requiresMultipleCaptchas() const
{
return mPriv->multipleRequired;
}
}
<|endoftext|> |
<commit_before>/*
* Servo
* read joystick data, normalize, write to servo
*
* @author: Navid Kalaei <[email protected]>
* @github: @navid-kalaei
* @license: MIT
*/
#include "Arduino.h"
#include "Servo.h"
// time to wait in millis
#define DELAY_TIME 200
#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1
#define SERVO_PIN 9
// boundries of analogRead()
#define ANALOG_READ_LOW 0
#define ANALOG_READ_HIGH 1023
// boundries for normalizing analogRead() from -90 to +90
#define NORMALIZE_BOUND_LOW -90
#define NORMALIZE_BOUND_HIGH 90
// use this number to shift normalize value be between 0 to 180
#define NORMALIZE_ORIGIN 90
// the value that joystick has at first
// they're usefull in normalizing
short int joyXOrigin = 0;
short int joyYOrigin = 0;
short int joyXOriginNormalized = 0;
short int joyYOriginNormalized = 0;
short int joyValueX = 0;
short int joyValueY = 0;
short int joyValueXNormalized = 0;
short int joyValueYNormalized = 0;
Servo myServo;
int myServoPos = 0;
short int normalize(short int value){
/*
* a wrapper for map built-in function
*
* @param value: is within analogRead boundries
* @return: normalize value within normalize boundries
*/
// https://www.arduino.cc/en/Reference/Map
// map(value, fromLow, fromHigh, toLow, toHigh)
return map(value,
ANALOG_READ_LOW, ANALOG_READ_HIGH,
NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH);
}
void checkBoundries(short int &value){
/*
* check if value is between normalized boudries or reset it to a boundry
*
* @param value: to check
* @return: void
*/
if(value > NORMALIZE_BOUND_HIGH){
value = NORMALIZE_BOUND_HIGH;
}
else if(value < NORMALIZE_BOUND_LOW){
value = NORMALIZE_BOUND_LOW;
}
}
void setup(){
myServo.attach(SERVO_PIN);
// initialize joystick pins
pinMode(JOY_PIN_X, INPUT);
pinMode(JOY_PIN_Y, INPUT);
joyXOrigin = analogRead(JOY_PIN_X);
joyYOrigin = analogRead(JOY_PIN_Y);
joyXOriginNormalized = normalize(joyXOrigin);
joyYOriginNormalized = normalize(joyYOrigin);
// wait until Serail is not available
while(!Serial);
Serial.begin(SERIAL_RATE);
}
void loop(){
joyValueX = analogRead(JOY_PIN_X);
joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
checkBoundries(joyValueXNormalized);
joyValueY = analogRead(JOY_PIN_Y);
joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
checkBoundries(joyValueYNormalized);
myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN;
myServo.write(myServoPos);
//Serial.println(myServoPos);
// delay(DELAY_TIME);
}
<commit_msg>decorate header comment servo/main.cpp<commit_after>/*************************************************
* Servo *
* read joystick data, normalize, write to servo *
* *
* @author: Navid Kalaei <[email protected]> *
* @github: @navid-kalaei *
* @license: MIT *
*************************************************/
#include "Arduino.h"
#include "Servo.h"
// time to wait in millis
#define DELAY_TIME 200
#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1
#define SERVO_PIN 9
// boundries of analogRead()
#define ANALOG_READ_LOW 0
#define ANALOG_READ_HIGH 1023
// boundries for normalizing analogRead() from -90 to +90
#define NORMALIZE_BOUND_LOW -90
#define NORMALIZE_BOUND_HIGH 90
// use this number to shift normalize value be between 0 to 180
#define NORMALIZE_ORIGIN 90
// the value that joystick has at first
// they're usefull in normalizing
short int joyXOrigin = 0;
short int joyYOrigin = 0;
short int joyXOriginNormalized = 0;
short int joyYOriginNormalized = 0;
short int joyValueX = 0;
short int joyValueY = 0;
short int joyValueXNormalized = 0;
short int joyValueYNormalized = 0;
Servo myServo;
int myServoPos = 0;
short int normalize(short int value){
/*
* a wrapper for map built-in function
*
* @param value: is within analogRead boundries
* @return: normalize value within normalize boundries
*/
// https://www.arduino.cc/en/Reference/Map
// map(value, fromLow, fromHigh, toLow, toHigh)
return map(value,
ANALOG_READ_LOW, ANALOG_READ_HIGH,
NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH);
}
void checkBoundries(short int &value){
/*
* check if value is between normalized boudries or reset it to a boundry
*
* @param value: to check
* @return: void
*/
if(value > NORMALIZE_BOUND_HIGH){
value = NORMALIZE_BOUND_HIGH;
}
else if(value < NORMALIZE_BOUND_LOW){
value = NORMALIZE_BOUND_LOW;
}
}
void setup(){
myServo.attach(SERVO_PIN);
// initialize joystick pins
pinMode(JOY_PIN_X, INPUT);
pinMode(JOY_PIN_Y, INPUT);
joyXOrigin = analogRead(JOY_PIN_X);
joyYOrigin = analogRead(JOY_PIN_Y);
joyXOriginNormalized = normalize(joyXOrigin);
joyYOriginNormalized = normalize(joyYOrigin);
// wait until Serail is not available
while(!Serial);
Serial.begin(SERIAL_RATE);
}
void loop(){
joyValueX = analogRead(JOY_PIN_X);
joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
checkBoundries(joyValueXNormalized);
joyValueY = analogRead(JOY_PIN_Y);
joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
checkBoundries(joyValueYNormalized);
myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN;
myServo.write(myServoPos);
//Serial.println(myServoPos);
// delay(DELAY_TIME);
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "projectmanager.h"
// appleseed.shared headers.
#include "application/application.h"
// Qt headers.
#include <QtConcurrentRun>
// boost headers.
#include "boost/filesystem/path.hpp"
using namespace appleseed::shared;
using namespace boost;
using namespace foundation;
using namespace renderer;
using namespace std;
namespace appleseed {
namespace studio {
//
// ProjectManager class implementation.
//
ProjectManager::ProjectManager()
: m_dirty_flag(false)
{
connect(
&m_async_io_future_watcher, SIGNAL(finished()),
this, SLOT(slot_load_project_async_complete()));
}
void ProjectManager::create_project()
{
const bool result = load_builtin_project("default");
assert(result);
}
void ProjectManager::load_project(const string& filepath)
{
m_async_io_filepath = QString::fromStdString(filepath);
m_async_io_future_watcher.setFuture(
QtConcurrent::run(this, &ProjectManager::do_load_project, filepath));
}
bool ProjectManager::load_builtin_project(const string& name)
{
ProjectFileReader reader;
m_project = reader.load_builtin(name.c_str());
m_dirty_flag = false;
return true;
}
bool ProjectManager::save_project()
{
return do_save_project_as(m_project->get_path());
}
bool ProjectManager::save_project_as(const string& filepath)
{
return do_save_project_as(filepath, ProjectFileWriter::OmitSearchPaths);
}
bool ProjectManager::do_save_project_as(const string& filepath,
ProjectFileWriter::Options options)
{
assert(m_project.get());
if (!ProjectFileWriter::write(m_project.ref(),
filepath.c_str(),
options))
return false;
m_project->set_path(filepath.c_str());
m_dirty_flag = false;
return true;
}
void ProjectManager::close_project()
{
m_project.reset();
m_dirty_flag = false;
}
Project* ProjectManager::get_project() const
{
return m_project.get();
}
bool ProjectManager::is_project_open() const
{
return m_project.get() != 0;
}
string ProjectManager::get_project_display_name() const
{
assert(m_project.get());
if (m_project->has_path())
{
const filesystem::path filepath(m_project->get_path());
return filepath.filename().string();
}
else
{
return "Untitled";
}
}
void ProjectManager::clear_project_dirty_flag()
{
m_dirty_flag = false;
}
void ProjectManager::set_project_dirty_flag()
{
m_dirty_flag = true;
}
bool ProjectManager::is_project_dirty() const
{
return m_dirty_flag;
}
void ProjectManager::slot_load_project_async_complete()
{
// Can't use qobject_cast<>: https://bugreports.qt-project.org/browse/QTBUG-10727.
const bool successful =
static_cast<QFutureWatcher<bool>*>(sender())->future().result();
emit signal_load_project_async_complete(m_async_io_filepath, successful);
}
string ProjectManager::get_project_schema_filepath()
{
const filesystem::path schema_path =
filesystem::path(Application::get_root_path())
/ "schemas"
/ "project.xsd";
return schema_path.string();
}
bool ProjectManager::do_load_project(const string& filepath)
{
const string schema_filepath = get_project_schema_filepath();
ProjectFileReader reader;
auto_release_ptr<Project> loaded_project(
reader.read(filepath.c_str(), schema_filepath.c_str()));
if (loaded_project.get() == 0)
return false;
m_project = loaded_project;
m_dirty_flag = false;
return true;
}
} // namespace studio
} // namespace appleseed
<commit_msg>removed extra whitespace<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "projectmanager.h"
// appleseed.shared headers.
#include "application/application.h"
// Qt headers.
#include <QtConcurrentRun>
// boost headers.
#include "boost/filesystem/path.hpp"
using namespace appleseed::shared;
using namespace boost;
using namespace foundation;
using namespace renderer;
using namespace std;
namespace appleseed {
namespace studio {
//
// ProjectManager class implementation.
//
ProjectManager::ProjectManager()
: m_dirty_flag(false)
{
connect(
&m_async_io_future_watcher, SIGNAL(finished()),
this, SLOT(slot_load_project_async_complete()));
}
void ProjectManager::create_project()
{
const bool result = load_builtin_project("default");
assert(result);
}
void ProjectManager::load_project(const string& filepath)
{
m_async_io_filepath = QString::fromStdString(filepath);
m_async_io_future_watcher.setFuture(
QtConcurrent::run(this, &ProjectManager::do_load_project, filepath));
}
bool ProjectManager::load_builtin_project(const string& name)
{
ProjectFileReader reader;
m_project = reader.load_builtin(name.c_str());
m_dirty_flag = false;
return true;
}
bool ProjectManager::save_project()
{
return do_save_project_as(m_project->get_path());
}
bool ProjectManager::save_project_as(const string& filepath)
{
return do_save_project_as(filepath, ProjectFileWriter::OmitSearchPaths);
}
bool ProjectManager::do_save_project_as(const string& filepath,
ProjectFileWriter::Options options)
{
assert(m_project.get());
if (!ProjectFileWriter::write(m_project.ref(),
filepath.c_str(),
options))
return false;
m_project->set_path(filepath.c_str());
m_dirty_flag = false;
return true;
}
void ProjectManager::close_project()
{
m_project.reset();
m_dirty_flag = false;
}
Project* ProjectManager::get_project() const
{
return m_project.get();
}
bool ProjectManager::is_project_open() const
{
return m_project.get() != 0;
}
string ProjectManager::get_project_display_name() const
{
assert(m_project.get());
if (m_project->has_path())
{
const filesystem::path filepath(m_project->get_path());
return filepath.filename().string();
}
else
{
return "Untitled";
}
}
void ProjectManager::clear_project_dirty_flag()
{
m_dirty_flag = false;
}
void ProjectManager::set_project_dirty_flag()
{
m_dirty_flag = true;
}
bool ProjectManager::is_project_dirty() const
{
return m_dirty_flag;
}
void ProjectManager::slot_load_project_async_complete()
{
// Can't use qobject_cast<>: https://bugreports.qt-project.org/browse/QTBUG-10727.
const bool successful =
static_cast<QFutureWatcher<bool>*>(sender())->future().result();
emit signal_load_project_async_complete(m_async_io_filepath, successful);
}
string ProjectManager::get_project_schema_filepath()
{
const filesystem::path schema_path =
filesystem::path(Application::get_root_path())
/ "schemas"
/ "project.xsd";
return schema_path.string();
}
bool ProjectManager::do_load_project(const string& filepath)
{
const string schema_filepath = get_project_schema_filepath();
ProjectFileReader reader;
auto_release_ptr<Project> loaded_project(
reader.read(filepath.c_str(), schema_filepath.c_str()));
if (loaded_project.get() == 0)
return false;
m_project = loaded_project;
m_dirty_flag = false;
return true;
}
} // namespace studio
} // namespace appleseed
<|endoftext|> |
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <cassert>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <common/Trace.h>
#include <efu/Launcher.h>
#include <iostream>
#include <thread>
#include <map>
void Launcher::launchThreads(std::shared_ptr<Detector> &detector) {
auto startThreadsWithoutAffinity = [&detector]() {
XTRACE(MAIN, ALW, "Launching threads without core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
}
};
auto setThreadCoreAffinity = [](std::thread __attribute__((unused)) &thread, std::uint16_t __attribute__((unused)) core) {
#ifdef __linux__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core, &cpuset);
XTRACE(MAIN, ALW, "Setting thread affinity to core %d\n", core);
GLOG_INF("Setting thread affinity to core " + std::to_string(core));
int __attribute__((unused))s = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t), &cpuset);
assert(s == 0);
}
#else
#pragma message("setaffinity only implemented for Linux")
GLOG_WAR("setaffinity only implemented for Linux");
#endif
};
std::map<std::string,std::uint16_t> AffinityMap;
for (auto &Affinity : ThreadCoreAffinity) {
AffinityMap[Affinity.Name] = Affinity.Core;
}
if (0 == ThreadCoreAffinity.size()) {
startThreadsWithoutAffinity();
} else if (1 == ThreadCoreAffinity.size() and ThreadCoreAffinity[0].Name == "implicit_affinity") {
XTRACE(MAIN, ALW, "Launching threads with implicit core affinity.\n");
int CoreCounter = ThreadCoreAffinity[0].Core;
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
setThreadCoreAffinity(ThreadInfo.thread, CoreCounter++);
}
} else {
XTRACE(MAIN, ALW, "Launching threads with explicit core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
if (1 == AffinityMap.count(ThreadInfo.name)) {
setThreadCoreAffinity(ThreadInfo.thread, AffinityMap[ThreadInfo.name]);
} else {
XTRACE(MAIN, ALW, "No thread core affinity information available for thread with id: %s\n", ThreadInfo.name.c_str());
}
}
}
}
<commit_msg>Minor typo.<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <cassert>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <common/Trace.h>
#include <efu/Launcher.h>
#include <iostream>
#include <thread>
#include <map>
void Launcher::launchThreads(std::shared_ptr<Detector> &detector) {
auto startThreadsWithoutAffinity = [&detector]() {
XTRACE(MAIN, ALW, "Launching threads without core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
}
};
auto setThreadCoreAffinity = [](std::thread __attribute__((unused)) &thread, std::uint16_t __attribute__((unused)) core) {
#ifdef __linux__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core, &cpuset);
XTRACE(MAIN, ALW, "Setting thread affinity to core %d\n", core);
GLOG_INF("Setting thread affinity to core " + std::to_string(core));
int __attribute__((unused))s = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t), &cpuset);
assert(s == 0);
#else
#pragma message("setaffinity only implemented for Linux")
GLOG_WAR("setaffinity only implemented for Linux");
#endif
};
std::map<std::string,std::uint16_t> AffinityMap;
for (auto &Affinity : ThreadCoreAffinity) {
AffinityMap[Affinity.Name] = Affinity.Core;
}
if (0 == ThreadCoreAffinity.size()) {
startThreadsWithoutAffinity();
} else if (1 == ThreadCoreAffinity.size() and ThreadCoreAffinity[0].Name == "implicit_affinity") {
XTRACE(MAIN, ALW, "Launching threads with implicit core affinity.\n");
int CoreCounter = ThreadCoreAffinity[0].Core;
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
setThreadCoreAffinity(ThreadInfo.thread, CoreCounter++);
}
} else {
XTRACE(MAIN, ALW, "Launching threads with explicit core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
if (1 == AffinityMap.count(ThreadInfo.name)) {
setThreadCoreAffinity(ThreadInfo.thread, AffinityMap[ThreadInfo.name]);
} else {
XTRACE(MAIN, ALW, "No thread core affinity information available for thread with id: %s\n", ThreadInfo.name.c_str());
}
}
}
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "masterrenderer.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/drt/drt.h"
#include "renderer/kernel/lighting/ilightingengine.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracing/pathtracing.h"
#include "renderer/kernel/rendering/debug/blanktilerenderer.h"
#include "renderer/kernel/rendering/debug/debugtilerenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/generic/genericsamplegenerator.h"
#include "renderer/kernel/rendering/generic/genericsamplerenderer.h"
#include "renderer/kernel/rendering/generic/generictilerenderer.h"
#include "renderer/kernel/rendering/lighttracing/lighttracingsamplegenerator.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/rendering/iframerenderer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/kernel/rendering/itilerenderer.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingengine.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputbinder.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/core/exceptions/stringexception.h"
// Standard headers.
#include <exception>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// MasterRenderer class implementation.
//
MasterRenderer::MasterRenderer(
Project& project,
const ParamArray& params,
IRendererController* renderer_controller,
ITileCallbackFactory* tile_callback_factory)
: m_project(project)
, m_params(params)
, m_renderer_controller(renderer_controller)
, m_tile_callback_factory(tile_callback_factory)
{
}
ParamArray& MasterRenderer::get_parameters()
{
return m_params;
}
const ParamArray& MasterRenderer::get_parameters() const
{
return m_params;
}
void MasterRenderer::render()
{
try
{
do_render();
}
catch (const StringException& e)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (%s: %s)", e.what(), e.string());
}
catch (const Exception& e)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (%s)", e.what());
}
catch (const bad_alloc&)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (ran out of memory)");
}
catch (...)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (unknown exception)");
}
}
void MasterRenderer::do_render()
{
while (true)
{
m_renderer_controller->on_rendering_begin();
const IRendererController::Status status = initialize_and_render_frame_sequence();
switch (status)
{
case IRendererController::TerminateRendering:
m_renderer_controller->on_rendering_success();
return;
case IRendererController::AbortRendering:
m_renderer_controller->on_rendering_abort();
return;
case IRendererController::ReinitializeRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()
{
assert(m_project.get_scene());
assert(m_project.get_frame());
if (!bind_scene_entities_inputs())
return IRendererController::AbortRendering;
m_project.create_aov_images();
m_project.update_trace_context();
const Scene& scene = *m_project.get_scene();
Frame& frame = *m_project.get_frame();
// Create the light sampler.
LightSampler light_sampler(scene);
// Create the shading engine.
ShadingEngine shading_engine(m_params.child("shading_engine"));
//
// Create a lighting engine factory.
//
auto_ptr<ILightingEngineFactory> lighting_engine_factory;
const string lighting_engine_param =
m_params.get_required<string>("lighting_engine", "pt");
if (lighting_engine_param == "drt")
{
lighting_engine_factory.reset(
new DRTLightingEngineFactory(
light_sampler,
m_params.child("drt")));
}
else if (lighting_engine_param == "pt")
{
lighting_engine_factory.reset(
new PTLightingEngineFactory(
light_sampler,
m_params.child("pt")));
}
//
// Create a sample renderer factory.
//
auto_ptr<ISampleRendererFactory> sample_renderer_factory;
const string sample_renderer_param =
m_params.get_required<string>("sample_renderer", "generic");
if (sample_renderer_param == "generic")
{
sample_renderer_factory.reset(
new GenericSampleRendererFactory(
scene,
frame,
m_project.get_trace_context(),
lighting_engine_factory.get(),
shading_engine,
m_params.child("generic_sample_renderer")));
}
//
// Create a tile renderer factory.
//
auto_ptr<ITileRendererFactory> tile_renderer_factory;
const string tile_renderer_param =
m_params.get_required<string>("tile_renderer", "generic");
if (tile_renderer_param == "generic")
{
tile_renderer_factory.reset(
new GenericTileRendererFactory(
frame,
sample_renderer_factory.get(),
m_params.child("generic_tile_renderer")));
}
else if (tile_renderer_param == "blank")
{
tile_renderer_factory.reset(new BlankTileRendererFactory());
}
else if (tile_renderer_param == "debug")
{
tile_renderer_factory.reset(new DebugTileRendererFactory());
}
//
// Create a sample generator factory.
//
auto_ptr<ISampleGeneratorFactory> sample_generator_factory;
const string sample_generator_param =
m_params.get_optional<string>("sample_generator", "generic");
if (sample_generator_param == "generic")
{
sample_generator_factory.reset(
new GenericSampleGeneratorFactory(
frame,
sample_renderer_factory.get()));
}
else if (sample_generator_param == "lighttracing")
{
sample_generator_factory.reset(
new LightTracingSampleGeneratorFactory(
scene,
frame,
m_project.get_trace_context(),
light_sampler,
m_params.child("lighttracing_sample_generator")));
}
//
// Create a frame renderer.
//
auto_release_ptr<IFrameRenderer> frame_renderer;
const string frame_renderer_param =
m_params.get_required<string>("frame_renderer", "generic");
if (frame_renderer_param == "generic")
{
frame_renderer.reset(
GenericFrameRendererFactory::create(
frame,
tile_renderer_factory.get(),
m_tile_callback_factory,
m_params.child("generic_frame_renderer")));
}
else if (frame_renderer_param == "progressive")
{
frame_renderer.reset(
ProgressiveFrameRendererFactory::create(
m_project,
sample_generator_factory.get(),
m_tile_callback_factory,
m_params.child("progressive_frame_renderer")));
}
// Execute the main rendering loop.
return render_frame_sequence(frame_renderer.get());
}
IRendererController::Status MasterRenderer::render_frame_sequence(IFrameRenderer* frame_renderer)
{
while (true)
{
assert(!frame_renderer->is_rendering());
m_renderer_controller->on_frame_begin();
m_project.get_scene()->on_frame_begin(m_project);
const IRendererController::Status status = render_frame(frame_renderer);
assert(!frame_renderer->is_rendering());
m_project.get_scene()->on_frame_end(m_project);
m_renderer_controller->on_frame_end();
switch (status)
{
case IRendererController::TerminateRendering:
case IRendererController::AbortRendering:
case IRendererController::ReinitializeRendering:
return status;
case IRendererController::RestartRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::render_frame(IFrameRenderer* frame_renderer)
{
frame_renderer->start_rendering();
while (frame_renderer->is_rendering())
{
const IRendererController::Status status = m_renderer_controller->on_progress();
switch (status)
{
case IRendererController::ContinueRendering:
break;
case IRendererController::TerminateRendering:
case IRendererController::AbortRendering:
case IRendererController::ReinitializeRendering:
frame_renderer->terminate_rendering();
return status;
case IRendererController::RestartRendering:
frame_renderer->stop_rendering();
return status;
assert_otherwise;
}
}
return IRendererController::TerminateRendering;
}
bool MasterRenderer::bind_scene_entities_inputs() const
{
InputBinder input_binder;
input_binder.bind(*m_project.get_scene());
return input_binder.get_error_count() == 0;
}
} // namespace renderer
<commit_msg>abort rendering with an error message if a rendering component cannot be created.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "masterrenderer.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/drt/drt.h"
#include "renderer/kernel/lighting/ilightingengine.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracing/pathtracing.h"
#include "renderer/kernel/rendering/debug/blanktilerenderer.h"
#include "renderer/kernel/rendering/debug/debugtilerenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/generic/genericsamplegenerator.h"
#include "renderer/kernel/rendering/generic/genericsamplerenderer.h"
#include "renderer/kernel/rendering/generic/generictilerenderer.h"
#include "renderer/kernel/rendering/lighttracing/lighttracingsamplegenerator.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/rendering/iframerenderer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/kernel/rendering/itilerenderer.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingengine.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputbinder.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/core/exceptions/stringexception.h"
// Standard headers.
#include <exception>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// MasterRenderer class implementation.
//
MasterRenderer::MasterRenderer(
Project& project,
const ParamArray& params,
IRendererController* renderer_controller,
ITileCallbackFactory* tile_callback_factory)
: m_project(project)
, m_params(params)
, m_renderer_controller(renderer_controller)
, m_tile_callback_factory(tile_callback_factory)
{
}
ParamArray& MasterRenderer::get_parameters()
{
return m_params;
}
const ParamArray& MasterRenderer::get_parameters() const
{
return m_params;
}
void MasterRenderer::render()
{
try
{
do_render();
}
catch (const StringException& e)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (%s: %s)", e.what(), e.string());
}
catch (const Exception& e)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (%s)", e.what());
}
catch (const bad_alloc&)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (ran out of memory)");
}
catch (...)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed (unknown exception)");
}
}
void MasterRenderer::do_render()
{
while (true)
{
m_renderer_controller->on_rendering_begin();
const IRendererController::Status status = initialize_and_render_frame_sequence();
switch (status)
{
case IRendererController::TerminateRendering:
m_renderer_controller->on_rendering_success();
return;
case IRendererController::AbortRendering:
m_renderer_controller->on_rendering_abort();
return;
case IRendererController::ReinitializeRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()
{
assert(m_project.get_scene());
assert(m_project.get_frame());
if (!bind_scene_entities_inputs())
return IRendererController::AbortRendering;
m_project.create_aov_images();
m_project.update_trace_context();
const Scene& scene = *m_project.get_scene();
Frame& frame = *m_project.get_frame();
// Create the light sampler.
LightSampler light_sampler(scene);
// Create the shading engine.
ShadingEngine shading_engine(m_params.child("shading_engine"));
//
// Create a lighting engine factory.
//
auto_ptr<ILightingEngineFactory> lighting_engine_factory;
const string lighting_engine_param =
m_params.get_required<string>("lighting_engine", "pt");
if (lighting_engine_param == "drt")
{
lighting_engine_factory.reset(
new DRTLightingEngineFactory(
light_sampler,
m_params.child("drt")));
}
else if (lighting_engine_param == "pt")
{
lighting_engine_factory.reset(
new PTLightingEngineFactory(
light_sampler,
m_params.child("pt")));
}
else
{
RENDERER_LOG_ERROR(
"invalid value for \"lighting_engine\" parameter: \"%s\"",
lighting_engine_param.c_str());
return IRendererController::AbortRendering;
}
//
// Create a sample renderer factory.
//
auto_ptr<ISampleRendererFactory> sample_renderer_factory;
const string sample_renderer_param =
m_params.get_required<string>("sample_renderer", "generic");
if (sample_renderer_param == "generic")
{
sample_renderer_factory.reset(
new GenericSampleRendererFactory(
scene,
frame,
m_project.get_trace_context(),
lighting_engine_factory.get(),
shading_engine,
m_params.child("generic_sample_renderer")));
}
else
{
RENDERER_LOG_ERROR(
"invalid value for \"sample_renderer\" parameter: \"%s\"",
sample_renderer_param.c_str());
return IRendererController::AbortRendering;
}
//
// Create a tile renderer factory.
//
auto_ptr<ITileRendererFactory> tile_renderer_factory;
const string tile_renderer_param =
m_params.get_required<string>("tile_renderer", "generic");
if (tile_renderer_param == "generic")
{
tile_renderer_factory.reset(
new GenericTileRendererFactory(
frame,
sample_renderer_factory.get(),
m_params.child("generic_tile_renderer")));
}
else if (tile_renderer_param == "blank")
{
tile_renderer_factory.reset(new BlankTileRendererFactory());
}
else if (tile_renderer_param == "debug")
{
tile_renderer_factory.reset(new DebugTileRendererFactory());
}
else
{
RENDERER_LOG_ERROR(
"invalid value for \"tile_renderer\" parameter: \"%s\"",
tile_renderer_param.c_str());
return IRendererController::AbortRendering;
}
//
// Create a sample generator factory.
//
auto_ptr<ISampleGeneratorFactory> sample_generator_factory;
const string sample_generator_param =
m_params.get_optional<string>("sample_generator", "generic");
if (sample_generator_param == "generic")
{
sample_generator_factory.reset(
new GenericSampleGeneratorFactory(
frame,
sample_renderer_factory.get()));
}
else if (sample_generator_param == "lighttracing")
{
sample_generator_factory.reset(
new LightTracingSampleGeneratorFactory(
scene,
frame,
m_project.get_trace_context(),
light_sampler,
m_params.child("lighttracing_sample_generator")));
}
else
{
RENDERER_LOG_ERROR(
"invalid value for \"sample_generator\" parameter: \"%s\"",
sample_generator_param.c_str());
return IRendererController::AbortRendering;
}
//
// Create a frame renderer.
//
auto_release_ptr<IFrameRenderer> frame_renderer;
const string frame_renderer_param =
m_params.get_required<string>("frame_renderer", "generic");
if (frame_renderer_param == "generic")
{
frame_renderer.reset(
GenericFrameRendererFactory::create(
frame,
tile_renderer_factory.get(),
m_tile_callback_factory,
m_params.child("generic_frame_renderer")));
}
else if (frame_renderer_param == "progressive")
{
frame_renderer.reset(
ProgressiveFrameRendererFactory::create(
m_project,
sample_generator_factory.get(),
m_tile_callback_factory,
m_params.child("progressive_frame_renderer")));
}
else
{
RENDERER_LOG_ERROR(
"invalid value for \"frame_renderer\" parameter: \"%s\"",
frame_renderer_param.c_str());
return IRendererController::AbortRendering;
}
// Execute the main rendering loop.
return render_frame_sequence(frame_renderer.get());
}
IRendererController::Status MasterRenderer::render_frame_sequence(IFrameRenderer* frame_renderer)
{
while (true)
{
assert(!frame_renderer->is_rendering());
m_renderer_controller->on_frame_begin();
m_project.get_scene()->on_frame_begin(m_project);
const IRendererController::Status status = render_frame(frame_renderer);
assert(!frame_renderer->is_rendering());
m_project.get_scene()->on_frame_end(m_project);
m_renderer_controller->on_frame_end();
switch (status)
{
case IRendererController::TerminateRendering:
case IRendererController::AbortRendering:
case IRendererController::ReinitializeRendering:
return status;
case IRendererController::RestartRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::render_frame(IFrameRenderer* frame_renderer)
{
frame_renderer->start_rendering();
while (frame_renderer->is_rendering())
{
const IRendererController::Status status = m_renderer_controller->on_progress();
switch (status)
{
case IRendererController::ContinueRendering:
break;
case IRendererController::TerminateRendering:
case IRendererController::AbortRendering:
case IRendererController::ReinitializeRendering:
frame_renderer->terminate_rendering();
return status;
case IRendererController::RestartRendering:
frame_renderer->stop_rendering();
return status;
assert_otherwise;
}
}
return IRendererController::TerminateRendering;
}
bool MasterRenderer::bind_scene_entities_inputs() const
{
InputBinder input_binder;
input_binder.bind(*m_project.get_scene());
return input_binder.get_error_count() == 0;
}
} // namespace renderer
<|endoftext|> |
<commit_before>#include "tests.h"
#include <cstdlib>
#include <chrono>
#include <memory>
#include <algorithm>
#include <unordered_set>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <conio.h> // _kbhit
#else
#include <unistd.h>
#include <termios.h>
#endif
namespace rpp
{
int test::asserts_failed;
// there are initialization order issues with this global variable, so wrap it to guarantee initialization order
static vector<test*>& all_tests() noexcept
{
static vector<test*> tests;
return tests;
}
test::test(strview name, bool autorun) : name(name), auto_run(autorun)
{
all_tests().push_back(this);
}
test::~test()
{
if (!all_tests().empty())
{
auto it = find(all_tests().begin(), all_tests().end(), this);
if (it != all_tests().end())
all_tests().erase(it);
}
}
void test::consolef(ConsoleColor color, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
#if _WIN32
static HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
static const int colormap[] = {
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, // Default
FOREGROUND_GREEN, // dark green
FOREGROUND_RED | FOREGROUND_GREEN, // dark yellow
FOREGROUND_RED, // dark red
};
if (color != Default) SetConsoleTextAttribute(console, colormap[color]);
if (color == Red) vfprintf(stderr, fmt, ap);
else vfprintf(stdout, fmt, ap);
if (color != Default) SetConsoleTextAttribute(console, colormap[Default]);
#else // @todo Proper Linux & OSX implementations
if (color == Red) vfprintf(stderr, fmt, ap);
else vfprintf(stdout, fmt, ap);
#endif
}
void test::assert_failed(const char* file, int line, const char* fmt, ...)
{
const char* filename = file + int(strview{ file }.rfindany("\\/") - file) + 1;
char message[8192];
va_list ap; va_start(ap, fmt);
vsnprintf(message, 8192, fmt, ap);
++asserts_failed;
consolef(Red, "FAILURE %12s:%d %s\n", filename, line, message);
}
void test::run_test(strview methodFilter)
{
char title[256];
int len = methodFilter
? snprintf(title, sizeof(title), "-------- running '%s.%.*s' --------", name.str, methodFilter.len, methodFilter.str)
: snprintf(title, sizeof(title), "-------- running '%s' --------", name.str);
consolef(Yellow, "%s\n", title);
run();
auto funcs = test_funcs.data();
auto count = test_funcs.size();
if (methodFilter)
{
for (auto i = 0u; i < count; ++i) {
if (funcs[i].name.find(methodFilter)) {
(funcs[i].lambda.*funcs[i].func)();
}
}
}
else
{
for (auto i = 0u; i < count; ++i) {
(funcs[i].lambda.*funcs[i].func)();
}
}
consolef(Yellow, "%s\n\n", (char*)memset(title, '-', len)); // "-------------"
}
void test::sleep(int millis)
{
#ifdef _WIN32
Sleep(millis);
#else
usleep(millis * 1000);
#endif
}
#ifndef _WIN32 // Linux:
static int _kbhit()
{
termios oldSettings; tcgetattr(STDIN_FILENO, &oldSettings);
termios newSettings = oldSettings;
newSettings.c_cc[VTIME] = 0;
newSettings.c_cc[VMIN] = 0;
newSettings.c_iflag &= ~(IXOFF);
newSettings.c_lflag &= ~(ECHO | ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &newSettings);
char keycodes[16];
int count = (int)::read(fileno(stdin), (void*)keycodes, 16);
tcsetattr(STDIN_FILENO, TCSANOW, &oldSettings);
return count == 0 ? 0 : keycodes[0];
}
#endif
static void pause(int millis = -1/*forever*/)
{
printf("\nPress any key to continue...");
using namespace chrono;
auto start = system_clock::now();
while (!_kbhit())
{
if (millis != -1)
{
auto elapsed = duration_cast<milliseconds>(system_clock::now() - start);
if (elapsed.count() >= millis)
break;
}
test::sleep(50);
}
}
//TestImpl(test_test)
//{
// Implement(test_test)
// {
// Assert(1 == 1);
// }
//}
//Instance;
int test::run_tests(const char* testNamePattern)
{
char empty[1] = "";
char name[1024]; strncpy(name, testNamePattern, 1024);
char* argv[2] = { empty, name };
return run_tests(2, argv);
}
int test::run_tests()
{
char empty[1] = "";
char* argv[1] = { empty };
return run_tests(1, argv);
}
static void move_console_window()
{
// move console window to the other monitor to make test debugging more seamless
// if debugger is attached with Visual Studio
#if _WIN32 && _MSC_VER
int numMonitors = 0;
if (IsDebuggerPresent() && (numMonitors = GetSystemMetrics(SM_CMONITORS)) > 1)
{
vector<HMONITOR> mon;
EnumDisplayMonitors(0, 0, [](HMONITOR monitor, HDC, RECT*, LPARAM data) {
((vector<HMONITOR>*)data)->push_back(monitor); return 1; }, (LPARAM)&mon);
RECT consoleRect; GetWindowRect(GetConsoleWindow(), &consoleRect);
HMONITOR consoleMon = MonitorFromRect(&consoleRect, MONITOR_DEFAULTTONEAREST);
HMONITOR otherMon = consoleMon != mon[0] ? mon[0] : mon[1];
MONITORINFO consoleMI = { sizeof(MONITORINFO) };
MONITORINFO otherMI = { sizeof(MONITORINFO) };
GetMonitorInfo(consoleMon, &consoleMI);
GetMonitorInfo(otherMon, &otherMI);
int x = consoleMI.rcMonitor.left > otherMI.rcMonitor.left // moveLeft ?
? otherMI.rcMonitor.right - (consoleRect.left - consoleMI.rcMonitor.left) - (consoleRect.right-consoleRect.left)
: otherMI.rcMonitor.left + (consoleRect.left - consoleMI.rcMonitor.left);
int y = otherMI.rcMonitor.top + (consoleRect.top - consoleMI.rcMonitor.top);
SetWindowPos(GetConsoleWindow(), 0, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
#endif
}
int test::run_tests(int argc, char* argv[])
{
move_console_window();
for (test* t : all_tests()) { // set the defaults
if (!t->auto_run) t->test_enabled = false;
}
int numTest = 0;
if (argc > 1)
{
// if arg is provided, we assume they are:
// test_testname or testname or -test_testname or -testname
// OR to run a specific test: testname.specifictest
unordered_set<strview> enabled, disabled;
for (int iarg = 1; iarg < argc; ++iarg)
{
rpp::strview arg = argv[iarg];
rpp::strview testName = arg.next('.');
rpp::strview specific = arg.next('.');
const bool enableTest = testName[0] != '-';
if (!enableTest) testName.chomp_first();
const bool exactMatch = testName.starts_with("test_");
if (exactMatch) consolef(Yellow, "Filtering exact tests '%s'\n\n", argv[iarg]);
else consolef(Yellow, "Filtering substr tests '%s'\n\n", argv[iarg]);
for (test* t : all_tests())
{
if (( exactMatch && t->name == testName) ||
(!exactMatch && t->name.find(testName)))
{
t->test_specific = specific;
if (enableTest) enabled.insert(t->name);
else disabled.insert(t->name);
break;
}
}
}
if (disabled.size())
{
for (test* t : all_tests()) {
if (t->auto_run) { // only consider disabling auto_run tests
t->test_enabled = disabled.find(t->name) == disabled.end();
if (!t->test_enabled)
consolef(ConsoleColor::Red, "Disabled test %s", t->name.to_cstr());
}
}
}
else if (enabled.size())
{
for (test* t : all_tests()) { // enable whatever was requested
t->test_enabled = enabled.find(t->name) != enabled.end();
if (t->test_enabled)
consolef(ConsoleColor::Green, "Enabled test %s", t->name.to_cstr());
}
}
}
else
{
consolef(Green, "Running all auto-run tests\n");
}
// run all the marked tests
for (test* t : all_tests()) {
if (t->test_enabled) {
t->run_test();
++numTest;
}
}
if (test::asserts_failed)
{
consolef(Red, "\nWARNING: %d assertions failed!\n", test::asserts_failed);
pause();
return -1;
}
if (numTest > 0)
consolef(Green, "\nSUCCESS: All test runs passed!\n");
else
consolef(Yellow, "\nNOTE: No tests were run! (out of %d)\n", (int)all_tests().size());
pause(5000);
return 0;
}
} // namespace rpp
#if RPP_TESTS_DEFINE_MAIN
int main(int argc, char* argv[])
{
return rpp::test::run_tests(argc, argv);
}
#endif
<commit_msg>Added missing newlines in rpp/tests<commit_after>#include "tests.h"
#include <cstdlib>
#include <chrono>
#include <memory>
#include <algorithm>
#include <unordered_set>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <conio.h> // _kbhit
#else
#include <unistd.h>
#include <termios.h>
#endif
namespace rpp
{
int test::asserts_failed;
// there are initialization order issues with this global variable, so wrap it to guarantee initialization order
static vector<test*>& all_tests() noexcept
{
static vector<test*> tests;
return tests;
}
test::test(strview name, bool autorun) : name(name), auto_run(autorun)
{
all_tests().push_back(this);
}
test::~test()
{
if (!all_tests().empty())
{
auto it = find(all_tests().begin(), all_tests().end(), this);
if (it != all_tests().end())
all_tests().erase(it);
}
}
void test::consolef(ConsoleColor color, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
#if _WIN32
static HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
static const int colormap[] = {
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, // Default
FOREGROUND_GREEN, // dark green
FOREGROUND_RED | FOREGROUND_GREEN, // dark yellow
FOREGROUND_RED, // dark red
};
if (color != Default) SetConsoleTextAttribute(console, colormap[color]);
if (color == Red) vfprintf(stderr, fmt, ap);
else vfprintf(stdout, fmt, ap);
if (color != Default) SetConsoleTextAttribute(console, colormap[Default]);
#else // @todo Proper Linux & OSX implementations
if (color == Red) vfprintf(stderr, fmt, ap);
else vfprintf(stdout, fmt, ap);
#endif
}
void test::assert_failed(const char* file, int line, const char* fmt, ...)
{
const char* filename = file + int(strview{ file }.rfindany("\\/") - file) + 1;
char message[8192];
va_list ap; va_start(ap, fmt);
vsnprintf(message, 8192, fmt, ap);
++asserts_failed;
consolef(Red, "FAILURE %12s:%d %s\n", filename, line, message);
}
void test::run_test(strview methodFilter)
{
char title[256];
int len = methodFilter
? snprintf(title, sizeof(title), "-------- running '%s.%.*s' --------", name.str, methodFilter.len, methodFilter.str)
: snprintf(title, sizeof(title), "-------- running '%s' --------", name.str);
consolef(Yellow, "%s\n", title);
run();
auto funcs = test_funcs.data();
auto count = test_funcs.size();
if (methodFilter)
{
for (auto i = 0u; i < count; ++i) {
if (funcs[i].name.find(methodFilter)) {
(funcs[i].lambda.*funcs[i].func)();
}
}
}
else
{
for (auto i = 0u; i < count; ++i) {
(funcs[i].lambda.*funcs[i].func)();
}
}
consolef(Yellow, "%s\n\n", (char*)memset(title, '-', len)); // "-------------"
}
void test::sleep(int millis)
{
#ifdef _WIN32
Sleep(millis);
#else
usleep(millis * 1000);
#endif
}
#ifndef _WIN32 // Linux:
static int _kbhit()
{
termios oldSettings; tcgetattr(STDIN_FILENO, &oldSettings);
termios newSettings = oldSettings;
newSettings.c_cc[VTIME] = 0;
newSettings.c_cc[VMIN] = 0;
newSettings.c_iflag &= ~(IXOFF);
newSettings.c_lflag &= ~(ECHO | ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &newSettings);
char keycodes[16];
int count = (int)::read(fileno(stdin), (void*)keycodes, 16);
tcsetattr(STDIN_FILENO, TCSANOW, &oldSettings);
return count == 0 ? 0 : keycodes[0];
}
#endif
static void pause(int millis = -1/*forever*/)
{
printf("\nPress any key to continue...");
using namespace chrono;
auto start = system_clock::now();
while (!_kbhit())
{
if (millis != -1)
{
auto elapsed = duration_cast<milliseconds>(system_clock::now() - start);
if (elapsed.count() >= millis)
break;
}
test::sleep(50);
}
}
//TestImpl(test_test)
//{
// Implement(test_test)
// {
// Assert(1 == 1);
// }
//}
//Instance;
int test::run_tests(const char* testNamePattern)
{
char empty[1] = "";
char name[1024]; strncpy(name, testNamePattern, 1024);
char* argv[2] = { empty, name };
return run_tests(2, argv);
}
int test::run_tests()
{
char empty[1] = "";
char* argv[1] = { empty };
return run_tests(1, argv);
}
static void move_console_window()
{
// move console window to the other monitor to make test debugging more seamless
// if debugger is attached with Visual Studio
#if _WIN32 && _MSC_VER
int numMonitors = 0;
if (IsDebuggerPresent() && (numMonitors = GetSystemMetrics(SM_CMONITORS)) > 1)
{
vector<HMONITOR> mon;
EnumDisplayMonitors(0, 0, [](HMONITOR monitor, HDC, RECT*, LPARAM data) {
((vector<HMONITOR>*)data)->push_back(monitor); return 1; }, (LPARAM)&mon);
RECT consoleRect; GetWindowRect(GetConsoleWindow(), &consoleRect);
HMONITOR consoleMon = MonitorFromRect(&consoleRect, MONITOR_DEFAULTTONEAREST);
HMONITOR otherMon = consoleMon != mon[0] ? mon[0] : mon[1];
MONITORINFO consoleMI = { sizeof(MONITORINFO) };
MONITORINFO otherMI = { sizeof(MONITORINFO) };
GetMonitorInfo(consoleMon, &consoleMI);
GetMonitorInfo(otherMon, &otherMI);
int x = consoleMI.rcMonitor.left > otherMI.rcMonitor.left // moveLeft ?
? otherMI.rcMonitor.right - (consoleRect.left - consoleMI.rcMonitor.left) - (consoleRect.right-consoleRect.left)
: otherMI.rcMonitor.left + (consoleRect.left - consoleMI.rcMonitor.left);
int y = otherMI.rcMonitor.top + (consoleRect.top - consoleMI.rcMonitor.top);
SetWindowPos(GetConsoleWindow(), 0, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
#endif
}
int test::run_tests(int argc, char* argv[])
{
move_console_window();
for (test* t : all_tests()) { // set the defaults
if (!t->auto_run) t->test_enabled = false;
}
int numTest = 0;
if (argc > 1)
{
// if arg is provided, we assume they are:
// test_testname or testname or -test_testname or -testname
// OR to run a specific test: testname.specifictest
unordered_set<strview> enabled, disabled;
for (int iarg = 1; iarg < argc; ++iarg)
{
rpp::strview arg = argv[iarg];
rpp::strview testName = arg.next('.');
rpp::strview specific = arg.next('.');
const bool enableTest = testName[0] != '-';
if (!enableTest) testName.chomp_first();
const bool exactMatch = testName.starts_with("test_");
if (exactMatch) consolef(Yellow, "Filtering exact tests '%s'\n\n", argv[iarg]);
else consolef(Yellow, "Filtering substr tests '%s'\n\n", argv[iarg]);
for (test* t : all_tests())
{
if (( exactMatch && t->name == testName) ||
(!exactMatch && t->name.find(testName)))
{
t->test_specific = specific;
if (enableTest) enabled.insert(t->name);
else disabled.insert(t->name);
break;
}
}
}
if (disabled.size())
{
for (test* t : all_tests()) {
if (t->auto_run) { // only consider disabling auto_run tests
t->test_enabled = disabled.find(t->name) == disabled.end();
if (!t->test_enabled)
consolef(ConsoleColor::Red, "Disabled test %s\n", t->name.to_cstr());
}
}
}
else if (enabled.size())
{
for (test* t : all_tests()) { // enable whatever was requested
t->test_enabled = enabled.find(t->name) != enabled.end();
if (t->test_enabled)
consolef(ConsoleColor::Green, "Enabled test %s\n", t->name.to_cstr());
}
}
}
else
{
consolef(Green, "Running all auto-run tests\n");
}
// run all the marked tests
for (test* t : all_tests()) {
if (t->test_enabled) {
t->run_test();
++numTest;
}
}
if (test::asserts_failed)
{
consolef(Red, "\nWARNING: %d assertions failed!\n", test::asserts_failed);
pause();
return -1;
}
if (numTest > 0)
consolef(Green, "\nSUCCESS: All test runs passed!\n");
else
consolef(Yellow, "\nNOTE: No tests were run! (out of %d)\n", (int)all_tests().size());
pause(5000);
return 0;
}
} // namespace rpp
#if RPP_TESTS_DEFINE_MAIN
int main(int argc, char* argv[])
{
return rpp::test::run_tests(argc, argv);
}
#endif
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// transaction_manager.cpp
//
// Identification: src/backend/concurrency/optimistic_transaction_manager.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimistic_transaction_manager.h"
#include "backend/common/platform.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/transaction_record.h"
#include "backend/concurrency/transaction.h"
#include "backend/catalog/manager.h"
#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/tile_group_header.h"
namespace peloton {
namespace concurrency {
OptimisticTransactionManager &OptimisticTransactionManager::GetInstance() {
static OptimisticTransactionManager txn_manager;
return txn_manager;
}
// Visibility check
bool OptimisticTransactionManager::IsVisible(const txn_id_t &tuple_txn_id,
const cid_t &tuple_begin_cid,
const cid_t &tuple_end_cid) {
if (tuple_txn_id == INVALID_TXN_ID) {
// the tuple is not available.
return false;
}
bool own = (current_txn->GetTransactionId() == tuple_txn_id);
// there are exactly two versions that can be owned by a transaction.
if (own == true) {
if (tuple_begin_cid == MAX_CID && tuple_end_cid != INVALID_CID) {
assert(tuple_end_cid == MAX_CID);
// the only version that is visible is the newly inserted one.
return true;
} else {
// the older version is not visible.
return false;
}
} else {
bool activated = (current_txn->GetStartCommitId() >= tuple_begin_cid);
bool invalidated = (current_txn->GetStartCommitId() >= tuple_end_cid);
if (tuple_txn_id != INITIAL_TXN_ID) {
// if the tuple is owned by other transactions.
if (tuple_begin_cid == MAX_CID) {
// currently, we do not handle cascading abort. so never read an
// uncommitted version.
return false;
} else {
// the older version may be visible.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
} else {
// if the tuple is not owned by any transaction.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
}
}
bool OptimisticTransactionManager::RecordRead(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordRead(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordWrite(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordWrite(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordInsert(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordInsert(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordDelete(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordDelete(tile_group_id, tuple_id);
return true;
}
void OptimisticTransactionManager::CommitTransaction() {
LOG_INFO("Committing peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
// generate transaction id.
cid_t end_commit_id = GetNextCommitId();
// validate read set.
auto read_tuples = current_txn->GetReadTuples();
for (auto entry : read_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
if (tile_group_header->GetTransactionId(tuple_slot) ==
current_txn->GetTransactionId()) {
// the version is owned by the transaction.
continue;
} else {
if (tile_group_header->GetTransactionId(tuple_slot) == INITIAL_TXN_ID &&
tile_group_header->GetBeginCommitId(tuple_slot) <= end_commit_id &&
tile_group_header->GetEndCommitId(tuple_slot) >= end_commit_id) {
// the version is not locked and still visible.
continue;
}
}
// otherwise, validation fails. abort transaction.
AbortTransaction();
return;
}
}
//////////////////////////////////////////////////////////
auto written_tuples = current_txn->GetWrittenTuples();
// install all updates.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INITIAL_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
// Logging
// {
// auto &log_manager = logging::LogManager::GetInstance();
// if (log_manager.IsInLoggingMode()) {
// auto logger = log_manager.GetBackendLogger();
// auto record = logger->GetTupleRecord(
// LOGRECORD_TYPE_TUPLE_UPDATE, transaction_->GetTransactionId(),
// target_table_->GetOid(), location, old_location, new_tuple);
// logger->Log(record);
// }
// }
}
}
// commit insert set.
auto inserted_tuples = current_txn->GetInsertedTuples();
for (auto entry : inserted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
for (auto tuple_slot : entry.second) {
tile_group->CommitInsertedTuple(
tuple_slot, current_txn->GetTransactionId(), end_commit_id);
}
// Logging
// {
// auto &log_manager = logging::LogManager::GetInstance();
// if (log_manager.IsInLoggingMode()) {
// auto logger = log_manager.GetBackendLogger();
// auto record = logger->GetTupleRecord(
// LOGRECORD_TYPE_TUPLE_UPDATE, transaction_->GetTransactionId(),
// target_table_->GetOid(), location, old_location, new_tuple);
// logger->Log(record);
// }
// }
}
// commit delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
// Logging
// {
// auto &log_manager = logging::LogManager::GetInstance();
// if (log_manager.IsInLoggingMode()) {
// auto logger = log_manager.GetBackendLogger();
// auto record = logger->GetTupleRecord(
// LOGRECORD_TYPE_TUPLE_UPDATE, transaction_->GetTransactionId(),
// target_table_->GetOid(), location, old_location, new_tuple);
// logger->Log(record);
// }
// }
}
}
delete current_txn;
current_txn = nullptr;
}
void OptimisticTransactionManager::AbortTransaction() {
LOG_INFO("Aborting peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
auto written_tuples = current_txn->GetWrittenTuples();
// recover write set.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
// recover delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
delete current_txn;
current_txn = nullptr;
}
} // End storage namespace
} // End peloton namespace<commit_msg>moved logging to mvcc commit<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// transaction_manager.cpp
//
// Identification: src/backend/concurrency/optimistic_transaction_manager.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimistic_transaction_manager.h"
#include "backend/common/platform.h"
#include "backend/logging/log_record.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/transaction_record.h"
#include "backend/concurrency/transaction.h"
#include "backend/catalog/manager.h"
#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/tile_group_header.h"
namespace peloton {
namespace concurrency {
OptimisticTransactionManager &OptimisticTransactionManager::GetInstance() {
static OptimisticTransactionManager txn_manager;
return txn_manager;
}
// Visibility check
bool OptimisticTransactionManager::IsVisible(const txn_id_t &tuple_txn_id,
const cid_t &tuple_begin_cid,
const cid_t &tuple_end_cid) {
if (tuple_txn_id == INVALID_TXN_ID) {
// the tuple is not available.
return false;
}
bool own = (current_txn->GetTransactionId() == tuple_txn_id);
// there are exactly two versions that can be owned by a transaction.
if (own == true) {
if (tuple_begin_cid == MAX_CID && tuple_end_cid != INVALID_CID) {
assert(tuple_end_cid == MAX_CID);
// the only version that is visible is the newly inserted one.
return true;
} else {
// the older version is not visible.
return false;
}
} else {
bool activated = (current_txn->GetStartCommitId() >= tuple_begin_cid);
bool invalidated = (current_txn->GetStartCommitId() >= tuple_end_cid);
if (tuple_txn_id != INITIAL_TXN_ID) {
// if the tuple is owned by other transactions.
if (tuple_begin_cid == MAX_CID) {
// currently, we do not handle cascading abort. so never read an
// uncommitted version.
return false;
} else {
// the older version may be visible.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
} else {
// if the tuple is not owned by any transaction.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
}
}
bool OptimisticTransactionManager::RecordRead(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordRead(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordWrite(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordWrite(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordInsert(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordInsert(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordDelete(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordDelete(tile_group_id, tuple_id);
return true;
}
void OptimisticTransactionManager::CommitTransaction() {
LOG_INFO("Committing peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
// generate transaction id.
cid_t end_commit_id = GetNextCommitId();
// validate read set.
auto read_tuples = current_txn->GetReadTuples();
for (auto entry : read_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
if (tile_group_header->GetTransactionId(tuple_slot) ==
current_txn->GetTransactionId()) {
// the version is owned by the transaction.
continue;
} else {
if (tile_group_header->GetTransactionId(tuple_slot) == INITIAL_TXN_ID &&
tile_group_header->GetBeginCommitId(tuple_slot) <= end_commit_id &&
tile_group_header->GetEndCommitId(tuple_slot) >= end_commit_id) {
// the version is not locked and still visible.
continue;
}
}
// otherwise, validation fails. abort transaction.
AbortTransaction();
return;
}
}
//////////////////////////////////////////////////////////
auto written_tuples = current_txn->GetWrittenTuples();
auto &log_manager = logging::LogManager::GetInstance();
if (log_manager.IsInLoggingMode()) {
auto logger = log_manager.GetBackendLogger();
auto record = new logging::TransactionRecord(LOGRECORD_TYPE_TRANSACTION_BEGIN, end_commit_id);
logger->Log(record);
}
// install all updates.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INITIAL_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
if (log_manager.IsInLoggingMode()) {
auto logger = log_manager.GetBackendLogger();
ItemPointer old_version(tile_group_id, tuple_slot);
auto new_tuple_tile_group = manager.GetTileGroup(new_version.block);
// TODO assumes in row store for now
auto new_tuple = new_tuple_tile_group->GetTile(0)->GetTupleLocation(new_version.offset);
auto record = logger->GetTupleRecord(
LOGRECORD_TYPE_TUPLE_UPDATE, end_commit_id,
tile_group->GetTableId(), new_version, old_version, new_tuple);
logger->Log(record);
}
}
}
// commit insert set.
auto inserted_tuples = current_txn->GetInsertedTuples();
for (auto entry : inserted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
for (auto tuple_slot : entry.second) {
tile_group->CommitInsertedTuple(
tuple_slot, current_txn->GetTransactionId(), end_commit_id);
if (log_manager.IsInLoggingMode()) {
auto logger = log_manager.GetBackendLogger();
auto new_tuple_tile_group = manager.GetTileGroup(tile_group_id);
// TODO assumes in row store for now
ItemPointer new_version(tile_group_id, tuple_slot);
auto new_tuple = new_tuple_tile_group->GetTile(0)->GetTupleLocation(tuple_slot);
auto record = logger->GetTupleRecord(
LOGRECORD_TYPE_TUPLE_INSERT, end_commit_id,
tile_group->GetTableId(), new_version, INVALID_ITEMPOINTER, new_tuple);
logger->Log(record);
}
}
}
// commit delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
if (log_manager.IsInLoggingMode()) {
auto logger = log_manager.GetBackendLogger();
ItemPointer removed(tile_group_id, tuple_slot);
auto record = logger->GetTupleRecord(
LOGRECORD_TYPE_TUPLE_DELETE, end_commit_id,
tile_group->GetTableId(), INVALID_ITEMPOINTER, removed);
logger->Log(record);
}
}
}
if (log_manager.IsInLoggingMode()) {
auto logger = log_manager.GetBackendLogger();
auto record = new logging::TransactionRecord(LOGRECORD_TYPE_TRANSACTION_COMMIT, end_commit_id);
logger->Log(record);
}
delete current_txn;
current_txn = nullptr;
}
void OptimisticTransactionManager::AbortTransaction() {
LOG_INFO("Aborting peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
auto written_tuples = current_txn->GetWrittenTuples();
// recover write set.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
// recover delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
delete current_txn;
current_txn = nullptr;
}
} // End storage namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/*
* Copyright 2015 BrewPi / Elco Jacobs
*
* This file is part of BrewPi.
*
* BrewPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BrewPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Pid.h"
Pid::Pid(TempSensorBasic * input,
ActuatorRange * output,
SetPoint * setPoint)
{
setConstants(temp_t(0.0), 0, 0);
p = 0;
i = 0;
d = 0;
inputError = 0;
derivative = 0;
integral = 0;
failedReadCount = 255; // start at 255, so inputFilter is refreshed at first valid read
setInputSensor(input);
setOutputActuator(output);
setSetPoint(setPoint);
setInputFilter(0);
// some filtering necessary due to quantization causing steps in the temperature
setDerivativeFilter(2);
actuatorIsNegative = false;
enabled = true;
// autotune = false;
// tuning = false;
// outputLag = 0;
// maxDerivative = 0.0;
}
Pid::~Pid(){}
void Pid::setConstants(temp_long_t kp,
uint16_t ti,
uint16_t td)
{
Kp = kp;
Ti = ti;
Td = td;
}
void Pid::update()
{
temp_t inputVal;
bool disable = !enabled;
if( setPoint->read().isDisabledOrInvalid()){
disable = true;
}
inputVal = inputSensor -> read();
if (inputVal.isDisabledOrInvalid()){
// Could not read from input sensor
if (failedReadCount < 255){ // limit
failedReadCount++;
}
if (failedReadCount > 20){
disable = true; // disable PID if sensor is lost for more than 20 seconds
}
}
else{
if (failedReadCount > 60){ // filters are stale, re-initialize them
inputFilter.init(inputVal);
derivativeFilter.init(temp_precise_t(0.0));
}
failedReadCount = 0;
}
if ( disable ){
return;
}
inputFilter.add(inputVal);
temp_t inputErrorPrevious = inputError;
inputError = inputFilter.readOutput() - setPoint->read();
if( (inputError - inputErrorPrevious) > temp_t (0.15) ||
(inputErrorPrevious - inputError) > temp_t (0.15)){ // more then 2 bits (0.0625 of the input sensor)
integral = 0; // reset integral when the error changes significantly, most likely due to setpoint changes
}
temp_precise_t delta = inputFilter.readOutput() - inputFilter.readPrevOutput();
derivativeFilter.add(delta);
derivative = derivativeFilter.readOutput();
// calculate PID parts.
p = Kp * -inputError;
i = (Ti != 0) ? Kp * (integral/Ti) : temp_long_t(0.0);
d = -Kp * (derivative * Td);
temp_long_t pidResult = temp_long_t(p) + temp_long_t(i) + temp_long_t(d);
// Get output to send to actuator. When actuator is a 'cooler', invert the result
temp_t output = (actuatorIsNegative) ? -pidResult : pidResult;
outputActuator -> setValue(output);
// get actual value from actuator
output = outputActuator->getValue();
// When actuator is a 'cooler', invert the output again
output = (actuatorIsNegative) ? -output : output;
// update integral with anti-windup back calculation
// pidResult - output is zero when actuator is not saturated
// Anti windup gain is 10.0
temp_long_t antiWindup = pidResult - temp_long_t(output);
antiWindup *= 10.0;
integral = integral - inputError;
if(Ti == 0){ // 0 has been chosen to indicate that the integrator is disabled. This also prevents divide by zero.
integral = 0;
}
else if(integral.sign() != (integral-antiWindup).sign()){
// anti-windup would make integral cross zero
integral = 0;
}
else{
if(integral.sign() == antiWindup.sign()){ // make sure anti-windup is towards zero
integral -= antiWindup;
}
}
/*
if(autotune){
tune(output, previousOutput);
}
*/
}
void Pid::setFiltering(uint8_t b){
inputFilter.setFiltering(b);
derivativeFilter.setFiltering(b);
}
uint8_t Pid::getFiltering(){
return inputFilter.getFiltering();
}
void Pid::setInputFilter(uint8_t b)
{
inputFilter.setFiltering(b);
}
void Pid::setDerivativeFilter(uint8_t b)
{
derivativeFilter.setFiltering(b);
}
bool Pid::setInputSensor(TempSensorBasic * s)
{
inputSensor = s;
temp_t t = s -> read();
if (t.isDisabledOrInvalid()){
return false; // could not read from sensor
}
inputFilter.init(t);
derivativeFilter.init(0.0);
return true;
}
bool Pid::setOutputActuator(ActuatorRange * a)
{
outputActuator = a;
return true;
}
/*
// Tune the PID with the Ziegler-Nichols Open-Loop Tuning Method or Process Reaction Method
// This determines the dead time and the reaction rate (max derivative) and calculates the PID parameters from that.
void Pid::tune(temp output, temp previousOutput){
static uint16_t lagTimer = 0;
static temp tuningStartTemp = inputFilter.readOutput();
temp min = outputActuator->min();
temp max = outputActuator->max();
temp tuningThreshold = (max >> uint8_t(1)) + (min >> uint8_t(1)); // (min + max) / 2
if(output == outputActuator->max() && previousOutput < tuningThreshold){
tuning = true; // only start tuning at a big step to the maximum output
}
// cancel tuning when the output is under the tuning threshold before maximum derivative is detected
if(output < tuningThreshold){
if(lagTimer > 2*(derivativeFilter.getDelay() + inputFilter.getDelay())){
tuning = false; // only stop tuning if filters have had time to settle
}
}
// TODO: when this happens, check the filter delay and see if the maximum still has to come
// Detect when at max derivative, the time until this happens is the lag time
// Together with the maximum derivative, this is used to determine the PID parameters
if(tuning){ // only for heating now
// if the derivative of the input starts falling, we have hit an inflection point
// Also check that the derivative is positive
if(derivativeFilter.isFalling() && (derivativeFilter.readOutput() > temp_precise(0))){
maxDerivative = derivativeFilter.readOutput(); // we're at the peak or past it
uint16_t filterDelay = derivativeFilter.getDelay();
uint16_t timeToMaxDerivative = (lagTimer <filterDelay) ? 0 : lagTimer - filterDelay;
// set PID constants to have no overshoot
temp_long deadTime = temp_long(timeToMaxDerivative) / temp_long(60.0); // derivative and integral are per minute, scale back here
temp_long riseTime = (inputFilter.readOutput() - tuningStartTemp) / derivative;
if(riseTime < temp_long(0)){
riseTime = 0.0;
}
deadTime = (deadTime > riseTime) ? deadTime - riseTime : temp_long(0); // rise time is not part of the dead time, eliminate it
outputLag = uint16_t(deadTime * temp_long(60)); // store outputlag in seconds
temp_long RL = derivative * deadTime;
if (RL < temp_long(0.25)){ // prevent divide by zero
Kp = 160.0;
}
else{
Kp = temp_long(100.0*0.4) / RL; // not aggressive. Quarter decay is 1.2 instead of 0.4. We don't want overshoot
}
if(deadTime > temp_long(1)){
Ki = Kp/(deadTime+deadTime);
}
else{
Ki = Kp*temp_long(0.5);
}
Kd = Kp*deadTime*temp_long(0.33);
tuning = false; // tuning ready
}
else{
if(lagTimer < UINT16_MAX){
lagTimer++;
}
}
}
else{
lagTimer= 0;
tuningStartTemp = inputFilter.readOutput();
}
}
*/
<commit_msg>changes to integrator anti-windup so it is symmetric and also works with a fluctuating fridge as setpoint actuator<commit_after>/*
* Copyright 2015 BrewPi / Elco Jacobs
*
* This file is part of BrewPi.
*
* BrewPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BrewPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Pid.h"
Pid::Pid(TempSensorBasic * input,
ActuatorRange * output,
SetPoint * setPoint)
{
setConstants(temp_t(0.0), 0, 0);
p = 0;
i = 0;
d = 0;
inputError = 0;
derivative = 0;
integral = 0;
failedReadCount = 255; // start at 255, so inputFilter is refreshed at first valid read
setInputSensor(input);
setOutputActuator(output);
setSetPoint(setPoint);
setInputFilter(0);
// some filtering necessary due to quantization causing steps in the temperature
setDerivativeFilter(2);
actuatorIsNegative = false;
enabled = true;
// autotune = false;
// tuning = false;
// outputLag = 0;
// maxDerivative = 0.0;
}
Pid::~Pid(){}
void Pid::setConstants(temp_long_t kp,
uint16_t ti,
uint16_t td)
{
Kp = kp;
Ti = ti;
Td = td;
}
void Pid::update()
{
temp_t inputVal;
bool disable = !enabled;
if( setPoint->read().isDisabledOrInvalid()){
disable = true;
}
inputVal = inputSensor -> read();
if (inputVal.isDisabledOrInvalid()){
// Could not read from input sensor
if (failedReadCount < 255){ // limit
failedReadCount++;
}
if (failedReadCount > 20){
disable = true; // disable PID if sensor is lost for more than 20 seconds
}
}
else{
if (failedReadCount > 60){ // filters are stale, re-initialize them
inputFilter.init(inputVal);
derivativeFilter.init(temp_precise_t(0.0));
}
failedReadCount = 0;
}
if ( disable ){
return;
}
inputFilter.add(inputVal);
temp_t inputErrorPrevious = inputError;
inputError = inputFilter.readOutput() - setPoint->read();
if( (inputError - inputErrorPrevious) > temp_t (0.15) ||
(inputErrorPrevious - inputError) > temp_t (0.15)){ // more then 2 bits (0.0625 of the input sensor)
integral = 0; // reset integral when the error changes significantly, most likely due to setpoint changes
}
temp_precise_t delta = inputFilter.readOutput() - inputFilter.readPrevOutput();
derivativeFilter.add(delta);
derivative = derivativeFilter.readOutput();
// calculate PID parts.
p = Kp * -inputError;
i = (Ti != 0) ? Kp * (integral/Ti) : temp_long_t(0.0);
d = -Kp * (derivative * Td);
temp_long_t pidResult = temp_long_t(p) + temp_long_t(i) + temp_long_t(d);
// Get output to send to actuator. When actuator is a 'cooler', invert the result
temp_t output = (actuatorIsNegative) ? -pidResult : pidResult;
outputActuator -> setValue(output);
// get actual value from actuator
output = outputActuator->getValue();
// When actuator is a 'cooler', invert the output again
output = (actuatorIsNegative) ? -output : output;
// update integral with anti-windup back calculation
// pidResult - output is zero when actuator is not saturated
// Anti windup gain is 10.0
temp_long_t antiWindup = pidResult - temp_long_t(output);
temp_long_t antiWindupGain = 10.0;
antiWindup *= antiWindupGain;
integral = integral - inputError;
if(Ti == 0){ // 0 has been chosen to indicate that the integrator is disabled. This also prevents divide by zero.
integral = 0;
}
else if(integral.sign() != (integral-antiWindup).sign()){
// anti-windup would make integral cross zero
integral = 0;
}
else{
integral -= antiWindup/Ti;
}
/*
if(autotune){
tune(output, previousOutput);
}
*/
}
void Pid::setFiltering(uint8_t b){
inputFilter.setFiltering(b);
derivativeFilter.setFiltering(b);
}
uint8_t Pid::getFiltering(){
return inputFilter.getFiltering();
}
void Pid::setInputFilter(uint8_t b)
{
inputFilter.setFiltering(b);
}
void Pid::setDerivativeFilter(uint8_t b)
{
derivativeFilter.setFiltering(b);
}
bool Pid::setInputSensor(TempSensorBasic * s)
{
inputSensor = s;
temp_t t = s -> read();
if (t.isDisabledOrInvalid()){
return false; // could not read from sensor
}
inputFilter.init(t);
derivativeFilter.init(0.0);
return true;
}
bool Pid::setOutputActuator(ActuatorRange * a)
{
outputActuator = a;
return true;
}
/*
// Tune the PID with the Ziegler-Nichols Open-Loop Tuning Method or Process Reaction Method
// This determines the dead time and the reaction rate (max derivative) and calculates the PID parameters from that.
void Pid::tune(temp output, temp previousOutput){
static uint16_t lagTimer = 0;
static temp tuningStartTemp = inputFilter.readOutput();
temp min = outputActuator->min();
temp max = outputActuator->max();
temp tuningThreshold = (max >> uint8_t(1)) + (min >> uint8_t(1)); // (min + max) / 2
if(output == outputActuator->max() && previousOutput < tuningThreshold){
tuning = true; // only start tuning at a big step to the maximum output
}
// cancel tuning when the output is under the tuning threshold before maximum derivative is detected
if(output < tuningThreshold){
if(lagTimer > 2*(derivativeFilter.getDelay() + inputFilter.getDelay())){
tuning = false; // only stop tuning if filters have had time to settle
}
}
// TODO: when this happens, check the filter delay and see if the maximum still has to come
// Detect when at max derivative, the time until this happens is the lag time
// Together with the maximum derivative, this is used to determine the PID parameters
if(tuning){ // only for heating now
// if the derivative of the input starts falling, we have hit an inflection point
// Also check that the derivative is positive
if(derivativeFilter.isFalling() && (derivativeFilter.readOutput() > temp_precise(0))){
maxDerivative = derivativeFilter.readOutput(); // we're at the peak or past it
uint16_t filterDelay = derivativeFilter.getDelay();
uint16_t timeToMaxDerivative = (lagTimer <filterDelay) ? 0 : lagTimer - filterDelay;
// set PID constants to have no overshoot
temp_long deadTime = temp_long(timeToMaxDerivative) / temp_long(60.0); // derivative and integral are per minute, scale back here
temp_long riseTime = (inputFilter.readOutput() - tuningStartTemp) / derivative;
if(riseTime < temp_long(0)){
riseTime = 0.0;
}
deadTime = (deadTime > riseTime) ? deadTime - riseTime : temp_long(0); // rise time is not part of the dead time, eliminate it
outputLag = uint16_t(deadTime * temp_long(60)); // store outputlag in seconds
temp_long RL = derivative * deadTime;
if (RL < temp_long(0.25)){ // prevent divide by zero
Kp = 160.0;
}
else{
Kp = temp_long(100.0*0.4) / RL; // not aggressive. Quarter decay is 1.2 instead of 0.4. We don't want overshoot
}
if(deadTime > temp_long(1)){
Ki = Kp/(deadTime+deadTime);
}
else{
Ki = Kp*temp_long(0.5);
}
Kd = Kp*deadTime*temp_long(0.33);
tuning = false; // tuning ready
}
else{
if(lagTimer < UINT16_MAX){
lagTimer++;
}
}
}
else{
lagTimer= 0;
tuningStartTemp = inputFilter.readOutput();
}
}
*/
<|endoftext|> |
<commit_before><commit_msg>10646 - What is the Card<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <nlohmann/json.hpp>
#include <vector>
#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
#include "RawDepthCalculatorConfig.hpp"
#include "RawImgFrame.hpp"
namespace dai {
struct DepthCalculatorDataOut {
DepthCalculatorConfigData config;
float depth_avg;
float depth_x;
float depth_y;
float depth_z;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(DepthCalculatorDataOut, config, depth_avg);
struct RawDepthCalculatorData : public RawBuffer {
std::vector<DepthCalculatorDataOut> depth;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::DepthCalculatorData;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawDepthCalculatorData, depth);
};
} // namespace dai<commit_msg>Add binding for depth data out<commit_after>#pragma once
#include <cstdint>
#include <nlohmann/json.hpp>
#include <vector>
#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
#include "RawDepthCalculatorConfig.hpp"
#include "RawImgFrame.hpp"
namespace dai {
struct DepthCalculatorDataOut {
DepthCalculatorConfigData config;
float depth_avg;
float depth_x;
float depth_y;
float depth_z;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(DepthCalculatorDataOut, config, depth_avg, depth_x, depth_y, depth_z);
struct RawDepthCalculatorData : public RawBuffer {
std::vector<DepthCalculatorDataOut> depth;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::DepthCalculatorData;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawDepthCalculatorData, depth);
};
} // namespace dai<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"
namespace net {
/* All verb handler identifiers */
enum class messaging_verb : int32_t {
MUTATION,
MUTATION_DONE,
BINARY, // Deprecated
READ_REPAIR,
READ,
READ_DATA,
READ_DIGEST,
REQUEST_RESPONSE, // client-initiated reads and writes
STREAM_INITIATE, // Deprecated
STREAM_INITIATE_DONE, // Deprecated
STREAM_REPLY, // Deprecated
STREAM_REQUEST, // Deprecated
RANGE_SLICE,
BOOTSTRAP_TOKEN, // Deprecated
TREE_REQUEST, // Deprecated
TREE_RESPONSE, // Deprecated
JOIN, // Deprecated
GOSSIP_DIGEST_SYN,
GOSSIP_DIGEST_ACK,
GOSSIP_DIGEST_ACK2,
DEFINITIONS_ANNOUNCE, // Deprecated
DEFINITIONS_UPDATE,
TRUNCATE,
SCHEMA_CHECK,
INDEX_SCAN, // Deprecated
REPLICATION_FINISHED,
INTERNAL_RESPONSE, // responses to internal calls
COUNTER_MUTATION,
STREAMING_REPAIR_REQUEST, // Deprecated
STREAMING_REPAIR_RESPONSE, // Deprecated
SNAPSHOT, // Similar to nt snapshot
MIGRATION_REQUEST,
GOSSIP_SHUTDOWN,
_TRACE,
ECHO,
REPAIR_MESSAGE,
PAXOS_PREPARE,
PAXOS_PROPOSE,
PAXOS_COMMIT,
PAGED_RANGE,
UNUSED_1,
UNUSED_2,
UNUSED_3,
// Used by streaming
STREAM_INIT_MESSAGE,
PREPARE_MESSAGE,
STREAM_MUTATION,
INCOMING_FILE_MESSAGE,
OUTGOING_FILE_MESSAGE,
RECEIVED_MESSAGE,
RETRY_MESSAGE,
COMPLETE_MESSAGE,
SESSION_FAILED_MESSAGE,
LAST,
};
} // namespace net
namespace std {
template <>
class hash<net::messaging_verb> {
public:
size_t operator()(const net::messaging_verb& x) const {
return hash<int32_t>()(int32_t(x));
}
};
} // namespace std
namespace net {
future<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);
future<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);
future<> ser_sstring(output_stream<char>& out, sstring& v);
future<> des_sstring(input_stream<char>& in, sstring& v);
future<> ser_frozen_mutation(output_stream<char>& out, const frozen_mutation& v);
future<> des_frozen_mutation(input_stream<char>& in, frozen_mutation& v);
// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
// T object and should use placement new in case T is non POD
struct serializer {
// For integer type
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto v_ = net::hton(v);
return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
});
}
// For vectors
template<typename T>
inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
return operator()(out, v.size()).then([&out, &v, this] {
return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
return operator()(out, e);
});
});
}
template<typename T>
inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
using size_type = typename std::vector<T>::size_type;
return in.read_exactly(sizeof(size_type)).then([&v, &in, this] (temporary_buffer<char> buf) {
if (buf.size() != sizeof(size_type)) {
throw rpc::closed_error();
}
size_type c = net::ntoh(*reinterpret_cast<const net::packed<size_type>*>(buf.get()));
new (&v) std::vector<T>;
v.reserve(c);
union U {
U(){}
~U(){}
U(U&&) {}
T v;
};
return do_with(U(), [c, &v, &in, this] (U& u) {
return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {
return operator()(in, u.v).then([&u, &v] {
v.emplace_back(std::move(u.v));
});
});
});
});
}
// For messaging_verb
inline auto operator()(output_stream<char>& out, messaging_verb& v) {
return ser_messaging_verb(out, v);
}
inline auto operator()(input_stream<char>& in, messaging_verb& v) {
return des_messaging_verb(in, v);
}
// For sstring
inline auto operator()(output_stream<char>& out, sstring& v) {
return ser_sstring(out, v);
}
inline auto operator()(input_stream<char>& in, sstring& v) {
return des_sstring(in, v);
}
// For frozen_mutation
inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
return ser_frozen_mutation(out, v);
}
inline auto operator()(output_stream<char>& out, frozen_mutation& v) {
return operator()(out, const_cast<const frozen_mutation&>(v));
}
inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
return des_frozen_mutation(in, v);
}
// For complex types which have serialize()/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
!std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto sz = serialize_int32_size + v.serialized_size();
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int32(_out, int32_t(sz - serialize_int32_size));
v.serialize(_out);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
!std::is_enum<T>::value, void*> = nullptr) {
return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int32_size) {
throw rpc::closed_error();
}
size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
new (&v) T(T::deserialize(bv));
assert(bv.size() == 0);
return make_ready_future<>();
});
});
}
};
class messaging_service {
public:
// FIXME: messaging service versioning
static constexpr int32_t current_version = 0;
struct shard_id {
gms::inet_address addr;
uint32_t cpu_id;
friend inline bool operator==(const shard_id& x, const shard_id& y) {
return x.addr == y.addr && x.cpu_id == y.cpu_id ;
}
friend inline bool operator<(const shard_id& x, const shard_id& y) {
if (x.addr < y.addr) {
return true;
} else if (y.addr < x.addr) {
return false;
} else {
return x.cpu_id < y.cpu_id;
}
}
friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
return os << x.addr << ":" << x.cpu_id;
}
struct hash {
size_t operator()(const shard_id& id) const {
return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
}
};
};
struct shard_info {
shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
: rpc_client(std::move(client)) {
}
std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
};
void foreach_client(std::function<void(const messaging_service::shard_id& id,
const messaging_service::shard_info& info)> f) const {
for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
f(i->first, i->second);
}
}
void increment_dropped_messages(messaging_verb verb) {
_dropped_messages[static_cast<int32_t>(verb)]++;
}
uint64_t get_dropped_messages(messaging_verb verb) const {
return _dropped_messages[static_cast<int32_t>(verb)];
}
const uint64_t* get_dropped_messages() const {
return _dropped_messages;
}
int32_t get_raw_version(const gms::inet_address& endpoint) const {
// FIXME: messaging service versioning
return current_version;
}
bool knows_version(const gms::inet_address& endpoint) const {
// FIXME: messaging service versioning
return true;
}
private:
static constexpr uint16_t _default_port = 7000;
gms::inet_address _listen_address;
uint16_t _port;
rpc::protocol<serializer, messaging_verb> _rpc;
rpc::protocol<serializer, messaging_verb>::server _server;
std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
: _listen_address(ip)
, _port(_default_port)
, _rpc(serializer{})
, _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
}
public:
uint16_t port() {
return _port;
}
auto listen_address() {
return _listen_address;
}
future<> stop() {
return when_all(_server.stop(),
parallel_for_each(_clients, [](std::pair<const shard_id, shard_info>& c) {
return c.second.rpc_client->stop();
})
).discard_result();
}
static auto no_wait() {
return rpc::no_wait;
}
public:
// Register a handler (a callback lambda) for verb
template <typename Func>
void register_handler(messaging_verb verb, Func&& func) {
_rpc.register_handler(verb, std::move(func));
}
// Send a message for verb
template <typename MsgIn, typename... MsgOut>
auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
auto& rpc_client = get_rpc_client(id);
auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
try {
if (f.failed()) {
this->increment_dropped_messages(verb);
f.get();
assert(false); // never reached
}
return std::move(f);
} catch(...) {
// FIXME: we need to distinguish between a transport error and
// a server error.
// remove_rpc_client(id);
throw;
}
});
}
template <typename... MsgOut>
auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
}
private:
// Return rpc::protocol::client for a shard which is a ip + cpuid pair.
rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
auto it = _clients.find(id);
if (it == _clients.end()) {
auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
it = _clients.emplace(id, shard_info(std::move(client))).first;
return *it->second.rpc_client;
} else {
return *it->second.rpc_client;
}
}
void remove_rpc_client(shard_id id) {
_clients.erase(id);
}
};
extern distributed<messaging_service> _the_messaging_service;
inline distributed<messaging_service>& get_messaging_service() {
return _the_messaging_service;
}
inline messaging_service& get_local_messaging_service() {
return _the_messaging_service.local();
}
future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<commit_msg>messaging_service: Extract integral reading logic<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"
namespace net {
/* All verb handler identifiers */
enum class messaging_verb : int32_t {
MUTATION,
MUTATION_DONE,
BINARY, // Deprecated
READ_REPAIR,
READ,
READ_DATA,
READ_DIGEST,
REQUEST_RESPONSE, // client-initiated reads and writes
STREAM_INITIATE, // Deprecated
STREAM_INITIATE_DONE, // Deprecated
STREAM_REPLY, // Deprecated
STREAM_REQUEST, // Deprecated
RANGE_SLICE,
BOOTSTRAP_TOKEN, // Deprecated
TREE_REQUEST, // Deprecated
TREE_RESPONSE, // Deprecated
JOIN, // Deprecated
GOSSIP_DIGEST_SYN,
GOSSIP_DIGEST_ACK,
GOSSIP_DIGEST_ACK2,
DEFINITIONS_ANNOUNCE, // Deprecated
DEFINITIONS_UPDATE,
TRUNCATE,
SCHEMA_CHECK,
INDEX_SCAN, // Deprecated
REPLICATION_FINISHED,
INTERNAL_RESPONSE, // responses to internal calls
COUNTER_MUTATION,
STREAMING_REPAIR_REQUEST, // Deprecated
STREAMING_REPAIR_RESPONSE, // Deprecated
SNAPSHOT, // Similar to nt snapshot
MIGRATION_REQUEST,
GOSSIP_SHUTDOWN,
_TRACE,
ECHO,
REPAIR_MESSAGE,
PAXOS_PREPARE,
PAXOS_PROPOSE,
PAXOS_COMMIT,
PAGED_RANGE,
UNUSED_1,
UNUSED_2,
UNUSED_3,
// Used by streaming
STREAM_INIT_MESSAGE,
PREPARE_MESSAGE,
STREAM_MUTATION,
INCOMING_FILE_MESSAGE,
OUTGOING_FILE_MESSAGE,
RECEIVED_MESSAGE,
RETRY_MESSAGE,
COMPLETE_MESSAGE,
SESSION_FAILED_MESSAGE,
LAST,
};
} // namespace net
namespace std {
template <>
class hash<net::messaging_verb> {
public:
size_t operator()(const net::messaging_verb& x) const {
return hash<int32_t>()(int32_t(x));
}
};
} // namespace std
namespace net {
future<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);
future<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);
future<> ser_sstring(output_stream<char>& out, sstring& v);
future<> des_sstring(input_stream<char>& in, sstring& v);
future<> ser_frozen_mutation(output_stream<char>& out, const frozen_mutation& v);
future<> des_frozen_mutation(input_stream<char>& in, frozen_mutation& v);
// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
// T object and should use placement new in case T is non POD
struct serializer {
template<typename T>
inline future<T> read_integral(input_stream<char>& in) {
static_assert(std::is_integral<T>::value, "T should be integral");
return in.read_exactly(sizeof(T)).then([] (temporary_buffer<char> buf) {
if (buf.size() != sizeof(T)) {
throw rpc::closed_error();
}
return make_ready_future<T>(net::ntoh(*unaligned_cast<T*>(buf.get())));
});
}
// For integer type
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto v_ = net::hton(v);
return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
});
}
// For vectors
template<typename T>
inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
return operator()(out, v.size()).then([&out, &v, this] {
return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
return operator()(out, e);
});
});
}
template<typename T>
inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
using size_type = typename std::vector<T>::size_type;
return read_integral<size_type>(in).then([&v, &in, this] (size_type c) {
new (&v) std::vector<T>;
v.reserve(c);
union U {
U(){}
~U(){}
U(U&&) {}
T v;
};
return do_with(U(), [c, &v, &in, this] (U& u) {
return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {
return operator()(in, u.v).then([&u, &v] {
v.emplace_back(std::move(u.v));
});
});
});
});
}
// For messaging_verb
inline auto operator()(output_stream<char>& out, messaging_verb& v) {
return ser_messaging_verb(out, v);
}
inline auto operator()(input_stream<char>& in, messaging_verb& v) {
return des_messaging_verb(in, v);
}
// For sstring
inline auto operator()(output_stream<char>& out, sstring& v) {
return ser_sstring(out, v);
}
inline auto operator()(input_stream<char>& in, sstring& v) {
return des_sstring(in, v);
}
// For frozen_mutation
inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
return ser_frozen_mutation(out, v);
}
inline auto operator()(output_stream<char>& out, frozen_mutation& v) {
return operator()(out, const_cast<const frozen_mutation&>(v));
}
inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
return des_frozen_mutation(in, v);
}
// For complex types which have serialize()/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
!std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto sz = serialize_int32_size + v.serialized_size();
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int32(_out, int32_t(sz - serialize_int32_size));
v.serialize(_out);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
!std::is_enum<T>::value, void*> = nullptr) {
return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int32_size) {
throw rpc::closed_error();
}
size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
new (&v) T(T::deserialize(bv));
assert(bv.size() == 0);
return make_ready_future<>();
});
});
}
};
class messaging_service {
public:
// FIXME: messaging service versioning
static constexpr int32_t current_version = 0;
struct shard_id {
gms::inet_address addr;
uint32_t cpu_id;
friend inline bool operator==(const shard_id& x, const shard_id& y) {
return x.addr == y.addr && x.cpu_id == y.cpu_id ;
}
friend inline bool operator<(const shard_id& x, const shard_id& y) {
if (x.addr < y.addr) {
return true;
} else if (y.addr < x.addr) {
return false;
} else {
return x.cpu_id < y.cpu_id;
}
}
friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
return os << x.addr << ":" << x.cpu_id;
}
struct hash {
size_t operator()(const shard_id& id) const {
return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
}
};
};
struct shard_info {
shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
: rpc_client(std::move(client)) {
}
std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
};
void foreach_client(std::function<void(const messaging_service::shard_id& id,
const messaging_service::shard_info& info)> f) const {
for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
f(i->first, i->second);
}
}
void increment_dropped_messages(messaging_verb verb) {
_dropped_messages[static_cast<int32_t>(verb)]++;
}
uint64_t get_dropped_messages(messaging_verb verb) const {
return _dropped_messages[static_cast<int32_t>(verb)];
}
const uint64_t* get_dropped_messages() const {
return _dropped_messages;
}
int32_t get_raw_version(const gms::inet_address& endpoint) const {
// FIXME: messaging service versioning
return current_version;
}
bool knows_version(const gms::inet_address& endpoint) const {
// FIXME: messaging service versioning
return true;
}
private:
static constexpr uint16_t _default_port = 7000;
gms::inet_address _listen_address;
uint16_t _port;
rpc::protocol<serializer, messaging_verb> _rpc;
rpc::protocol<serializer, messaging_verb>::server _server;
std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
: _listen_address(ip)
, _port(_default_port)
, _rpc(serializer{})
, _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
}
public:
uint16_t port() {
return _port;
}
auto listen_address() {
return _listen_address;
}
future<> stop() {
return when_all(_server.stop(),
parallel_for_each(_clients, [](std::pair<const shard_id, shard_info>& c) {
return c.second.rpc_client->stop();
})
).discard_result();
}
static auto no_wait() {
return rpc::no_wait;
}
public:
// Register a handler (a callback lambda) for verb
template <typename Func>
void register_handler(messaging_verb verb, Func&& func) {
_rpc.register_handler(verb, std::move(func));
}
// Send a message for verb
template <typename MsgIn, typename... MsgOut>
auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
auto& rpc_client = get_rpc_client(id);
auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
try {
if (f.failed()) {
this->increment_dropped_messages(verb);
f.get();
assert(false); // never reached
}
return std::move(f);
} catch(...) {
// FIXME: we need to distinguish between a transport error and
// a server error.
// remove_rpc_client(id);
throw;
}
});
}
template <typename... MsgOut>
auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
}
private:
// Return rpc::protocol::client for a shard which is a ip + cpuid pair.
rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
auto it = _clients.find(id);
if (it == _clients.end()) {
auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
it = _clients.emplace(id, shard_info(std::move(client))).first;
return *it->second.rpc_client;
} else {
return *it->second.rpc_client;
}
}
void remove_rpc_client(shard_id id) {
_clients.erase(id);
}
};
extern distributed<messaging_service> _the_messaging_service;
inline distributed<messaging_service>& get_messaging_service() {
return _the_messaging_service;
}
inline messaging_service& get_local_messaging_service() {
return _the_messaging_service.local();
}
future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<|endoftext|> |
<commit_before>// Filename: config_text.cxx
// Created by: drose (02Mar00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// [email protected] .
//
////////////////////////////////////////////////////////////////////
#include "config_text.h"
#include "staticTextFont.h"
#include "dynamicTextFont.h"
#include "dynamicTextPage.h"
#include "textFont.h"
#include "textNode.h"
#include <dconfig.h>
Configure(config_text);
NotifyCategoryDef(text, "");
ConfigureFn(config_text) {
StaticTextFont::init_type();
DynamicTextFont::init_type();
DynamicTextPage::init_type();
TextFont::init_type();
TextNode::init_type();
}
const bool flatten_text = config_text.GetBool("flatten-text", true);
<commit_msg>fix for build without freetype<commit_after>// Filename: config_text.cxx
// Created by: drose (02Mar00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// [email protected] .
//
////////////////////////////////////////////////////////////////////
#include "config_text.h"
#include "staticTextFont.h"
#include "textFont.h"
#include "textNode.h"
#include "dynamicTextFont.h"
#include "dynamicTextPage.h"
#include <dconfig.h>
Configure(config_text);
NotifyCategoryDef(text, "");
ConfigureFn(config_text) {
StaticTextFont::init_type();
TextFont::init_type();
TextNode::init_type();
#ifdef HAVE_FREETYPE
DynamicTextFont::init_type();
DynamicTextPage::init_type();
#endif
}
const bool flatten_text = config_text.GetBool("flatten-text", true);
<|endoftext|> |
<commit_before>#include "filehandler.h"
/**
* @brief FileHandler::FileHandler
*/
FileHandler::FileHandler()
{
this->m_pid = 0; // zero out counter ids
this->m_fid = 0;
this->m_did = 0;
this->lastError = 0;
}
/**
* @brief FileHandler::create_project
* creates project and associated files.
* @param std::string name
* @return Project* created project
*/
Project* FileHandler::create_project(std::string projName){
Project* proj = new Project(this->m_pid, projName);
this->m_projects.insert(std::make_pair(proj->m_id, proj));
save_project(proj);
this->m_pid++;
return proj;
}
/**
* @brief FileHandler::create_directory
* @param dirpath
* @return unique directory ID
*/
ID FileHandler::create_directory(std::string dirpath){
this->lastError = make_dir(dirpath); //varying implementation, OS dependant
ID id = this->add_dir(dirpath);
return id;
}
/**
* @brief FileHandler::delete_directory
* @param id
* @return errorcode, if deletion was done code is 0;
* otherwise see OS relevant directoryfile.
*/
FH_ERROR FileHandler::delete_directory(ID id){
FH_ERROR err = remove_dir(this->get_dir(id)); //varying implementation, OS dependant
return err;
}
/**
* @todo unfinished, needs full project structure
* and program to file parser to finish
* @brief FileHandler::save_project
* @param Project* name
* Creates project and associated files.
* @return void
*/
void FileHandler::save_project(Project* proj){
std::string projFile = proj->m_name + std::string(".txt"); //filename
if(!proj->saved){
ID dirID = create_directory(std::string(WORKSPACE) + "/"+ proj->m_name);//project directory
proj->files->dir = dirID;
proj->files->f_proj = create_file(projFile, dirID); //create project file
std::string vidFile = proj->m_name + "_videos.txt";
proj->files->f_videos = create_file(vidFile, dirID); //create video file
std::string analysisFile = proj->m_name + "_analyses.txt";
proj->files->f_analysis = create_file(analysisFile, dirID); //create analysis file
std::string drawingFile = proj->m_name + "_drawings.txt";
proj->files->f_drawings =create_file(drawingFile, dirID); //create drawings file
}
update_proj_files(proj);
}
/**
* @todo unfinished, will be released with parser
* however, is needed for creating
* @brief FileHandler::save_project
* @param Project* name
* Creates project and associated files.
* @return void
*/
void FileHandler::update_proj_files(Project* proj){
ProjectStream ps;
ps << *proj;
write_file(proj->files->f_proj, ps.projFile.str(), WRITE_OPTION::OVERWRITE);
write_file(proj->files->f_videos, ps.videos.str(), WRITE_OPTION::OVERWRITE);
write_file(proj->files->f_analysis, ps.analyzes.str(), WRITE_OPTION::OVERWRITE);
write_file(proj->files->f_drawings, ps.drawings.str(), WRITE_OPTION::OVERWRITE);
}
void FileHandler::load_proj_files(std::string str){
ID id;
std::string filepath;
std::stringstream sstr;
sstr << str;
//read files until empty
while(sstr >> id >> filepath){
add_file(id, filepath);
}
}
/**
* @todo load analyses (in project <</>> operators)
* @todo load drawings (in project <</>> operators)
* @brief FileHandler::load_project
* @param projname
* @param dirpath
* @return project
*/
Project* FileHandler::load_project(std::string projname, std::string dirpath){
Project* proj = new Project();
ProjectStream projStream;
proj->saved = true;
// Read project file
std::string projFilePath = dirpath + "/" + projname + ".txt";
proj->files->f_proj = load_project_file(projFilePath, projStream.projFile);
// Read video file
std::string videoFilePath = dirpath + "/" + projname + "_videos.txt";
proj->files->f_videos = load_project_file(videoFilePath, projStream.videos);
// Read Analyzes
std::string analysesFilePath = dirpath + "/" + projname + "_analyses.txt";
proj->files->f_analysis = load_project_file(analysesFilePath, projStream.videos);
// Read Drawings
std::string drawingsFilePath = dirpath + "/" + projname + "_drawings.txt";
proj->files->f_drawings = load_project_file(drawingsFilePath, projStream.drawings);
// Read project from projstream
projStream >> *proj;
return proj;
}
ID FileHandler::load_project_file(std::string filePath, std::stringstream& projFileStream){
std::string buf;
ID projFileID = add_file(filePath);
read_file(projFileID, buf);
projFileStream << buf; // Read project name
return projFileID;
}
/**
* @brief FileHandler::delete_project
* Deletes project, its associated files and contents.
* OBS! This operation is as of now irreversible
* @param Project*
* @return FH_ERROR errorcode
*/
FH_ERROR FileHandler::delete_project(Project* proj){
ProjFiles* pf = proj->files;
delete_file(pf->f_proj);
delete_file(pf->f_videos);
delete_file(pf->f_analysis);
delete_file(pf->f_drawings);
return delete_directory(proj->files->dir);
}
/**
* @todo make threadsafe
* @brief FileHandler::add_video
* @param Project*,string filepath
*
* string
* Add a video filepath to a given project.
* Creates Video object which is accessed further by returned id.
*/
void FileHandler::add_video(Project* proj, std::string filePath){
Video* v = new Video(filePath);
proj->add_video(v);
this->add_file(filePath);
}
/**
* @brief FileHandler::create_file
* create a file by given name in already excisting
* application tracked directory
* @param std::string file name, ID directory id
*/
ID FileHandler::create_file(std::string filename, ID dirID){
std::ofstream f;
std::string filePath = this->get_dir(dirID)+"/"+filename;
f.open(filePath.c_str());
return this->add_file(filePath);
}
/**
* @todo make threadsafe
* @brief FileHandler::delete_file
* delete application tracked file
* @param ID file id
*/
FH_ERROR FileHandler::delete_file(ID id){
std::string file = this->get_file(id);
return std::remove(file.c_str());
}
/**
* @todo make threadsafe
* @brief FileHandler::write_file
* Write given text to an application tracked file
* @param ID file id, std::string text
* @return void
*/
void FileHandler::write_file(ID id, std::string text, WRITE_OPTION opt){
std::string fileName = this->get_file(id);
std::ofstream f;
switch(opt){
case WRITE_OPTION::OVERWRITE:
f.open(fileName.c_str(), std::ios::in | std::ios::out);
break;
case WRITE_OPTION::APPEND:
f.open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::ate);
break;
default:
return; // no open file
break;
}
if(f.is_open()) f << text.c_str() << std::endl;
}
/**
* @brief FileHandler::read_file
* Read given lenght of lines to buffer from application
* tracked file. OBS! If number of lines exceeds =>
* reads to end of file (EOF)
* @param ID file id, std::string text
* @return voi
*/
void FileHandler::read_file(ID id, std::string& buf, int linesToRead){
std::ifstream f(this->get_file(id));
std::string temp;
if(f.is_open()){
while(linesToRead-- && std::getline(f, temp)){
buf += temp;
}
}
}
/**
* @brief FileHandler::get_project
* Getter
* @param ID project id
* @return Project*
*/
Project* FileHandler::get_project(ID pid){
this->projMapLock.lock();
Project* p = this->m_projects.at(pid);
this->projMapLock.unlock();
return p;
}
/**
* @brief FileHandler::get_file
* Getter
* @param ID project file id
* @return std::string filepath
*/
std::string FileHandler::get_file(ID id){
this->fileMapLock.lock();
std::string file = this->m_fileMap.at(id);
this->fileMapLock.unlock();
return file;
}
/**
* @brief FileHandler::get_dir
* @param ID directory id
* @return directory path
*/
std::string FileHandler::get_dir(ID id){
this->dirMapLock.lock();
std::string dir = this->m_dirMap.at(id);
this->dirMapLock.unlock();
return dir;
}
/**
* @brief FileHandler::add_projectr
* @param std::pari<<ID, Project*> pair
* @return void
*/
void FileHandler::add_project(std::pair<ID,Project*> pair){
this->projMapLock.lock();
this->m_projects.insert(pair);
this->projMapLock.unlock();
}
/**
* @brief FileHandler::add_file
* @param std::string filepath
* @return unique file identifier
*/
ID FileHandler::add_file(std::string filepath){
add_file(this->m_fid, filepath);
return this->m_fid++;
}
/**
* @brief FileHandler::add_file
* @param id
* @param filepath
*/
void FileHandler::add_file(ID id ,std::string filepath){
std::pair<ID,std::string> pair = std::make_pair(id, filepath);
this->fileMapLock.lock();
this->m_fileMap.insert(pair);
this->fileMapLock.unlock();
}
/**
* @brief FileHandler::add_dir
* @param std::string dirpath
* @return unique directory identifier
*/
ID FileHandler::add_dir(std::string dirpath){
std::pair<ID,std::string> pair = std::make_pair(this->m_did, dirpath);
this->dirMapLock.lock();
this->m_dirMap.insert(pair);
this->dirMapLock.unlock();
return this->m_did++;
}
<commit_msg>properly set project id on load<commit_after>#include "filehandler.h"
/**
* @brief FileHandler::FileHandler
*/
FileHandler::FileHandler()
{
this->m_pid = 0; // zero out counter ids
this->m_fid = 0;
this->m_did = 0;
this->lastError = 0;
}
/**
* @brief FileHandler::create_project
* creates project and associated files.
* @param std::string name
* @return Project* created project
*/
Project* FileHandler::create_project(std::string projName){
Project* proj = new Project(this->m_pid, projName);
this->m_projects.insert(std::make_pair(proj->m_id, proj));
save_project(proj);
this->m_pid++;
return proj;
}
/**
* @brief FileHandler::create_directory
* @param dirpath
* @return unique directory ID
*/
ID FileHandler::create_directory(std::string dirpath){
this->lastError = make_dir(dirpath); //varying implementation, OS dependant
ID id = this->add_dir(dirpath);
return id;
}
/**
* @brief FileHandler::delete_directory
* @param id
* @return errorcode, if deletion was done code is 0;
* otherwise see OS relevant directoryfile.
*/
FH_ERROR FileHandler::delete_directory(ID id){
FH_ERROR err = remove_dir(this->get_dir(id)); //varying implementation, OS dependant
return err;
}
/**
* @todo unfinished, needs full project structure
* and program to file parser to finish
* @brief FileHandler::save_project
* @param Project* name
* Creates project and associated files.
* @return void
*/
void FileHandler::save_project(Project* proj){
std::string projFile = proj->m_name + std::string(".txt"); //filename
if(!proj->saved){
ID dirID = create_directory(std::string(WORKSPACE) + "/"+ proj->m_name);//project directory
proj->files->dir = dirID;
proj->files->f_proj = create_file(projFile, dirID); //create project file
std::string vidFile = proj->m_name + "_videos.txt";
proj->files->f_videos = create_file(vidFile, dirID); //create video file
std::string analysisFile = proj->m_name + "_analyses.txt";
proj->files->f_analysis = create_file(analysisFile, dirID); //create analysis file
std::string drawingFile = proj->m_name + "_drawings.txt";
proj->files->f_drawings =create_file(drawingFile, dirID); //create drawings file
}
update_proj_files(proj);
}
/**
* @todo unfinished, will be released with parser
* however, is needed for creating
* @brief FileHandler::save_project
* @param Project* name
* Creates project and associated files.
* @return void
*/
void FileHandler::update_proj_files(Project* proj){
ProjectStream ps;
ps << *proj;
write_file(proj->files->f_proj, ps.projFile.str(), WRITE_OPTION::OVERWRITE);
write_file(proj->files->f_videos, ps.videos.str(), WRITE_OPTION::OVERWRITE);
write_file(proj->files->f_analysis, ps.analyzes.str(), WRITE_OPTION::OVERWRITE);
write_file(proj->files->f_drawings, ps.drawings.str(), WRITE_OPTION::OVERWRITE);
}
void FileHandler::load_proj_files(std::string str){
ID id;
std::string filepath;
std::stringstream sstr;
sstr << str;
//read files until empty
while(sstr >> id >> filepath){
add_file(id, filepath);
}
}
/**
* @todo load analyses (in project <</>> operators)
* @todo load drawings (in project <</>> operators)
* @brief FileHandler::load_project
* @param projname
* @param dirpath
* @return project
*/
Project* FileHandler::load_project(std::string projname, std::string dirpath){
Project* proj = new Project();
add_project(std::make_pair(this->m_pid++, proj));
ProjectStream projStream;
proj->saved = true;
// Read project file
std::string projFilePath = dirpath + "/" + projname + ".txt";
proj->files->f_proj = load_project_file(projFilePath, projStream.projFile);
// Read video file
std::string videoFilePath = dirpath + "/" + projname + "_videos.txt";
proj->files->f_videos = load_project_file(videoFilePath, projStream.videos);
// Read Analyzes
std::string analysesFilePath = dirpath + "/" + projname + "_analyses.txt";
proj->files->f_analysis = load_project_file(analysesFilePath, projStream.videos);
// Read Drawings
std::string drawingsFilePath = dirpath + "/" + projname + "_drawings.txt";
proj->files->f_drawings = load_project_file(drawingsFilePath, projStream.drawings);
// Read project from projstream
projStream >> *proj;
return proj;
}
ID FileHandler::load_project_file(std::string filePath, std::stringstream& projFileStream){
std::string buf;
ID projFileID = add_file(filePath);
read_file(projFileID, buf);
projFileStream << buf; // Read project name
return projFileID;
}
/**
* @brief FileHandler::delete_project
* Deletes project, its associated files and contents.
* OBS! This operation is as of now irreversible
* @param Project*
* @return FH_ERROR errorcode
*/
FH_ERROR FileHandler::delete_project(Project* proj){
ProjFiles* pf = proj->files;
delete_file(pf->f_proj);
delete_file(pf->f_videos);
delete_file(pf->f_analysis);
delete_file(pf->f_drawings);
return delete_directory(proj->files->dir);
}
/**
* @todo make threadsafe
* @brief FileHandler::add_video
* @param Project*,string filepath
*
* string
* Add a video filepath to a given project.
* Creates Video object which is accessed further by returned id.
*/
void FileHandler::add_video(Project* proj, std::string filePath){
Video* v = new Video(filePath);
proj->add_video(v);
this->add_file(filePath);
}
/**
* @brief FileHandler::create_file
* create a file by given name in already excisting
* application tracked directory
* @param std::string file name, ID directory id
*/
ID FileHandler::create_file(std::string filename, ID dirID){
std::ofstream f;
std::string filePath = this->get_dir(dirID)+"/"+filename;
f.open(filePath.c_str());
return this->add_file(filePath);
}
/**
* @todo make threadsafe
* @brief FileHandler::delete_file
* delete application tracked file
* @param ID file id
*/
FH_ERROR FileHandler::delete_file(ID id){
std::string file = this->get_file(id);
return std::remove(file.c_str());
}
/**
* @todo make threadsafe
* @brief FileHandler::write_file
* Write given text to an application tracked file
* @param ID file id, std::string text
* @return void
*/
void FileHandler::write_file(ID id, std::string text, WRITE_OPTION opt){
std::string fileName = this->get_file(id);
std::ofstream f;
switch(opt){
case WRITE_OPTION::OVERWRITE:
f.open(fileName.c_str(), std::ios::in | std::ios::out);
break;
case WRITE_OPTION::APPEND:
f.open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::ate);
break;
default:
return; // no open file
break;
}
if(f.is_open()) f << text.c_str() << std::endl;
}
/**
* @brief FileHandler::read_file
* Read given lenght of lines to buffer from application
* tracked file. OBS! If number of lines exceeds =>
* reads to end of file (EOF)
* @param ID file id, std::string text
* @return voi
*/
void FileHandler::read_file(ID id, std::string& buf, int linesToRead){
std::ifstream f(this->get_file(id));
std::string temp;
if(f.is_open()){
while(linesToRead-- && std::getline(f, temp)){
buf += temp;
}
}
}
/**
* @brief FileHandler::get_project
* Getter
* @param ID project id
* @return Project*
*/
Project* FileHandler::get_project(ID pid){
this->projMapLock.lock();
Project* p = this->m_projects.at(pid);
this->projMapLock.unlock();
return p;
}
/**
* @brief FileHandler::get_file
* Getter
* @param ID project file id
* @return std::string filepath
*/
std::string FileHandler::get_file(ID id){
this->fileMapLock.lock();
std::string file = this->m_fileMap.at(id);
this->fileMapLock.unlock();
return file;
}
/**
* @brief FileHandler::get_dir
* @param ID directory id
* @return directory path
*/
std::string FileHandler::get_dir(ID id){
this->dirMapLock.lock();
std::string dir = this->m_dirMap.at(id);
this->dirMapLock.unlock();
return dir;
}
/**
* @brief FileHandler::add_projectr
* @param std::pari<<ID, Project*> pair
* @return void
*/
void FileHandler::add_project(std::pair<ID,Project*> pair){
this->projMapLock.lock();
this->m_projects.insert(pair);
this->projMapLock.unlock();
}
/**
* @brief FileHandler::add_file
* @param std::string filepath
* @return unique file identifier
*/
ID FileHandler::add_file(std::string filepath){
add_file(this->m_fid, filepath);
return this->m_fid++;
}
/**
* @brief FileHandler::add_file
* @param id
* @param filepath
*/
void FileHandler::add_file(ID id ,std::string filepath){
std::pair<ID,std::string> pair = std::make_pair(id, filepath);
this->fileMapLock.lock();
this->m_fileMap.insert(pair);
this->fileMapLock.unlock();
}
/**
* @brief FileHandler::add_dir
* @param std::string dirpath
* @return unique directory identifier
*/
ID FileHandler::add_dir(std::string dirpath){
std::pair<ID,std::string> pair = std::make_pair(this->m_did, dirpath);
this->dirMapLock.lock();
this->m_dirMap.insert(pair);
this->dirMapLock.unlock();
return this->m_did++;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/ASTDeserializationListener.h"
using namespace clang;
namespace cling {
///\brief Translates 'interesting' for the interpreter
/// ASTDeserializationListener events into interpreter callback.
///
class InterpreterPPCallbacks : public PPCallbacks {
private:
cling::InterpreterCallbacks* m_Callbacks;
public:
InterpreterPPCallbacks(InterpreterCallbacks* C) : m_Callbacks(C) { }
~InterpreterPPCallbacks() { }
virtual bool FileNotFound(llvm::StringRef FileName,
llvm::SmallVectorImpl<char>& RecoveryPath) {
if (m_Callbacks)
return m_Callbacks->FileNotFound(FileName, RecoveryPath);
// Returning true would mean that the preprocessor should try to recover.
return false;
}
};
///\brief Translates 'interesting' for the interpreter
/// ASTDeserializationListener events into interpreter callback.
///
class InterpreterDeserializationListener : public ASTDeserializationListener {
private:
cling::InterpreterCallbacks* m_Callbacks;
public:
InterpreterDeserializationListener(InterpreterCallbacks* C)
: m_Callbacks(C) {}
virtual void DeclRead(serialization::DeclID, const Decl *D) {
if (m_Callbacks)
m_Callbacks->DeclDeserialized(D);
}
virtual void TypeRead(serialization::TypeIdx, QualType T) {
if (m_Callbacks)
m_Callbacks->TypeDeserialized(T.getTypePtr());
}
};
///\brief Translates 'interesting' for the interpreter ExternalSemaSource
/// events into interpreter callbacks.
///
class InterpreterExternalSemaSource : public clang::ExternalSemaSource {
protected:
///\brief The interpreter callback which are subscribed for the events.
///
/// Usually the callbacks is the owner of the class and the interpreter owns
/// the callbacks so they can't be out of sync. Eg we notifying the wrong
/// callback class.
///
InterpreterCallbacks* m_Callbacks; // we don't own it.
public:
InterpreterExternalSemaSource(InterpreterCallbacks* C) : m_Callbacks(C){}
~InterpreterExternalSemaSource() {}
InterpreterCallbacks* getCallbacks() const { return m_Callbacks; }
/// \brief Provides last resort lookup for failed unqualified lookups.
///
/// This gets translated into InterpreterCallback's call.
///
///\param[out] R The recovered symbol.
///\param[in] S The scope in which the lookup failed.
///
///\returns true if a suitable declaration is found.
///
virtual bool LookupUnqualified(clang::LookupResult& R, clang::Scope* S) {
if (m_Callbacks)
return m_Callbacks->LookupObject(R, S);
return false;
}
virtual bool FindExternalVisibleDeclsByName(const clang::DeclContext* DC,
clang::DeclarationName Name) {
if (m_Callbacks)
return m_Callbacks->LookupObject(DC, Name);
return false;
}
// Silence warning virtual function was hidden.
using ExternalASTSource::CompleteType(clang::ObjCInterfaceDecl*);
virtual void CompleteType(TagDecl* Tag) {
if (m_Callbacks)
m_Callbacks->LookupObject(Tag);
}
void UpdateWithNewDeclsFwd(const DeclContext *DC, DeclarationName Name,
llvm::ArrayRef<NamedDecl*> Decls) {
SetExternalVisibleDeclsForName(DC, Name, Decls);
}
};
InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,
InterpreterExternalSemaSource* IESS,
InterpreterDeserializationListener* IDL,
InterpreterPPCallbacks* IPPC)
: m_Interpreter(interp), m_ExternalSemaSource(IESS),
m_DeserializationListener(IDL), m_IsRuntime(false) {
if (IESS)
m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());
ASTReader* Reader = m_Interpreter->getCI()->getModuleManager();
if (IDL && Reader)
Reader->setDeserializationListener(IDL);
if (IPPC)
m_Interpreter->getCI()->getPreprocessor().addPPCallbacks(IPPC);
}
InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,
bool enableExternalSemaSourceCallbacks/* = false*/,
bool enableDeserializationListenerCallbacks/* = false*/,
bool enablePPCallbacks/* = false*/)
: m_Interpreter(interp), m_IsRuntime(false) {
if (enableExternalSemaSourceCallbacks) {
m_ExternalSemaSource.reset(new InterpreterExternalSemaSource(this));
m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());
}
ASTReader* Reader = m_Interpreter->getCI()->getModuleManager();
if (enableDeserializationListenerCallbacks && Reader) {
// FIXME: need to create a multiplexer if a DeserializationListener is
// alreday present.
m_DeserializationListener.
reset(new InterpreterDeserializationListener(this));
Reader->setDeserializationListener(m_DeserializationListener.get());
}
if (enablePPCallbacks) {
m_PPCallbacks.reset(new InterpreterPPCallbacks(this));
Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
PP.addPPCallbacks(m_PPCallbacks.get());
}
}
// pin the vtable here
InterpreterCallbacks::~InterpreterCallbacks() {
// FIXME: we have to remove the external source at destruction time. Needs
// further tweaks of the patch in clang. This will be done later once the
// patch is in clang's mainline.
}
ExternalSemaSource*
InterpreterCallbacks::getInterpreterExternalSemaSource() const {
return m_ExternalSemaSource.get();
}
ASTDeserializationListener*
InterpreterCallbacks::getInterpreterDeserializationListener() const {
return m_DeserializationListener.get();
}
bool InterpreterCallbacks::FileNotFound(llvm::StringRef FileName,
llvm::SmallVectorImpl<char>& RecoveryPath) {
// Default implementation is no op.
return false;
}
bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) {
// Default implementation is no op.
return false;
}
bool InterpreterCallbacks::LookupObject(const DeclContext*, DeclarationName) {
// Default implementation is no op.
return false;
}
bool InterpreterCallbacks::LookupObject(TagDecl*) {
// Default implementation is no op.
return false;
}
void InterpreterCallbacks::UpdateWithNewDecls(const DeclContext *DC,
DeclarationName Name,
llvm::ArrayRef<NamedDecl*> Decls) {
if (m_ExternalSemaSource)
m_ExternalSemaSource->UpdateWithNewDeclsFwd(DC, Name, Decls);
}
} // end namespace cling
// TODO: Make the build system in the testsuite aware how to build that class
// and extract it out there again.
#include "DynamicLookup.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
namespace cling {
namespace test {
TestProxy* Tester = 0;
extern "C" int printf(const char* fmt, ...);
TestProxy::TestProxy(){}
int TestProxy::Draw(){ return 12; }
const char* TestProxy::getVersion(){ return "Interpreter.cpp"; }
int TestProxy::Add10(int num) { return num + 10;}
int TestProxy::Add(int a, int b) {
return a + b;
}
void TestProxy::PrintString(std::string s) { printf("%s\n", s.c_str()); }
bool TestProxy::PrintArray(int a[], size_t size) {
for (unsigned i = 0; i < size; ++i)
printf("%i", a[i]);
printf("%s", "\n");
return true;
}
void TestProxy::PrintArray(float a[][5], size_t size) {
for (unsigned i = 0; i < size; ++i)
for (unsigned j = 0; j < 5; ++j)
printf("%i", (int)a[i][j]);
printf("%s", "\n");
}
void TestProxy::PrintArray(int a[][4][5], size_t size) {
for (unsigned i = 0; i < size; ++i)
for (unsigned j = 0; j < 4; ++j)
for (unsigned k = 0; k < 5; ++k)
printf("%i", a[i][j][k]);
printf("%s", "\n");
}
SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp)
: InterpreterCallbacks(interp, /*enableExternalSemaSourceCallbacks*/true),
m_TesterDecl(0) {
m_Interpreter->process("cling::test::Tester = new cling::test::TestProxy();");
}
SymbolResolverCallback::~SymbolResolverCallback() { }
bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) {
if (m_IsRuntime) {
// Only for demo resolve all unknown objects to cling::test::Tester
if (!m_TesterDecl) {
clang::Sema& SemaR = m_Interpreter->getSema();
clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaR, "cling");
NSD = utils::Lookup::Namespace(&SemaR, "test", NSD);
m_TesterDecl = utils::Lookup::Named(&SemaR, "Tester", NSD);
}
assert (m_TesterDecl && "Tester not found!");
R.addDecl(m_TesterDecl);
return true; // Tell clang to continue.
}
if (ShouldResolveAtRuntime(R, S)) {
ASTContext& C = R.getSema().getASTContext();
DeclContext* DC = 0;
// For DeclContext-less scopes like if (dyn_expr) {}
while (!DC) {
DC = static_cast<DeclContext*>(S->getEntity());
S = S->getParent();
}
DeclarationName Name = R.getLookupName();
IdentifierInfo* II = Name.getAsIdentifierInfo();
SourceLocation Loc = R.getNameLoc();
VarDecl* Res = VarDecl::Create(C, DC, Loc, Loc, II, C.DependentTy,
/*TypeSourceInfo*/0, SC_None);
// Annotate the decl to give a hint in cling. FIXME: Current implementation
// is a gross hack, because TClingCallbacks shouldn't know about
// EvaluateTSynthesizer at all!
SourceRange invalidRange;
Res->addAttr(new (C) AnnotateAttr(invalidRange, C, "__ResolveAtRuntime"));
R.addDecl(Res);
DC->addDecl(Res);
// Say that we can handle the situation. Clang should try to recover
return true;
}
return false;
}
bool SymbolResolverCallback::ShouldResolveAtRuntime(LookupResult& R,
Scope* S) {
if (R.getLookupKind() != Sema::LookupOrdinaryName)
return false;
if (R.isForRedeclaration())
return false;
if (!R.empty())
return false;
// FIXME: Figure out better way to handle:
// C++ [basic.lookup.classref]p1:
// In a class member access expression (5.2.5), if the . or -> token is
// immediately followed by an identifier followed by a <, the
// identifier must be looked up to determine whether the < is the
// beginning of a template argument list (14.2) or a less-than operator.
// The identifier is first looked up in the class of the object
// expression. If the identifier is not found, it is then looked up in
// the context of the entire postfix-expression and shall name a class
// or function template.
//
// We want to ignore object(.|->)member<template>
if (R.getSema().PP.LookAhead(0).getKind() == tok::less)
// TODO: check for . or -> in the cached token stream
return false;
for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {
if (!Ctx->isDependentContext())
// For now we support only the prompt.
if (isa<FunctionDecl>(Ctx))
return true;
}
}
return false;
}
} // end test
} // end cling
<commit_msg>Spell it syntactically correct.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/ASTDeserializationListener.h"
using namespace clang;
namespace cling {
///\brief Translates 'interesting' for the interpreter
/// ASTDeserializationListener events into interpreter callback.
///
class InterpreterPPCallbacks : public PPCallbacks {
private:
cling::InterpreterCallbacks* m_Callbacks;
public:
InterpreterPPCallbacks(InterpreterCallbacks* C) : m_Callbacks(C) { }
~InterpreterPPCallbacks() { }
virtual bool FileNotFound(llvm::StringRef FileName,
llvm::SmallVectorImpl<char>& RecoveryPath) {
if (m_Callbacks)
return m_Callbacks->FileNotFound(FileName, RecoveryPath);
// Returning true would mean that the preprocessor should try to recover.
return false;
}
};
///\brief Translates 'interesting' for the interpreter
/// ASTDeserializationListener events into interpreter callback.
///
class InterpreterDeserializationListener : public ASTDeserializationListener {
private:
cling::InterpreterCallbacks* m_Callbacks;
public:
InterpreterDeserializationListener(InterpreterCallbacks* C)
: m_Callbacks(C) {}
virtual void DeclRead(serialization::DeclID, const Decl *D) {
if (m_Callbacks)
m_Callbacks->DeclDeserialized(D);
}
virtual void TypeRead(serialization::TypeIdx, QualType T) {
if (m_Callbacks)
m_Callbacks->TypeDeserialized(T.getTypePtr());
}
};
///\brief Translates 'interesting' for the interpreter ExternalSemaSource
/// events into interpreter callbacks.
///
class InterpreterExternalSemaSource : public clang::ExternalSemaSource {
protected:
///\brief The interpreter callback which are subscribed for the events.
///
/// Usually the callbacks is the owner of the class and the interpreter owns
/// the callbacks so they can't be out of sync. Eg we notifying the wrong
/// callback class.
///
InterpreterCallbacks* m_Callbacks; // we don't own it.
public:
InterpreterExternalSemaSource(InterpreterCallbacks* C) : m_Callbacks(C){}
~InterpreterExternalSemaSource() {}
InterpreterCallbacks* getCallbacks() const { return m_Callbacks; }
/// \brief Provides last resort lookup for failed unqualified lookups.
///
/// This gets translated into InterpreterCallback's call.
///
///\param[out] R The recovered symbol.
///\param[in] S The scope in which the lookup failed.
///
///\returns true if a suitable declaration is found.
///
virtual bool LookupUnqualified(clang::LookupResult& R, clang::Scope* S) {
if (m_Callbacks)
return m_Callbacks->LookupObject(R, S);
return false;
}
virtual bool FindExternalVisibleDeclsByName(const clang::DeclContext* DC,
clang::DeclarationName Name) {
if (m_Callbacks)
return m_Callbacks->LookupObject(DC, Name);
return false;
}
// Silence warning virtual function was hidden.
using ExternalASTSource::CompleteType;
virtual void CompleteType(TagDecl* Tag) {
if (m_Callbacks)
m_Callbacks->LookupObject(Tag);
}
void UpdateWithNewDeclsFwd(const DeclContext *DC, DeclarationName Name,
llvm::ArrayRef<NamedDecl*> Decls) {
SetExternalVisibleDeclsForName(DC, Name, Decls);
}
};
InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,
InterpreterExternalSemaSource* IESS,
InterpreterDeserializationListener* IDL,
InterpreterPPCallbacks* IPPC)
: m_Interpreter(interp), m_ExternalSemaSource(IESS),
m_DeserializationListener(IDL), m_IsRuntime(false) {
if (IESS)
m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());
ASTReader* Reader = m_Interpreter->getCI()->getModuleManager();
if (IDL && Reader)
Reader->setDeserializationListener(IDL);
if (IPPC)
m_Interpreter->getCI()->getPreprocessor().addPPCallbacks(IPPC);
}
InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,
bool enableExternalSemaSourceCallbacks/* = false*/,
bool enableDeserializationListenerCallbacks/* = false*/,
bool enablePPCallbacks/* = false*/)
: m_Interpreter(interp), m_IsRuntime(false) {
if (enableExternalSemaSourceCallbacks) {
m_ExternalSemaSource.reset(new InterpreterExternalSemaSource(this));
m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());
}
ASTReader* Reader = m_Interpreter->getCI()->getModuleManager();
if (enableDeserializationListenerCallbacks && Reader) {
// FIXME: need to create a multiplexer if a DeserializationListener is
// alreday present.
m_DeserializationListener.
reset(new InterpreterDeserializationListener(this));
Reader->setDeserializationListener(m_DeserializationListener.get());
}
if (enablePPCallbacks) {
m_PPCallbacks.reset(new InterpreterPPCallbacks(this));
Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
PP.addPPCallbacks(m_PPCallbacks.get());
}
}
// pin the vtable here
InterpreterCallbacks::~InterpreterCallbacks() {
// FIXME: we have to remove the external source at destruction time. Needs
// further tweaks of the patch in clang. This will be done later once the
// patch is in clang's mainline.
}
ExternalSemaSource*
InterpreterCallbacks::getInterpreterExternalSemaSource() const {
return m_ExternalSemaSource.get();
}
ASTDeserializationListener*
InterpreterCallbacks::getInterpreterDeserializationListener() const {
return m_DeserializationListener.get();
}
bool InterpreterCallbacks::FileNotFound(llvm::StringRef FileName,
llvm::SmallVectorImpl<char>& RecoveryPath) {
// Default implementation is no op.
return false;
}
bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) {
// Default implementation is no op.
return false;
}
bool InterpreterCallbacks::LookupObject(const DeclContext*, DeclarationName) {
// Default implementation is no op.
return false;
}
bool InterpreterCallbacks::LookupObject(TagDecl*) {
// Default implementation is no op.
return false;
}
void InterpreterCallbacks::UpdateWithNewDecls(const DeclContext *DC,
DeclarationName Name,
llvm::ArrayRef<NamedDecl*> Decls) {
if (m_ExternalSemaSource)
m_ExternalSemaSource->UpdateWithNewDeclsFwd(DC, Name, Decls);
}
} // end namespace cling
// TODO: Make the build system in the testsuite aware how to build that class
// and extract it out there again.
#include "DynamicLookup.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
namespace cling {
namespace test {
TestProxy* Tester = 0;
extern "C" int printf(const char* fmt, ...);
TestProxy::TestProxy(){}
int TestProxy::Draw(){ return 12; }
const char* TestProxy::getVersion(){ return "Interpreter.cpp"; }
int TestProxy::Add10(int num) { return num + 10;}
int TestProxy::Add(int a, int b) {
return a + b;
}
void TestProxy::PrintString(std::string s) { printf("%s\n", s.c_str()); }
bool TestProxy::PrintArray(int a[], size_t size) {
for (unsigned i = 0; i < size; ++i)
printf("%i", a[i]);
printf("%s", "\n");
return true;
}
void TestProxy::PrintArray(float a[][5], size_t size) {
for (unsigned i = 0; i < size; ++i)
for (unsigned j = 0; j < 5; ++j)
printf("%i", (int)a[i][j]);
printf("%s", "\n");
}
void TestProxy::PrintArray(int a[][4][5], size_t size) {
for (unsigned i = 0; i < size; ++i)
for (unsigned j = 0; j < 4; ++j)
for (unsigned k = 0; k < 5; ++k)
printf("%i", a[i][j][k]);
printf("%s", "\n");
}
SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp)
: InterpreterCallbacks(interp, /*enableExternalSemaSourceCallbacks*/true),
m_TesterDecl(0) {
m_Interpreter->process("cling::test::Tester = new cling::test::TestProxy();");
}
SymbolResolverCallback::~SymbolResolverCallback() { }
bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) {
if (m_IsRuntime) {
// Only for demo resolve all unknown objects to cling::test::Tester
if (!m_TesterDecl) {
clang::Sema& SemaR = m_Interpreter->getSema();
clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaR, "cling");
NSD = utils::Lookup::Namespace(&SemaR, "test", NSD);
m_TesterDecl = utils::Lookup::Named(&SemaR, "Tester", NSD);
}
assert (m_TesterDecl && "Tester not found!");
R.addDecl(m_TesterDecl);
return true; // Tell clang to continue.
}
if (ShouldResolveAtRuntime(R, S)) {
ASTContext& C = R.getSema().getASTContext();
DeclContext* DC = 0;
// For DeclContext-less scopes like if (dyn_expr) {}
while (!DC) {
DC = static_cast<DeclContext*>(S->getEntity());
S = S->getParent();
}
DeclarationName Name = R.getLookupName();
IdentifierInfo* II = Name.getAsIdentifierInfo();
SourceLocation Loc = R.getNameLoc();
VarDecl* Res = VarDecl::Create(C, DC, Loc, Loc, II, C.DependentTy,
/*TypeSourceInfo*/0, SC_None);
// Annotate the decl to give a hint in cling. FIXME: Current implementation
// is a gross hack, because TClingCallbacks shouldn't know about
// EvaluateTSynthesizer at all!
SourceRange invalidRange;
Res->addAttr(new (C) AnnotateAttr(invalidRange, C, "__ResolveAtRuntime"));
R.addDecl(Res);
DC->addDecl(Res);
// Say that we can handle the situation. Clang should try to recover
return true;
}
return false;
}
bool SymbolResolverCallback::ShouldResolveAtRuntime(LookupResult& R,
Scope* S) {
if (R.getLookupKind() != Sema::LookupOrdinaryName)
return false;
if (R.isForRedeclaration())
return false;
if (!R.empty())
return false;
// FIXME: Figure out better way to handle:
// C++ [basic.lookup.classref]p1:
// In a class member access expression (5.2.5), if the . or -> token is
// immediately followed by an identifier followed by a <, the
// identifier must be looked up to determine whether the < is the
// beginning of a template argument list (14.2) or a less-than operator.
// The identifier is first looked up in the class of the object
// expression. If the identifier is not found, it is then looked up in
// the context of the entire postfix-expression and shall name a class
// or function template.
//
// We want to ignore object(.|->)member<template>
if (R.getSema().PP.LookAhead(0).getKind() == tok::less)
// TODO: check for . or -> in the cached token stream
return false;
for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {
if (!Ctx->isDependentContext())
// For now we support only the prompt.
if (isa<FunctionDecl>(Ctx))
return true;
}
}
return false;
}
} // end test
} // end cling
<|endoftext|> |
<commit_before>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Codegen/LLVMGPU/KernelConfig.h"
#include "iree/compiler/Codegen/LLVMGPU/LLVMGPUUtils.h"
#include "iree/compiler/Codegen/PassDetail.h"
#include "iree/compiler/Codegen/Passes.h"
#include "iree/compiler/Codegen/Transforms/Transforms.h"
#include "iree/compiler/Codegen/Utils/MarkerUtils.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/HAL/IR/LoweringConfig.h"
#include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h"
#include "iree/compiler/Dialect/LinalgExt/Transforms/Transforms.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
#include "mlir/Dialect/GPU/Passes.h"
#include "mlir/Dialect/LLVMIR/NVVMDialect.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Support/MathExtras.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
#define DEBUG_TYPE "iree-llvmgpu-tile-and-distribute"
namespace mlir {
namespace iree_compiler {
/// Patterns for workgroup level tiling. Workgroup tiling is done at the flow
/// level but we may have extra tiling for the reduction dimension. Therefore we
/// tile again without distributing.
static void populateTilingReductionPatterns(
MLIRContext *context, OwningRewritePatternList &patterns) {
auto tileSizesFn = [&](OpBuilder &builder,
Operation *op) -> SmallVector<Value, 4> {
SmallVector<unsigned> partitionedLoops = getPartitionedLoops(op);
SmallVector<int64_t, 4> tileSizes = getTileSizes(op, 0);
Location loc = op->getLoc();
auto tileSizesVal =
llvm::to_vector<4>(llvm::map_range(tileSizes, [&](int64_t v) -> Value {
return builder.create<ConstantIndexOp>(loc, v);
}));
auto zero = builder.create<ConstantIndexOp>(loc, 0);
for (unsigned depth : partitionedLoops) {
if (depth < tileSizesVal.size()) {
tileSizesVal[depth] = zero;
}
}
return tileSizesVal;
};
auto tilingOptions = linalg::LinalgTilingOptions()
.setLoopType(linalg::LinalgTilingLoopType::Loops)
.setTileSizeComputationFunction(tileSizesFn);
patterns.insert<linalg::LinalgTilingPattern<linalg::MatmulOp>,
linalg::LinalgTilingPattern<linalg::BatchMatmulOp>,
linalg::LinalgTilingPattern<linalg::GenericOp>>(
context, tilingOptions,
linalg::LinalgTransformationFilter(
{Identifier::get(getWorkgroupMarker(), context)},
Identifier::get(getWorkgroupKTiledMarker(), context)));
}
/// Patterns for thread level tiling.
static void populateTilingToInvocationPatterns(
MLIRContext *context, OwningRewritePatternList &patterns,
ArrayRef<int64_t> workgroupSize) {
linalg::TileSizeComputationFunction getInnerTileSizeFn =
[](OpBuilder &builder, Operation *operation) {
SmallVector<Value, 4> tileSizesVal;
SmallVector<int64_t, 4> tileSizes = getTileSizes(operation, 2);
if (tileSizes.empty()) return SmallVector<Value, 4>();
SmallVector<unsigned> partitionedLoops = getPartitionedLoops(operation);
llvm::DenseSet<unsigned> partitionedLoopsSet(partitionedLoops.begin(),
partitionedLoops.end());
tileSizesVal.reserve(tileSizes.size());
for (auto val : llvm::enumerate(tileSizes)) {
int64_t useTileSize =
partitionedLoopsSet.count(val.index()) ? val.value() : 0;
tileSizesVal.push_back(builder.create<ConstantIndexOp>(
operation->getLoc(), useTileSize));
}
return tileSizesVal;
};
auto getThreadProcInfoFn = [workgroupSize](
OpBuilder &builder, Location loc,
ArrayRef<Range> parallelLoopRanges) {
return getGPUThreadIdsAndCounts(builder, loc, parallelLoopRanges.size(),
workgroupSize);
};
linalg::LinalgLoopDistributionOptions invocationDistributionOptions;
invocationDistributionOptions.procInfo = getThreadProcInfoFn;
invocationDistributionOptions.distributionMethod = {
{linalg::DistributionMethod::Cyclic, linalg::DistributionMethod::Cyclic,
linalg::DistributionMethod::Cyclic}};
auto tilingOptions =
linalg::LinalgTilingOptions()
.setLoopType(linalg::LinalgTilingLoopType::Loops)
.setTileSizeComputationFunction(getInnerTileSizeFn)
.setDistributionOptions(invocationDistributionOptions);
patterns
.insert<linalg::LinalgTilingPattern<linalg::MatmulOp>,
linalg::LinalgTilingPattern<linalg::FillOp>,
linalg::LinalgTilingPattern<linalg::CopyOp>,
linalg::LinalgTilingPattern<linalg::BatchMatmulOp>,
linalg::LinalgTilingPattern<linalg::GenericOp>,
linalg::LinalgTilingPattern<linalg::Conv2DNhwcHwcfOp>,
linalg::LinalgTilingPattern<linalg::DepthwiseConv2DNhwcOp>,
linalg::LinalgTilingPattern<linalg::Conv2DNhwcHwcfOp>,
linalg::LinalgTilingPattern<linalg::DepthwiseConv2DNhwcOp>,
linalg::LinalgTilingPattern<linalg::DepthwiseConv2DNhwcOp>,
linalg_ext::TiledOpInterfaceTilingPattern<linalg_ext::ScatterOp>>(
context, tilingOptions,
linalg::LinalgTransformationFilter(
{Identifier::get(getWorkgroupMarker(), context),
Identifier::get(getWorkgroupKTiledMarker(), context),
Identifier::get(getWorkgroupMemoryMarker(), context)},
Identifier::get(getVectorizeMarker(), context)));
}
static LogicalResult copyToWorkgroupMemory(OpBuilder &b, Value src, Value dst) {
auto copyOp = b.create<linalg::CopyOp>(src.getLoc(), src, dst);
setMarker(copyOp, getCopyToWorkgroupMemoryMarker());
return success();
}
static Optional<Value> allocateWorkgroupMemory(
OpBuilder &b, memref::SubViewOp subview,
ArrayRef<Value> boundingSubViewSize, DataLayout &layout) {
// In CUDA workgroup memory is represented by a global variable. Create a
// global variable and a memref.GetGlobalOp at the beginning of the funtion to
// get the memref.
OpBuilder::InsertionGuard guard(b);
FuncOp funcOp = subview->getParentOfType<FuncOp>();
if (!funcOp) {
subview.emitError("expected op to be within std.func");
return llvm::None;
}
ModuleOp moduleOp = funcOp->getParentOfType<ModuleOp>();
SymbolTable symbolTable(moduleOp);
// The bounding subview size is expected to be constant. This specified the
// shape of the allocation.
SmallVector<int64_t, 2> shape = llvm::to_vector<2>(
llvm::map_range(boundingSubViewSize, [](Value v) -> int64_t {
APInt value;
if (matchPattern(v, m_ConstantInt(&value))) return value.getSExtValue();
return -1;
}));
if (llvm::any_of(shape, [](int64_t v) { return v == -1; })) return {};
Type allocType =
MemRefType::get(shape, subview.getType().getElementType(), {},
gpu::GPUDialect::getWorkgroupAddressSpace());
b.setInsertionPoint(&moduleOp.front());
auto global =
b.create<memref::GlobalOp>(funcOp.getLoc(), "__shared_memory__",
/*sym_visibility=*/b.getStringAttr("private"),
/*type=*/allocType,
/*initial_value=*/ElementsAttr(),
/*constant=*/false);
symbolTable.insert(global);
b.setInsertionPointToStart(&(*funcOp.getBody().begin()));
Value buffer = b.create<memref::GetGlobalOp>(funcOp.getLoc(), global.type(),
global.getName());
return buffer;
}
static LogicalResult deallocateWorkgroupMemory(OpBuilder &b, Value buffer) {
// Nothing to do.
return success();
}
static void populatePromotionPatterns(MLIRContext *context,
OwningRewritePatternList &patterns) {
patterns.insert<linalg::LinalgPromotionPattern<linalg::MatmulOp>,
linalg::LinalgPromotionPattern<linalg::BatchMatmulOp>>(
context,
linalg::LinalgPromotionOptions()
.setAllocationDeallocationFns(allocateWorkgroupMemory,
deallocateWorkgroupMemory)
.setCopyInOutFns(copyToWorkgroupMemory, copyToWorkgroupMemory)
.setOperandsToPromote({0, 1})
.setUseFullTileBuffers({false, false}),
linalg::LinalgTransformationFilter(
{Identifier::get(getWorkgroupKTiledMarker(), context)},
Identifier::get(getWorkgroupMemoryMarker(), context)));
}
namespace {
struct LLVMGPUTileAndDistributePass
: public LLVMGPUTileAndDistributeBase<LLVMGPUTileAndDistributePass> {
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<AffineDialect, gpu::GPUDialect>();
}
void runOnOperation() override {
MLIRContext *context = &getContext();
auto funcOp = getOperation();
if (!isEntryPoint(funcOp)) return;
{
// Tile again at the workgroup level since redution dimension were
// ignored. Dimensions already tiled will be ignore since we tile to the
// same size.
OwningRewritePatternList wgTilingPatterns(context);
populateTilingReductionPatterns(context, wgTilingPatterns);
(void)applyPatternsAndFoldGreedily(funcOp, std::move(wgTilingPatterns));
}
{
RewritePatternSet wgTilingCanonicalizationPatterns =
linalg::getLinalgTilingCanonicalizationPatterns(context);
populateAffineMinSCFCanonicalizationPattern(
wgTilingCanonicalizationPatterns);
(void)applyPatternsAndFoldGreedily(
funcOp, std::move(wgTilingCanonicalizationPatterns));
}
LLVM_DEBUG({
llvm::dbgs() << "After tile reductions:";
funcOp.dump();
});
auto workgroupSize = llvm::to_vector<4>(llvm::map_range(
getEntryPoint(funcOp).workgroup_size().getValue(),
[&](Attribute attr) { return attr.cast<IntegerAttr>().getInt(); }));
int64_t flatWorkgroupSize =
workgroupSize[0] * workgroupSize[1] * workgroupSize[2];
// Only promote to workgroup size if there are multiple warps.
if (flatWorkgroupSize > 32) {
OwningRewritePatternList promotionPatterns(&getContext());
populatePromotionPatterns(context, promotionPatterns);
(void)applyPatternsAndFoldGreedily(funcOp, std::move(promotionPatterns));
// Insert barriers before and after copies to workgroup memory and skip
// insert barriers between back to back copy to workgroup memory.
OpBuilder builder(&getContext());
funcOp.walk([&builder](linalg::CopyOp copyOp) {
if (hasMarker(copyOp, getCopyToWorkgroupMemoryMarker())) {
Operation *prevOp = copyOp->getPrevNode();
if (!prevOp || !hasMarker(prevOp, getCopyToWorkgroupMemoryMarker())) {
builder.setInsertionPoint(copyOp);
builder.create<gpu::BarrierOp>(copyOp.getLoc());
}
Operation *nextOp = copyOp->getNextNode();
if (!nextOp || !hasMarker(nextOp, getCopyToWorkgroupMemoryMarker())) {
builder.setInsertionPointAfter(copyOp);
builder.create<gpu::BarrierOp>(copyOp.getLoc());
}
}
});
}
{
RewritePatternSet promotionCanonicalization =
linalg::getLinalgTilingCanonicalizationPatterns(context);
(void)applyPatternsAndFoldGreedily(funcOp,
std::move(promotionCanonicalization));
}
LLVM_DEBUG({
llvm::dbgs() << "After promotion:";
funcOp.dump();
});
{
// Apply last level of tiling and distribute to threads.
OwningRewritePatternList threadLevelTilingPatterns(context);
populateTilingToInvocationPatterns(context, threadLevelTilingPatterns,
workgroupSize);
(void)applyPatternsAndFoldGreedily(funcOp,
std::move(threadLevelTilingPatterns));
}
{
// Apply canonicalization patterns.
RewritePatternSet threadTilingCanonicalizationPatterns =
linalg::getLinalgTilingCanonicalizationPatterns(context);
populateAffineMinSCFCanonicalizationPattern(
threadTilingCanonicalizationPatterns);
(void)applyPatternsAndFoldGreedily(
funcOp, std::move(threadTilingCanonicalizationPatterns));
}
LLVM_DEBUG({
llvm::dbgs() << "After tile and distribute to threads:";
funcOp.dump();
});
}
};
} // namespace
std::unique_ptr<OperationPass<FuncOp>>
createLLVMGPUTileAndDistributeToThreads() {
return std::make_unique<LLVMGPUTileAndDistributePass>();
}
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Fixes for 4beb756a748e710203bd309d57dc449ee9c8e3f0<commit_after>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Codegen/LLVMGPU/KernelConfig.h"
#include "iree/compiler/Codegen/LLVMGPU/LLVMGPUUtils.h"
#include "iree/compiler/Codegen/PassDetail.h"
#include "iree/compiler/Codegen/Passes.h"
#include "iree/compiler/Codegen/Transforms/Transforms.h"
#include "iree/compiler/Codegen/Utils/MarkerUtils.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/HAL/IR/LoweringConfig.h"
#include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h"
#include "iree/compiler/Dialect/LinalgExt/Transforms/Transforms.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
#include "mlir/Dialect/GPU/Passes.h"
#include "mlir/Dialect/LLVMIR/NVVMDialect.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Support/MathExtras.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
#define DEBUG_TYPE "iree-llvmgpu-tile-and-distribute"
namespace mlir {
namespace iree_compiler {
/// Patterns for workgroup level tiling. Workgroup tiling is done at the flow
/// level but we may have extra tiling for the reduction dimension. Therefore we
/// tile again without distributing.
static void populateTilingReductionPatterns(
MLIRContext *context, OwningRewritePatternList &patterns) {
auto tileSizesFn = [&](OpBuilder &builder,
Operation *op) -> SmallVector<Value, 4> {
SmallVector<unsigned> partitionedLoops = getPartitionedLoops(op);
SmallVector<int64_t, 4> tileSizes = getTileSizes(op, 0);
Location loc = op->getLoc();
auto tileSizesVal =
llvm::to_vector<4>(llvm::map_range(tileSizes, [&](int64_t v) -> Value {
return builder.create<ConstantIndexOp>(loc, v);
}));
auto zero = builder.create<ConstantIndexOp>(loc, 0);
for (unsigned depth : partitionedLoops) {
if (depth < tileSizesVal.size()) {
tileSizesVal[depth] = zero;
}
}
return tileSizesVal;
};
auto tilingOptions = linalg::LinalgTilingOptions()
.setLoopType(linalg::LinalgTilingLoopType::Loops)
.setTileSizeComputationFunction(tileSizesFn);
patterns.insert<linalg::LinalgTilingPattern<linalg::MatmulOp>,
linalg::LinalgTilingPattern<linalg::BatchMatmulOp>,
linalg::LinalgTilingPattern<linalg::GenericOp>>(
context, tilingOptions,
linalg::LinalgTransformationFilter(
{Identifier::get(getWorkgroupMarker(), context)},
Identifier::get(getWorkgroupKTiledMarker(), context)));
}
/// Patterns for thread level tiling.
static void populateTilingToInvocationPatterns(
MLIRContext *context, OwningRewritePatternList &patterns,
ArrayRef<int64_t> workgroupSize) {
linalg::TileSizeComputationFunction getInnerTileSizeFn =
[](OpBuilder &builder, Operation *operation) {
SmallVector<Value, 4> tileSizesVal;
SmallVector<int64_t, 4> tileSizes = getTileSizes(operation, 2);
if (tileSizes.empty()) return SmallVector<Value, 4>();
SmallVector<unsigned> partitionedLoops = getPartitionedLoops(operation);
llvm::DenseSet<unsigned> partitionedLoopsSet(partitionedLoops.begin(),
partitionedLoops.end());
tileSizesVal.reserve(tileSizes.size());
for (auto val : llvm::enumerate(tileSizes)) {
int64_t useTileSize =
partitionedLoopsSet.count(val.index()) ? val.value() : 0;
tileSizesVal.push_back(builder.create<ConstantIndexOp>(
operation->getLoc(), useTileSize));
}
return tileSizesVal;
};
auto getThreadProcInfoFn = [workgroupSize](
OpBuilder &builder, Location loc,
ArrayRef<Range> parallelLoopRanges) {
return getGPUThreadIdsAndCounts(builder, loc, parallelLoopRanges.size(),
workgroupSize);
};
linalg::LinalgLoopDistributionOptions invocationDistributionOptions;
invocationDistributionOptions.procInfo = getThreadProcInfoFn;
invocationDistributionOptions.distributionMethod = {
{linalg::DistributionMethod::Cyclic, linalg::DistributionMethod::Cyclic,
linalg::DistributionMethod::Cyclic}};
auto tilingOptions =
linalg::LinalgTilingOptions()
.setLoopType(linalg::LinalgTilingLoopType::Loops)
.setTileSizeComputationFunction(getInnerTileSizeFn)
.setDistributionOptions(invocationDistributionOptions);
patterns
.insert<linalg::LinalgTilingPattern<linalg::MatmulOp>,
linalg::LinalgTilingPattern<linalg::FillOp>,
linalg::LinalgTilingPattern<linalg::CopyOp>,
linalg::LinalgTilingPattern<linalg::BatchMatmulOp>,
linalg::LinalgTilingPattern<linalg::GenericOp>,
linalg::LinalgTilingPattern<linalg::Conv2DNhwcHwcfOp>,
linalg::LinalgTilingPattern<linalg::DepthwiseConv2DNhwOp>,
linalg::LinalgTilingPattern<linalg::DepthwiseConv2DNhwcOp>,
linalg_ext::TiledOpInterfaceTilingPattern<linalg_ext::ScatterOp>>(
context, tilingOptions,
linalg::LinalgTransformationFilter(
{Identifier::get(getWorkgroupMarker(), context),
Identifier::get(getWorkgroupKTiledMarker(), context),
Identifier::get(getWorkgroupMemoryMarker(), context)},
Identifier::get(getVectorizeMarker(), context)));
}
static LogicalResult copyToWorkgroupMemory(OpBuilder &b, Value src, Value dst) {
auto copyOp = b.create<linalg::CopyOp>(src.getLoc(), src, dst);
setMarker(copyOp, getCopyToWorkgroupMemoryMarker());
return success();
}
static Optional<Value> allocateWorkgroupMemory(
OpBuilder &b, memref::SubViewOp subview,
ArrayRef<Value> boundingSubViewSize, DataLayout &layout) {
// In CUDA workgroup memory is represented by a global variable. Create a
// global variable and a memref.GetGlobalOp at the beginning of the funtion to
// get the memref.
OpBuilder::InsertionGuard guard(b);
FuncOp funcOp = subview->getParentOfType<FuncOp>();
if (!funcOp) {
subview.emitError("expected op to be within std.func");
return llvm::None;
}
ModuleOp moduleOp = funcOp->getParentOfType<ModuleOp>();
SymbolTable symbolTable(moduleOp);
// The bounding subview size is expected to be constant. This specified the
// shape of the allocation.
SmallVector<int64_t, 2> shape = llvm::to_vector<2>(
llvm::map_range(boundingSubViewSize, [](Value v) -> int64_t {
APInt value;
if (matchPattern(v, m_ConstantInt(&value))) return value.getSExtValue();
return -1;
}));
if (llvm::any_of(shape, [](int64_t v) { return v == -1; })) return {};
Type allocType =
MemRefType::get(shape, subview.getType().getElementType(), {},
gpu::GPUDialect::getWorkgroupAddressSpace());
b.setInsertionPoint(&moduleOp.front());
auto global =
b.create<memref::GlobalOp>(funcOp.getLoc(), "__shared_memory__",
/*sym_visibility=*/b.getStringAttr("private"),
/*type=*/allocType,
/*initial_value=*/ElementsAttr(),
/*constant=*/false);
symbolTable.insert(global);
b.setInsertionPointToStart(&(*funcOp.getBody().begin()));
Value buffer = b.create<memref::GetGlobalOp>(funcOp.getLoc(), global.type(),
global.getName());
return buffer;
}
static LogicalResult deallocateWorkgroupMemory(OpBuilder &b, Value buffer) {
// Nothing to do.
return success();
}
static void populatePromotionPatterns(MLIRContext *context,
OwningRewritePatternList &patterns) {
patterns.insert<linalg::LinalgPromotionPattern<linalg::MatmulOp>,
linalg::LinalgPromotionPattern<linalg::BatchMatmulOp>>(
context,
linalg::LinalgPromotionOptions()
.setAllocationDeallocationFns(allocateWorkgroupMemory,
deallocateWorkgroupMemory)
.setCopyInOutFns(copyToWorkgroupMemory, copyToWorkgroupMemory)
.setOperandsToPromote({0, 1})
.setUseFullTileBuffers({false, false}),
linalg::LinalgTransformationFilter(
{Identifier::get(getWorkgroupKTiledMarker(), context)},
Identifier::get(getWorkgroupMemoryMarker(), context)));
}
namespace {
struct LLVMGPUTileAndDistributePass
: public LLVMGPUTileAndDistributeBase<LLVMGPUTileAndDistributePass> {
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<AffineDialect, gpu::GPUDialect>();
}
void runOnOperation() override {
MLIRContext *context = &getContext();
auto funcOp = getOperation();
if (!isEntryPoint(funcOp)) return;
{
// Tile again at the workgroup level since redution dimension were
// ignored. Dimensions already tiled will be ignore since we tile to the
// same size.
OwningRewritePatternList wgTilingPatterns(context);
populateTilingReductionPatterns(context, wgTilingPatterns);
(void)applyPatternsAndFoldGreedily(funcOp, std::move(wgTilingPatterns));
}
{
RewritePatternSet wgTilingCanonicalizationPatterns =
linalg::getLinalgTilingCanonicalizationPatterns(context);
populateAffineMinSCFCanonicalizationPattern(
wgTilingCanonicalizationPatterns);
(void)applyPatternsAndFoldGreedily(
funcOp, std::move(wgTilingCanonicalizationPatterns));
}
LLVM_DEBUG({
llvm::dbgs() << "After tile reductions:";
funcOp.dump();
});
auto workgroupSize = llvm::to_vector<4>(llvm::map_range(
getEntryPoint(funcOp).workgroup_size().getValue(),
[&](Attribute attr) { return attr.cast<IntegerAttr>().getInt(); }));
int64_t flatWorkgroupSize =
workgroupSize[0] * workgroupSize[1] * workgroupSize[2];
// Only promote to workgroup size if there are multiple warps.
if (flatWorkgroupSize > 32) {
OwningRewritePatternList promotionPatterns(&getContext());
populatePromotionPatterns(context, promotionPatterns);
(void)applyPatternsAndFoldGreedily(funcOp, std::move(promotionPatterns));
// Insert barriers before and after copies to workgroup memory and skip
// insert barriers between back to back copy to workgroup memory.
OpBuilder builder(&getContext());
funcOp.walk([&builder](linalg::CopyOp copyOp) {
if (hasMarker(copyOp, getCopyToWorkgroupMemoryMarker())) {
Operation *prevOp = copyOp->getPrevNode();
if (!prevOp || !hasMarker(prevOp, getCopyToWorkgroupMemoryMarker())) {
builder.setInsertionPoint(copyOp);
builder.create<gpu::BarrierOp>(copyOp.getLoc());
}
Operation *nextOp = copyOp->getNextNode();
if (!nextOp || !hasMarker(nextOp, getCopyToWorkgroupMemoryMarker())) {
builder.setInsertionPointAfter(copyOp);
builder.create<gpu::BarrierOp>(copyOp.getLoc());
}
}
});
}
{
RewritePatternSet promotionCanonicalization =
linalg::getLinalgTilingCanonicalizationPatterns(context);
(void)applyPatternsAndFoldGreedily(funcOp,
std::move(promotionCanonicalization));
}
LLVM_DEBUG({
llvm::dbgs() << "After promotion:";
funcOp.dump();
});
{
// Apply last level of tiling and distribute to threads.
OwningRewritePatternList threadLevelTilingPatterns(context);
populateTilingToInvocationPatterns(context, threadLevelTilingPatterns,
workgroupSize);
(void)applyPatternsAndFoldGreedily(funcOp,
std::move(threadLevelTilingPatterns));
}
{
// Apply canonicalization patterns.
RewritePatternSet threadTilingCanonicalizationPatterns =
linalg::getLinalgTilingCanonicalizationPatterns(context);
populateAffineMinSCFCanonicalizationPattern(
threadTilingCanonicalizationPatterns);
(void)applyPatternsAndFoldGreedily(
funcOp, std::move(threadTilingCanonicalizationPatterns));
}
LLVM_DEBUG({
llvm::dbgs() << "After tile and distribute to threads:";
funcOp.dump();
});
}
};
} // namespace
std::unique_ptr<OperationPass<FuncOp>>
createLLVMGPUTileAndDistributeToThreads() {
return std::make_unique<LLVMGPUTileAndDistributePass>();
}
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#include "top.hpp"
#include "codegen.hpp"
#include "utils/libUtils.h"
#include "os/os.hpp"
#include "jit/src/jit.hpp"
#include "utils/target_mappings.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/DataLayout.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
using namespace amdcl;
using namespace llvm;
static std::string aclGetCodegenName(const aclTargetInfo &tgtInfo)
{
assert(tgtInfo.arch_id <= aclLast && "Unknown device id!");
const FamilyMapping *family = familySet + tgtInfo.arch_id;
if (!family) return "";
assert((tgtInfo.chip_id) < family->children_size && "Unknown family id!");
const TargetMapping *target = &family->target[tgtInfo.chip_id];
return (target) ? target->codegen_name : "";
}
/*! Function that modifies the code gen level based on the
* function size threshhold.
*/
static CodeGenOpt::Level
AdjustCGOptLevel(Module& M, CodeGenOpt::Level OrigOLvl)
{
const unsigned int FuncSizeThreshold = 10000;
if (OrigOLvl == CodeGenOpt::None)
return OrigOLvl;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Function *F = (Function *)I;
if (F->size() > FuncSizeThreshold) {
return CodeGenOpt::None;
}
}
return OrigOLvl;
}
int
llvmCodeGen(
Module* Composite,
amd::option::Options *OptionsObj,
std::string& output,
aclBinary* binary)
{
const FamilyMapping &familyMap = familySet[binary->target.arch_id];
const bool optimize = (OptionsObj ? (OptionsObj->oVariables->OptLevel > 0) : true);
const TargetMapping* targetMap = familyMap.target;
unsigned famID = binary->target.chip_id;
if (!targetMap || !targetMap[famID].supported) {
LogError("Device is not supported by code generator!");
return 1;
}
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1463
#else
// a dirty way to guarantee "push bp" inserted by CodeGen in prologue
llvm::NoFramePointerElim = !optimize;
#endif
// Load the module to be compiled...
Module &mod = *Composite;
// FIXME: The triple given in this map is wrong and isn't really
// useful. Only need the architecture.
const std::string TargetTriple = std::string(familyMap.triple);
Triple TheTriple(TargetTriple);
if (TheTriple.getTriple().empty()) {
TheTriple.setTriple(sys::getDefaultTargetTriple());
}
Triple::ArchType arch = TheTriple.getArch();
bool isGPU = (arch == Triple::amdil || arch == Triple::amdil64 ||
arch == Triple::hsail || arch == Triple::hsail64);
if (isGPU) {
TheTriple.setOS(Triple::UnknownOS);
} else { // CPUs
// FIXME: This should come from somewhere else.
#ifdef __linux__
TheTriple.setOS(Triple::Linux);
#else
TheTriple.setOS(Triple::MinGW32);
#endif
}
TheTriple.setEnvironment(Triple::AMDOpenCL);
// FIXME: need to make AMDOpenCL be the same as ELF
if (OptionsObj->oVariables->UseJIT)
TheTriple.setEnvironment(Triple::ELF);
mod.setTargetTriple(TheTriple.getTriple());
// Allocate target machine. First, check whether the user has explicitly
// specified an architecture to compile for. If so we have to look it up by
// name, because it might be a backend that has no mapping to a target triple.
const Target *TheTarget = 0;
assert(binary->target.arch_id != aclError && "Cannot have the error device!");
std::string MArch = familyMap.architecture;
#ifdef WITH_TARGET_HSAIL
if (MArch == "hsail" && OptionsObj->oVariables->GPU64BitIsa) {
MArch = std::string("hsail-64");
}
#endif
for (TargetRegistry::iterator it = TargetRegistry::begin(),
ie = TargetRegistry::end(); it != ie; ++it) {
if (MArch == it->getName()) {
TheTarget = &*it;
break;
}
}
if (!TheTarget) {
errs() << ": ERROR: invalid target '" << MArch << "'.\n";
return 1;
}
CodeGenOpt::Level OLvl = CodeGenOpt::None;
switch (OptionsObj->oVariables->OptLevel) {
case 0: // -O0
OLvl = CodeGenOpt::None;
break;
case 1: // -O1
OLvl = CodeGenOpt::Less;
break;
default:
assert(!"Error with optimization level");
case 2: // -O2
case 5: // -O5(-Os)
OLvl = CodeGenOpt::Default;
break;
case 3: // -O3
case 4: // -O4
OLvl = CodeGenOpt::Aggressive;
break;
};
// If there is a very big function, lower the optimization level.
OLvl = AdjustCGOptLevel(mod, OLvl);
// Adjust the triple to match (if known), otherwise stick with the
// module/host triple.
Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
if (Type != Triple::UnknownArch)
TheTriple.setArch(Type);
// Package up features to be passed to target/subtarget
std::string FeatureStr;
if ((Type == Triple::amdil || Type == Triple::amdil64) &&
targetMap[famID].chip_options) {
uint64_t y = targetMap[famID].chip_options;
for (uint64_t x = 0; y != 0; y >>= 1, ++x) {
if (!(y & 0x1) && (x >= 11 && x < 16)) {
continue;
}
if ((1 << x) == F_NO_ALIAS) {
FeatureStr += (!OptionsObj->oVariables->AssumeAlias ? '+' : '-');
} else if ((1 << x) == F_STACK_UAV) {
FeatureStr += (OptionsObj->oVariables->UseStackUAV ? '+' : '-');
} else if ((1 << x) == F_MACRO_CALL) {
FeatureStr += (OptionsObj->oVariables->UseMacroForCall ? '+' : '-');
} else if ((1 << x) == F_64BIT_PTR) {
FeatureStr += (binary->target.arch_id == aclAMDIL64) ? '+' : '-';
} else {
FeatureStr += ((y & 0x1) ? '+' : '-');
}
FeatureStr += GPUCodeGenFlagTable[x];
if (y != 0x1) {
FeatureStr += ',';
}
}
}
if (Type == Triple::amdil64) {
if (OptionsObj->oVariables->SmallGlobalObjects)
FeatureStr += ",+small-global-objects";
}
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1463
llvm::TargetOptions targetOptions;
targetOptions.NoFramePointerElim = false;
targetOptions.StackAlignmentOverride =
OptionsObj->oVariables->CPUStackAlignment;
// jgolds
//targetOptions.EnableEBB = (optimize && OptionsObj->oVariables->CGEBB);
//targetOptions.EnableBFO = OptionsObj->oVariables->CGBFO;
//targetOptions.NoExcessFPPrecision = !OptionsObj->oVariables->EnableFMA;
// Don't allow unsafe optimizations for CPU because the library
// contains code that is not safe. See bug 9567.
if (isGPU)
targetOptions.UnsafeFPMath = OptionsObj->oVariables->UnsafeMathOpt;
targetOptions.LessPreciseFPMADOption = OptionsObj->oVariables->MadEnable ||
OptionsObj->oVariables->EnableMAD;
targetOptions.NoInfsFPMath = OptionsObj->oVariables->FiniteMathOnly;
// Need to add a support for OptionsObj->oVariables->NoSignedZeros,
targetOptions.NoNaNsFPMath = OptionsObj->oVariables->FastRelaxedMath;
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
aclGetCodegenName(binary->target), FeatureStr, targetOptions,
WINDOWS_SWITCH(Reloc::DynamicNoPIC, Reloc::PIC_),
CodeModel::Default, OLvl));
#else
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
aclGetCodegenName(binary->target), FeatureStr,
WINDOWS_SWITCH(Reloc::DynamicNoPIC, Reloc::PIC_),
CodeModel::Default));
assert(target.get() && "Could not allocate target machine!");
#endif
// MCJIT(Jan)
if(!isGPU && OptionsObj->oVariables->UseJIT) {
TargetMachine* jittarget(TheTarget->createTargetMachine(TheTriple.getTriple(),
aclGetCodegenName(binary->target), FeatureStr, targetOptions,
WINDOWS_SWITCH(Reloc::DynamicNoPIC, Reloc::PIC_),
CodeModel::Default, OLvl));
std::string ErrStr = jitCodeGen(Composite, jittarget, OLvl, output);
if (!ErrStr.empty()) {
LogError("MCJIT failed to generate code");
LogError(ErrStr.c_str());
return 1;
}
return 0;
}
TargetMachine &Target = *target;
// Figure out where we are going to send the output...
raw_string_ostream *RSOut = new raw_string_ostream(output);
formatted_raw_ostream *Out = new formatted_raw_ostream(*RSOut, formatted_raw_ostream::DELETE_STREAM);
if (Out == 0) {
LogError("llvmCodeGen couldn't create an output stream");
return 1;
}
// Build up all of the passes that we want to do to the module or function or
// Basic Block.
PassManager Passes;
// Add the target data from the target machine, if it exists, or the module.
if (const DataLayout *TD = Target.getDataLayout())
Passes.add(new DataLayout(*TD));
else
Passes.add(new DataLayout(&mod));
// Override default to generate verbose assembly, if the device is not the GPU.
// The GPU sets this in AMDILTargetMachine.cpp.
if (familyMap.target == (const TargetMapping*)&X86TargetMapping ||
#if WITH_VERSION_0_9
familyMap.target == (const TargetMapping*)&A32TargetMapping ||
familyMap.target == (const TargetMapping*)&A32TargetMapping ||
#elif WITH_VERSION_0_8
#else
#error "The current version implementation was not implemented here."
#endif
familyMap.target == (const TargetMapping*)&X64TargetMapping
) {
Target.setAsmVerbosityDefault(true);
}
#ifdef WITH_TARGET_HSAIL
if (isHSAILTarget(binary->target)) {
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_ObjectFile, true)) {
delete Out;
return 1;
}
} else
#endif
{
#ifndef NDEBUG
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1144
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, false))
#else
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, OLvl, false))
#endif
#else
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1144
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, true))
#else
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, OLvl, true))
#endif
#endif
{
delete Out;
return 1;
}
}
Passes.run(mod);
delete Out;
return 0;
}
int
CLCodeGen::codegen(llvm::Module *input)
{
uint64_t time_cg = 0ULL;
if (Options()->oVariables->EnableBuildTiming) {
time_cg = amd::Os::timeNanos();
}
llvmbinary_ = input;
amdcl::CompilerStage *cs = reinterpret_cast<amdcl::CompilerStage*>(this);
if (!isHSAILTarget(cs->Elf()->target)) {
setWholeProgram(true);
}
int ret = llvmCodeGen(LLVMBinary(), Options(), Source(), Elf());
if (Options()->oVariables->EnableBuildTiming) {
time_cg = amd::Os::timeNanos() - time_cg;
std::stringstream tmp_ss;
tmp_ss << " LLVM CodeGen time: "
<< time_cg/1000ULL
<< "us\n";
appendLogToCL(CL(), tmp_ss.str());
}
if (!Source().empty() && Options()->isDumpFlagSet(amd::option::DUMP_CGIL)) {
std::string ilFileName = Options()->getDumpFileName(".il");
std::fstream f;
f.open(ilFileName.c_str(), (std::fstream::out | std::fstream::binary));
f.write(Source().data(), Source().length());
f.close();
}
return ret;
}
<commit_msg>P4 to Git Change 1087805 by yaxunl@yaxunl_stg_win50 on 2014/10/15 16:07:03<commit_after>//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#include "top.hpp"
#include "codegen.hpp"
#include "utils/libUtils.h"
#include "os/os.hpp"
#include "jit/src/jit.hpp"
#include "utils/target_mappings.h"
#ifdef _MSC_VER
/* for disabling warning in llvm/ADT/Statistic.h */
#pragma warning(disable:4146)
#endif
#include "llvm/ADT/Statistic.h"
#ifdef _MSC_VER
#pragma warning(default:4146)
#endif
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/DataLayout.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
using namespace amdcl;
using namespace llvm;
static std::string aclGetCodegenName(const aclTargetInfo &tgtInfo)
{
assert(tgtInfo.arch_id <= aclLast && "Unknown device id!");
const FamilyMapping *family = familySet + tgtInfo.arch_id;
if (!family) return "";
assert((tgtInfo.chip_id) < family->children_size && "Unknown family id!");
const TargetMapping *target = &family->target[tgtInfo.chip_id];
return (target) ? target->codegen_name : "";
}
/*! Function that modifies the code gen level based on the
* function size threshhold.
*/
static CodeGenOpt::Level
AdjustCGOptLevel(Module& M, CodeGenOpt::Level OrigOLvl)
{
const unsigned int FuncSizeThreshold = 10000;
if (OrigOLvl == CodeGenOpt::None)
return OrigOLvl;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Function *F = (Function *)I;
if (F->size() > FuncSizeThreshold) {
return CodeGenOpt::None;
}
}
return OrigOLvl;
}
int
llvmCodeGen(
Module* Composite,
amd::option::Options *OptionsObj,
std::string& output,
aclBinary* binary)
{
const FamilyMapping &familyMap = familySet[binary->target.arch_id];
const bool optimize = (OptionsObj ? (OptionsObj->oVariables->OptLevel > 0) : true);
const TargetMapping* targetMap = familyMap.target;
unsigned famID = binary->target.chip_id;
if (!targetMap || !targetMap[famID].supported) {
LogError("Device is not supported by code generator!");
return 1;
}
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1463
#else
// a dirty way to guarantee "push bp" inserted by CodeGen in prologue
llvm::NoFramePointerElim = !optimize;
#endif
// Load the module to be compiled...
Module &mod = *Composite;
// FIXME: The triple given in this map is wrong and isn't really
// useful. Only need the architecture.
const std::string TargetTriple = std::string(familyMap.triple);
Triple TheTriple(TargetTriple);
if (TheTriple.getTriple().empty()) {
TheTriple.setTriple(sys::getDefaultTargetTriple());
}
Triple::ArchType arch = TheTriple.getArch();
bool isGPU = (arch == Triple::amdil || arch == Triple::amdil64 ||
arch == Triple::hsail || arch == Triple::hsail64);
if (isGPU) {
TheTriple.setOS(Triple::UnknownOS);
} else { // CPUs
// FIXME: This should come from somewhere else.
#ifdef __linux__
TheTriple.setOS(Triple::Linux);
#else
TheTriple.setOS(Triple::MinGW32);
#endif
}
TheTriple.setEnvironment(Triple::AMDOpenCL);
// FIXME: need to make AMDOpenCL be the same as ELF
if (OptionsObj->oVariables->UseJIT)
TheTriple.setEnvironment(Triple::ELF);
mod.setTargetTriple(TheTriple.getTriple());
// Allocate target machine. First, check whether the user has explicitly
// specified an architecture to compile for. If so we have to look it up by
// name, because it might be a backend that has no mapping to a target triple.
const Target *TheTarget = 0;
assert(binary->target.arch_id != aclError && "Cannot have the error device!");
std::string MArch = familyMap.architecture;
#ifdef WITH_TARGET_HSAIL
if (MArch == "hsail" && OptionsObj->oVariables->GPU64BitIsa) {
MArch = std::string("hsail-64");
}
#endif
for (TargetRegistry::iterator it = TargetRegistry::begin(),
ie = TargetRegistry::end(); it != ie; ++it) {
if (MArch == it->getName()) {
TheTarget = &*it;
break;
}
}
if (!TheTarget) {
errs() << ": ERROR: invalid target '" << MArch << "'.\n";
return 1;
}
CodeGenOpt::Level OLvl = CodeGenOpt::None;
switch (OptionsObj->oVariables->OptLevel) {
case 0: // -O0
OLvl = CodeGenOpt::None;
break;
case 1: // -O1
OLvl = CodeGenOpt::Less;
break;
default:
assert(!"Error with optimization level");
case 2: // -O2
case 5: // -O5(-Os)
OLvl = CodeGenOpt::Default;
break;
case 3: // -O3
case 4: // -O4
OLvl = CodeGenOpt::Aggressive;
break;
};
// If there is a very big function, lower the optimization level.
OLvl = AdjustCGOptLevel(mod, OLvl);
// Adjust the triple to match (if known), otherwise stick with the
// module/host triple.
Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
if (Type != Triple::UnknownArch)
TheTriple.setArch(Type);
// Package up features to be passed to target/subtarget
std::string FeatureStr;
if ((Type == Triple::amdil || Type == Triple::amdil64) &&
targetMap[famID].chip_options) {
uint64_t y = targetMap[famID].chip_options;
for (uint64_t x = 0; y != 0; y >>= 1, ++x) {
if (!(y & 0x1) && (x >= 11 && x < 16)) {
continue;
}
if ((1 << x) == F_NO_ALIAS) {
FeatureStr += (!OptionsObj->oVariables->AssumeAlias ? '+' : '-');
} else if ((1 << x) == F_STACK_UAV) {
FeatureStr += (OptionsObj->oVariables->UseStackUAV ? '+' : '-');
} else if ((1 << x) == F_MACRO_CALL) {
FeatureStr += (OptionsObj->oVariables->UseMacroForCall ? '+' : '-');
} else if ((1 << x) == F_64BIT_PTR) {
FeatureStr += (binary->target.arch_id == aclAMDIL64) ? '+' : '-';
} else {
FeatureStr += ((y & 0x1) ? '+' : '-');
}
FeatureStr += GPUCodeGenFlagTable[x];
if (y != 0x1) {
FeatureStr += ',';
}
}
}
if (Type == Triple::amdil64) {
if (OptionsObj->oVariables->SmallGlobalObjects)
FeatureStr += ",+small-global-objects";
}
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1463
llvm::TargetOptions targetOptions;
targetOptions.NoFramePointerElim = false;
targetOptions.StackAlignmentOverride =
OptionsObj->oVariables->CPUStackAlignment;
// jgolds
//targetOptions.EnableEBB = (optimize && OptionsObj->oVariables->CGEBB);
//targetOptions.EnableBFO = OptionsObj->oVariables->CGBFO;
//targetOptions.NoExcessFPPrecision = !OptionsObj->oVariables->EnableFMA;
// Don't allow unsafe optimizations for CPU because the library
// contains code that is not safe. See bug 9567.
if (isGPU)
targetOptions.UnsafeFPMath = OptionsObj->oVariables->UnsafeMathOpt;
targetOptions.LessPreciseFPMADOption = OptionsObj->oVariables->MadEnable ||
OptionsObj->oVariables->EnableMAD;
targetOptions.NoInfsFPMath = OptionsObj->oVariables->FiniteMathOnly;
// Need to add a support for OptionsObj->oVariables->NoSignedZeros,
targetOptions.NoNaNsFPMath = OptionsObj->oVariables->FastRelaxedMath;
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
aclGetCodegenName(binary->target), FeatureStr, targetOptions,
WINDOWS_SWITCH(Reloc::DynamicNoPIC, Reloc::PIC_),
CodeModel::Default, OLvl));
#else
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
aclGetCodegenName(binary->target), FeatureStr,
WINDOWS_SWITCH(Reloc::DynamicNoPIC, Reloc::PIC_),
CodeModel::Default));
assert(target.get() && "Could not allocate target machine!");
#endif
// MCJIT(Jan)
if(!isGPU && OptionsObj->oVariables->UseJIT) {
TargetMachine* jittarget(TheTarget->createTargetMachine(TheTriple.getTriple(),
aclGetCodegenName(binary->target), FeatureStr, targetOptions,
WINDOWS_SWITCH(Reloc::DynamicNoPIC, Reloc::PIC_),
CodeModel::Default, OLvl));
std::string ErrStr = jitCodeGen(Composite, jittarget, OLvl, output);
if (!ErrStr.empty()) {
LogError("MCJIT failed to generate code");
LogError(ErrStr.c_str());
return 1;
}
return 0;
}
TargetMachine &Target = *target;
// Figure out where we are going to send the output...
raw_string_ostream *RSOut = new raw_string_ostream(output);
formatted_raw_ostream *Out = new formatted_raw_ostream(*RSOut, formatted_raw_ostream::DELETE_STREAM);
if (Out == 0) {
LogError("llvmCodeGen couldn't create an output stream");
return 1;
}
// Build up all of the passes that we want to do to the module or function or
// Basic Block.
PassManager Passes;
// Add the target data from the target machine, if it exists, or the module.
if (const DataLayout *TD = Target.getDataLayout())
Passes.add(new DataLayout(*TD));
else
Passes.add(new DataLayout(&mod));
// Override default to generate verbose assembly, if the device is not the GPU.
// The GPU sets this in AMDILTargetMachine.cpp.
if (familyMap.target == (const TargetMapping*)&X86TargetMapping ||
#if WITH_VERSION_0_9
familyMap.target == (const TargetMapping*)&A32TargetMapping ||
familyMap.target == (const TargetMapping*)&A32TargetMapping ||
#elif WITH_VERSION_0_8
#else
#error "The current version implementation was not implemented here."
#endif
familyMap.target == (const TargetMapping*)&X64TargetMapping
) {
Target.setAsmVerbosityDefault(true);
}
#ifdef WITH_TARGET_HSAIL
if (isHSAILTarget(binary->target)) {
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_ObjectFile, true)) {
delete Out;
return 1;
}
} else
#endif
{
#ifndef NDEBUG
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1144
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, false))
#else
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, OLvl, false))
#endif
#else
#if 1 || LLVM_TRUNK_INTEGRATION_CL >= 1144
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, true))
#else
if (Target.addPassesToEmitFile(Passes, *Out, TargetMachine::CGFT_AssemblyFile, OLvl, true))
#endif
#endif
{
delete Out;
return 1;
}
}
Passes.run(mod);
llvm::PrintStatistics();
delete Out;
return 0;
}
int
CLCodeGen::codegen(llvm::Module *input)
{
uint64_t time_cg = 0ULL;
if (Options()->oVariables->EnableBuildTiming) {
time_cg = amd::Os::timeNanos();
}
llvmbinary_ = input;
amdcl::CompilerStage *cs = reinterpret_cast<amdcl::CompilerStage*>(this);
if (!isHSAILTarget(cs->Elf()->target)) {
setWholeProgram(true);
}
int ret = llvmCodeGen(LLVMBinary(), Options(), Source(), Elf());
if (Options()->oVariables->EnableBuildTiming) {
time_cg = amd::Os::timeNanos() - time_cg;
std::stringstream tmp_ss;
tmp_ss << " LLVM CodeGen time: "
<< time_cg/1000ULL
<< "us\n";
appendLogToCL(CL(), tmp_ss.str());
}
if (!Source().empty() && Options()->isDumpFlagSet(amd::option::DUMP_CGIL)) {
std::string ilFileName = Options()->getDumpFileName(".il");
std::fstream f;
f.open(ilFileName.c_str(), (std::fstream::out | std::fstream::binary));
f.write(Source().data(), Source().length());
f.close();
}
return ret;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/14/2020, 3:53:32 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
ll W, H, K;
public:
Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}
ll answer()
{
ll ans{0};
for (auto y{1LL}; y < H; ++y)
{
ans += calc(0, y);
}
for (auto s{1LL}; s < W; ++s)
{
for (auto y{1LL}; s * y < 2 * K && y < H; ++y)
{
ans += calc(s, y);
}
}
return ans;
}
private:
ll calc(ll s, ll y)
{
ll R{2 * K - H * s + s * y + gcd(s, H) + 2};
if (R < 0)
{
return 0;
}
ll ans{min(W - 1, R / H)};
ll x{R / H + 1};
if (x <= W - 1 && H * x - gcd(H - y, x) + gcd(y, x + s) <= R)
{
++ans;
}
return ans;
}
};
// ----- main() -----
int main()
{
ll W, H, K;
cin >> W >> H >> K;
Solve solve(W, H, K), solve2(H, W, K);
ll ans{2 * (solve.answer() + solve2.answer())};
cout << ans << endl;
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/14/2020, 3:53:32 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
ll W, H, K;
public:
Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}
ll answer()
{
ll ans{0};
for (auto y{1LL}; y < H; ++y)
{
ans += calc(0, y);
}
for (auto s{1LL}; s < W; ++s)
{
for (auto y{1LL}; s * y < 2 * K && y < H; ++y)
{
ans += calc(s, y);
}
}
return ans;
}
private:
ll calc(ll s, ll y)
{
ll R{2 * K - H * s + s * y + gcd(s, H) + 2};
if (R < 0)
{
return 0;
}
ll ans{min(W - s - 1, R / H)};
ll x{R / H + 1};
if (x + s < W && H * x - gcd(H - y, x) + gcd(y, x + s) <= R)
{
++ans;
}
return ans;
}
};
// ----- main() -----
int main()
{
ll W, H, K;
cin >> W >> H >> K;
Solve solve(W, H, K), solve2(H, W, K);
ll ans{2 * (solve.answer() + solve2.answer())};
cout << ans << endl;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#include <memory>
#include <dune/stuff/common/memory.hh>
#include <dune/hdd/playground/linearelliptic/discreteproblem.hh>
#include <dune/hdd/playground/linearelliptic/discretizations/swipdg.hh>
template< class GridImp >
class LinearellipticExampleSWIPDG
{
public:
typedef GridImp GridType;
typedef Dune::HDD::LinearElliptic::DiscreteProblem< GridType > DiscreteProblemType;
typedef typename DiscreteProblemType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = DiscreteProblemType::dimRange;
typedef Dune::HDD::LinearElliptic::Discretizations::SWIPDG< GridType, Dune::Stuff::Grid::ChooseLayer::leaf,
RangeFieldType, dimRange, 1 > DiscretizationType;
static std::string static_id()
{
return "linearelliptic.swipdg";
}
static void write_config_file(const std::string filename = static_id() + ".cfg")
{
DiscreteProblemType::write_config(filename, static_id());
}
void initialize(const std::vector< std::string > arguments)
{
using namespace Dune;
if (!discrete_problem_) {
discrete_problem_ = Stuff::Common::make_unique< DiscreteProblemType >(static_id(), arguments);
const bool debug_logging = discrete_problem_->debug_logging();
auto& info = DSC_LOG_INFO;
auto& debug = DSC_LOG_DEBUG;
discretization_ = Stuff::Common::make_unique< DiscretizationType >(discrete_problem_->grid_provider(),
discrete_problem_->boundary_info(),
discrete_problem_->problem());
info << "initializing discretization";
if (debug_logging)
info << ":" << std::endl;
else
info << "... " << std::flush;
Dune::Timer timer;
discretization_->init(debug, " ");
if (!debug_logging)
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} else
DSC_LOG_INFO << "initialize has already been called" << std::endl;
} // ... initialize(...)
const DiscreteProblemType& discrete_problem() const
{
return *discrete_problem_;
}
const DiscretizationType& discretization() const
{
return *discretization_;
}
DiscretizationType* discretization_and_return_ptr() const
{
return new DiscretizationType(*discretization_);
}
private:
std::unique_ptr< DiscreteProblemType > discrete_problem_;
std::unique_ptr< DiscretizationType > discretization_;
}; // class LinearellipticExampleSWIPDG
namespace Dune {
// forward grid declaratios
template< int dim, int dimworld, typename _ctype >
class SGrid;
template< int dim >
class YaspGrid;
} // namespace Dune
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 1, 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 2, 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 3, 3 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 3 > >;
#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
<commit_msg>[examples.linearelliptic.swipdg] choose istl backend * way faster than eigen for large systems<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#include <memory>
#include <dune/stuff/common/memory.hh>
#include <dune/hdd/playground/linearelliptic/discreteproblem.hh>
#include <dune/hdd/playground/linearelliptic/discretizations/swipdg.hh>
template< class GridImp >
class LinearellipticExampleSWIPDG
{
public:
typedef GridImp GridType;
typedef Dune::HDD::LinearElliptic::DiscreteProblem< GridType > DiscreteProblemType;
typedef typename DiscreteProblemType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = DiscreteProblemType::dimRange;
typedef Dune::HDD::LinearElliptic::Discretizations::SWIPDG
< GridType, Dune::Stuff::Grid::ChooseLayer::leaf, RangeFieldType, dimRange, 1
, Dune::GDT::ChooseSpaceBackend::fem_localfunction
, Dune::Stuff::LA::ChooseBackend::istl_sparse > DiscretizationType;
static std::string static_id()
{
return "linearelliptic.swipdg";
}
static void write_config_file(const std::string filename = static_id() + ".cfg")
{
DiscreteProblemType::write_config(filename, static_id());
}
void initialize(const std::vector< std::string > arguments)
{
using namespace Dune;
if (!discrete_problem_) {
discrete_problem_ = Stuff::Common::make_unique< DiscreteProblemType >(static_id(), arguments);
const bool debug_logging = discrete_problem_->debug_logging();
auto& info = DSC_LOG_INFO;
auto& debug = DSC_LOG_DEBUG;
discretization_ = Stuff::Common::make_unique< DiscretizationType >(discrete_problem_->grid_provider(),
discrete_problem_->boundary_info(),
discrete_problem_->problem());
info << "initializing discretization";
if (debug_logging)
info << ":" << std::endl;
else
info << "... " << std::flush;
Dune::Timer timer;
discretization_->init(debug, " ");
if (!debug_logging)
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} else
DSC_LOG_INFO << "initialize has already been called" << std::endl;
} // ... initialize(...)
const DiscreteProblemType& discrete_problem() const
{
return *discrete_problem_;
}
const DiscretizationType& discretization() const
{
return *discretization_;
}
DiscretizationType* discretization_and_return_ptr() const
{
return new DiscretizationType(*discretization_);
}
private:
std::unique_ptr< DiscreteProblemType > discrete_problem_;
std::unique_ptr< DiscretizationType > discretization_;
}; // class LinearellipticExampleSWIPDG
namespace Dune {
// forward grid declaratios
template< int dim, int dimworld, typename _ctype >
class SGrid;
template< int dim >
class YaspGrid;
} // namespace Dune
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 1, 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 2, 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 3, 3 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 3 > >;
#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
<|endoftext|> |
<commit_before>#ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
#define ITERTOOLS_SAMPLE_CLASSES_HPP
#include <iostream>
#include <cstddef>
namespace itertest {
class MoveOnly {
private:
int i; // not an aggregate
public:
MoveOnly(int v)
: i{v}
{ }
MoveOnly(const MoveOnly&) = delete;
MoveOnly& operator=(const MoveOnly&) = delete;
MoveOnly(MoveOnly&& other) noexcept
: i{other.i}
{ }
MoveOnly& operator=(MoveOnly&& other) noexcept {
this->i = other.i;
return *this;
}
friend std::ostream& operator<<(
std::ostream& out, const MoveOnly& self) {
return out << self.i;
}
};
class DerefByValue {
private:
static constexpr std::size_t N = 3;
int array[N] = {0};
public:
DerefByValue() = default;
class Iterator {
private:
int *current;
public:
Iterator() = default;
Iterator(int *p)
: current{p}
{ }
bool operator!=(const Iterator& other) const {
return this->current != other.current;
}
// for testing, iterator derefences to an int instead of
// an int&
int operator*() {
return *this->current;
}
Iterator& operator++() {
++this->current;
return *this;
}
};
Iterator begin() {
return {this->array};
}
Iterator end() {
return {this->array + N};
}
};
}
#endif // #ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
<commit_msg>makes MoveOnly less-than comparable<commit_after>#ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
#define ITERTOOLS_SAMPLE_CLASSES_HPP
#include <iostream>
#include <utility>
#include <cstddef>
namespace itertest {
class MoveOnly {
private:
int i; // not an aggregate
public:
MoveOnly(int v)
: i{v}
{ }
MoveOnly(const MoveOnly&) = delete;
MoveOnly& operator=(const MoveOnly&) = delete;
MoveOnly(MoveOnly&& other) noexcept
: i{other.i}
{ }
MoveOnly& operator=(MoveOnly&& other) noexcept {
this->i = other.i;
return *this;
}
// for std::next_permutation compatibility
friend bool operator<(const MoveOnly& lhs, const MoveOnly& rhs) {
return lhs.i < rhs.i;
}
friend std::ostream& operator<<(
std::ostream& out, const MoveOnly& self) {
return out << self.i;
}
};
class DerefByValue {
private:
static constexpr std::size_t N = 3;
int array[N] = {0};
public:
DerefByValue() = default;
class Iterator {
private:
int *current;
public:
Iterator() = default;
Iterator(int *p)
: current{p}
{ }
bool operator!=(const Iterator& other) const {
return this->current != other.current;
}
// for testing, iterator derefences to an int instead of
// an int&
int operator*() {
return *this->current;
}
Iterator& operator++() {
++this->current;
return *this;
}
};
Iterator begin() {
return {this->array};
}
Iterator end() {
return {this->array + N};
}
};
}
#endif // #ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "openpagesmanager.h"
#include "centralwidget.h"
#include "helpconstants.h"
#include "helpmanager.h"
#include "helpviewer.h"
#include "openpagesmodel.h"
#include "openpageswidget.h"
#include <QtGui/QComboBox>
#include <QtGui/QTreeView>
#include <QtHelp/QHelpEngineCore>
using namespace Help::Internal;
OpenPagesManager *OpenPagesManager::m_instance = 0;
// -- OpenPagesManager
OpenPagesManager::OpenPagesManager(QObject *parent)
: QObject(parent)
, m_comboBox(0)
, m_model(0)
, m_openPagesWidget(0)
{
Q_ASSERT(!m_instance);
m_instance = this;
m_model = new OpenPagesModel(this);
m_openPagesWidget = new OpenPagesWidget(m_model);
connect(m_openPagesWidget, SIGNAL(setCurrentPage(QModelIndex)), this,
SLOT(setCurrentPage(QModelIndex)));
connect(m_openPagesWidget, SIGNAL(closePage(QModelIndex)), this,
SLOT(closePage(QModelIndex)));
connect(m_openPagesWidget, SIGNAL(closePagesExcept(QModelIndex)), this,
SLOT(closePagesExcept(QModelIndex)));
m_comboBox = new QComboBox;
m_comboBox->setModel(m_model);
m_comboBox->setMinimumContentsLength(40);
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this,
SLOT(setCurrentPage(int)));
}
OpenPagesManager &OpenPagesManager::instance()
{
Q_ASSERT(m_instance);
return *m_instance;
}
QWidget* OpenPagesManager::openPagesWidget() const
{
return m_openPagesWidget;
}
QComboBox* OpenPagesManager::openPagesComboBox() const
{
if (!m_comboBox) {
}
return m_comboBox;
}
int OpenPagesManager::pageCount() const
{
return m_model->rowCount();
}
QStringList splitString(const QVariant &value)
{
using namespace Help::Constants;
return value.toString().split(ListSeparator, QString::SkipEmptyParts);
}
void OpenPagesManager::setupInitialPages()
{
const QHelpEngineCore &engine = HelpManager::helpEngineCore();
const int option = engine.customValue(QLatin1String("StartOption"),
Help::Constants::ShowLastPages).toInt();
QString homePage = engine.customValue(QLatin1String("DefaultHomePage"),
Help::Constants::AboutBlank).toString();
int initialPage = 0;
switch (option) {
case Help::Constants::ShowHomePage: {
m_model->addPage(engine.customValue(QLatin1String("HomePage"),
homePage).toString());
} break;
case Help::Constants::ShowBlankPage: {
m_model->addPage(QUrl(Help::Constants::AboutBlank));
} break;
case Help::Constants::ShowLastPages: {
const QStringList &lastShownPageList = splitString(engine
.customValue(QLatin1String("LastShownPages")));
const int pageCount = lastShownPageList.count();
if (pageCount > 0) {
QStringList zoomFactors = splitString(engine
.customValue(QLatin1String("LastShownPagesZoom")));
while (zoomFactors.count() < pageCount)
zoomFactors.append(Help::Constants::DefaultZoomFactor);
initialPage = engine.customValue(QLatin1String("LastTabPage"), 0).toInt();
for (int curPage = 0; curPage < pageCount; ++curPage) {
const QString &curFile = lastShownPageList.at(curPage);
if (engine.findFile(curFile).isValid()
|| curFile == Help::Constants::AboutBlank) {
m_model->addPage(curFile, zoomFactors.at(curPage).toFloat());
} else if (curPage <= initialPage && initialPage > 0) {
--initialPage;
}
}
}
} break;
default: break;
}
if (m_model->rowCount() == 0)
m_model->addPage(homePage);
for (int i = 0; i < m_model->rowCount(); ++i)
CentralWidget::instance()->addPage(m_model->pageAt(i));
emit pagesChanged();
setCurrentPage(initialPage);
}
// -- public slots
HelpViewer *OpenPagesManager::createPage()
{
return createPage(QUrl(Help::Constants::AboutBlank));
}
HelpViewer *OpenPagesManager::createPageFromSearch(const QUrl &url)
{
return createPage(url, true);
}
HelpViewer *OpenPagesManager::createPage(const QUrl &url, bool fromSearch)
{
if (HelpViewer::launchWithExternalApp(url))
return 0;
m_model->addPage(url);
const int index = m_model->rowCount() - 1;
HelpViewer * const page = m_model->pageAt(index);
CentralWidget::instance()->addPage(page, fromSearch);
emit pagesChanged();
setCurrentPage(index);
return page;
}
void OpenPagesManager::setCurrentPage(int index)
{
m_comboBox->setCurrentIndex(index);
CentralWidget::instance()->setCurrentPage(m_model->pageAt(index));
selectCurrentPage(); // update the selction inside the tree view
}
void OpenPagesManager::setCurrentPage(const QModelIndex &index)
{
if (index.isValid()) {
m_comboBox->setCurrentIndex(index.row());
CentralWidget::instance()->setCurrentPage(m_model->pageAt(index.row()));
}
}
void OpenPagesManager::closeCurrentPage()
{
QModelIndexList indexes = m_openPagesWidget->selectionModel()->selectedRows();
if (indexes.isEmpty())
return;
Q_ASSERT(indexes.count() == 1);
removePage(indexes.first().row());
}
void OpenPagesManager::closePage(const QModelIndex &index)
{
if (index.isValid())
removePage(index.row());
}
void OpenPagesManager::closePagesExcept(const QModelIndex &index)
{
if (index.isValid()) {
int i = 0;
HelpViewer *viewer = m_model->pageAt(index.row());
while (m_model->rowCount() > 1) {
if (m_model->pageAt(i) != viewer) {
removePage(i);
} else {
i++;
}
}
}
}
// -- private
void OpenPagesManager::selectCurrentPage()
{
QItemSelectionModel * selModel = m_openPagesWidget->selectionModel();
selModel->clearSelection();
selModel->select(m_model->index(CentralWidget::instance()->currentIndex(), 0),
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
m_openPagesWidget->scrollTo(m_openPagesWidget->currentIndex());
}
void OpenPagesManager::removePage(int index)
{
Q_ASSERT(m_model->rowCount() > 1);
m_model->removePage(index);
CentralWidget::instance()->removePage(index);
emit pagesChanged();
selectCurrentPage(); // update the selction inside the tree view
}
<commit_msg>Fix typo and code leftover.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "openpagesmanager.h"
#include "centralwidget.h"
#include "helpconstants.h"
#include "helpmanager.h"
#include "helpviewer.h"
#include "openpagesmodel.h"
#include "openpageswidget.h"
#include <QtGui/QComboBox>
#include <QtGui/QTreeView>
#include <QtHelp/QHelpEngineCore>
using namespace Help::Internal;
OpenPagesManager *OpenPagesManager::m_instance = 0;
// -- OpenPagesManager
OpenPagesManager::OpenPagesManager(QObject *parent)
: QObject(parent)
, m_comboBox(0)
, m_model(0)
, m_openPagesWidget(0)
{
Q_ASSERT(!m_instance);
m_instance = this;
m_model = new OpenPagesModel(this);
m_openPagesWidget = new OpenPagesWidget(m_model);
connect(m_openPagesWidget, SIGNAL(setCurrentPage(QModelIndex)), this,
SLOT(setCurrentPage(QModelIndex)));
connect(m_openPagesWidget, SIGNAL(closePage(QModelIndex)), this,
SLOT(closePage(QModelIndex)));
connect(m_openPagesWidget, SIGNAL(closePagesExcept(QModelIndex)), this,
SLOT(closePagesExcept(QModelIndex)));
m_comboBox = new QComboBox;
m_comboBox->setModel(m_model);
m_comboBox->setMinimumContentsLength(40);
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this,
SLOT(setCurrentPage(int)));
}
OpenPagesManager &OpenPagesManager::instance()
{
Q_ASSERT(m_instance);
return *m_instance;
}
QWidget* OpenPagesManager::openPagesWidget() const
{
return m_openPagesWidget;
}
QComboBox* OpenPagesManager::openPagesComboBox() const
{
return m_comboBox;
}
int OpenPagesManager::pageCount() const
{
return m_model->rowCount();
}
QStringList splitString(const QVariant &value)
{
using namespace Help::Constants;
return value.toString().split(ListSeparator, QString::SkipEmptyParts);
}
void OpenPagesManager::setupInitialPages()
{
const QHelpEngineCore &engine = HelpManager::helpEngineCore();
const int option = engine.customValue(QLatin1String("StartOption"),
Help::Constants::ShowLastPages).toInt();
QString homePage = engine.customValue(QLatin1String("DefaultHomePage"),
Help::Constants::AboutBlank).toString();
int initialPage = 0;
switch (option) {
case Help::Constants::ShowHomePage: {
m_model->addPage(engine.customValue(QLatin1String("HomePage"),
homePage).toString());
} break;
case Help::Constants::ShowBlankPage: {
m_model->addPage(QUrl(Help::Constants::AboutBlank));
} break;
case Help::Constants::ShowLastPages: {
const QStringList &lastShownPageList = splitString(engine
.customValue(QLatin1String("LastShownPages")));
const int pageCount = lastShownPageList.count();
if (pageCount > 0) {
QStringList zoomFactors = splitString(engine
.customValue(QLatin1String("LastShownPagesZoom")));
while (zoomFactors.count() < pageCount)
zoomFactors.append(Help::Constants::DefaultZoomFactor);
initialPage = engine.customValue(QLatin1String("LastTabPage"), 0).toInt();
for (int curPage = 0; curPage < pageCount; ++curPage) {
const QString &curFile = lastShownPageList.at(curPage);
if (engine.findFile(curFile).isValid()
|| curFile == Help::Constants::AboutBlank) {
m_model->addPage(curFile, zoomFactors.at(curPage).toFloat());
} else if (curPage <= initialPage && initialPage > 0) {
--initialPage;
}
}
}
} break;
default: break;
}
if (m_model->rowCount() == 0)
m_model->addPage(homePage);
for (int i = 0; i < m_model->rowCount(); ++i)
CentralWidget::instance()->addPage(m_model->pageAt(i));
emit pagesChanged();
setCurrentPage(initialPage);
}
// -- public slots
HelpViewer *OpenPagesManager::createPage()
{
return createPage(QUrl(Help::Constants::AboutBlank));
}
HelpViewer *OpenPagesManager::createPageFromSearch(const QUrl &url)
{
return createPage(url, true);
}
HelpViewer *OpenPagesManager::createPage(const QUrl &url, bool fromSearch)
{
if (HelpViewer::launchWithExternalApp(url))
return 0;
m_model->addPage(url);
const int index = m_model->rowCount() - 1;
HelpViewer * const page = m_model->pageAt(index);
CentralWidget::instance()->addPage(page, fromSearch);
emit pagesChanged();
setCurrentPage(index);
return page;
}
void OpenPagesManager::setCurrentPage(int index)
{
m_comboBox->setCurrentIndex(index);
CentralWidget::instance()->setCurrentPage(m_model->pageAt(index));
selectCurrentPage(); // update the selection inside the tree view
}
void OpenPagesManager::setCurrentPage(const QModelIndex &index)
{
if (index.isValid()) {
m_comboBox->setCurrentIndex(index.row());
CentralWidget::instance()->setCurrentPage(m_model->pageAt(index.row()));
}
}
void OpenPagesManager::closeCurrentPage()
{
QModelIndexList indexes = m_openPagesWidget->selectionModel()->selectedRows();
if (indexes.isEmpty())
return;
Q_ASSERT(indexes.count() == 1);
removePage(indexes.first().row());
}
void OpenPagesManager::closePage(const QModelIndex &index)
{
if (index.isValid())
removePage(index.row());
}
void OpenPagesManager::closePagesExcept(const QModelIndex &index)
{
if (index.isValid()) {
int i = 0;
HelpViewer *viewer = m_model->pageAt(index.row());
while (m_model->rowCount() > 1) {
if (m_model->pageAt(i) != viewer) {
removePage(i);
} else {
i++;
}
}
}
}
// -- private
void OpenPagesManager::selectCurrentPage()
{
QItemSelectionModel * selModel = m_openPagesWidget->selectionModel();
selModel->clearSelection();
selModel->select(m_model->index(CentralWidget::instance()->currentIndex(), 0),
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
m_openPagesWidget->scrollTo(m_openPagesWidget->currentIndex());
}
void OpenPagesManager::removePage(int index)
{
Q_ASSERT(m_model->rowCount() > 1);
m_model->removePage(index);
CentralWidget::instance()->removePage(index);
emit pagesChanged();
selectCurrentPage(); // update the selection inside the tree view
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Controls.cpp
*
* Contains the yaw_controller() and depth_controller functions
******************************************************************************/
#include "Mapper.h"
/******************************************************************************
* float yaw_controller()
*
* Takes in readings from the IMU and returns a value between -1 and 1 (-100% -
* +100%) that the port and starboard thrusters should run at
******************************************************************************/
float yaw_controller(bno055_t bno055, pid_data_t yaw_pid)
{
float motor_percent;
float DT = .005;
float YAW_SAT = .2;
// control output //
if( bno055.yaw < 180 ) // AUV is pointed right
{
// u[2] is negative
motor_percent = yaw_pid.kp*(yaw_pid.err)
+ yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
else // AUV is pointed left
{
// u[2] is positive
motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r)
+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
// saturate yaw controller //
if( motor_percent > YAW_SAT )
{
motor_percent=YAW_SAT;
}
else if( motor_percent < -YAW_SAT )
{
motor_percent = -YAW_SAT;
}
yaw_pid.i_err += yaw_pid.err*DT;
// set current yaw to be the old yaw //
yaw_pid.oldyaw = bno055.yaw;
return motor_percent;
}
/******************************************************************************
* float depth_controller(float range)
*
* Takes a range-from-bottom reading from the laser range-finder code and
* returns a value between -1 and 1 (-100% - +100%) that the vertical thruster
* should run at
******************************************************************************/
/*
float depth_controller(float range)
{
float vert_percent; // vertical thruster output in a percentage
float depth_sum_error = 0; // accumulated range error for integral control
float range_current;
float range_old;
float
// accumulated range error for integral control //
depth_sum_error += range - depth_pid.setpoint;
if( range > depth_pid.setpoint )
{
vert_percent = depth_pid.kp*(range-depth_pid.setpoint)
+ depth_pid.ki*(depth_sum_error)
+ depth_pid.kd*((range_current-range_old)/DT);
}
else
{
// shut off vertical thruster //
vert_percent = 0;
}
// saturate depth controller //
if( vert_percent > DEPTH_SAT )
{
vert_percent = DEPTH_SAT;
}
else if( vert_percent < -DEPTH_SAT )
{
vert_percent = -DEPTH_SAT;
}
// set current depth to be the old depth //
depth_pid.old = depth_pid.current;
return vert_percent;
}
*/
<commit_msg>Uncommented depth_controller<commit_after>/******************************************************************************
* Controls.cpp
*
* Contains the yaw_controller() and depth_controller functions
******************************************************************************/
#include "Mapper.h"
/******************************************************************************
* float yaw_controller()
*
* Takes in readings from the IMU and returns a value between -1 and 1 (-100% -
* +100%) that the port and starboard thrusters should run at
******************************************************************************/
float yaw_controller(bno055_t bno055, pid_data_t yaw_pid)
{
float motor_percent;
float DT = .005;
float YAW_SAT = .2;
// control output //
if( bno055.yaw < 180 ) // AUV is pointed right
{
// u[2] is negative
motor_percent = yaw_pid.kp*(yaw_pid.err)
+ yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
else // AUV is pointed left
{
// u[2] is positive
motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r)
+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
// saturate yaw controller //
if( motor_percent > YAW_SAT )
{
motor_percent=YAW_SAT;
}
else if( motor_percent < -YAW_SAT )
{
motor_percent = -YAW_SAT;
}
yaw_pid.i_err += yaw_pid.err*DT;
// set current yaw to be the old yaw //
yaw_pid.oldyaw = bno055.yaw;
return motor_percent;
}
/******************************************************************************
* float depth_controller(float range)
*
* Takes a range-from-bottom reading from the laser range-finder code and
* returns a value between -1 and 1 (-100% - +100%) that the vertical thruster
* should run at
******************************************************************************/
float depth_controller(float range)
{
float vert_percent; // vertical thruster output in a percentage
float depth_sum_error = 0; // accumulated range error for integral control
float range_current;
float range_old;
// accumulated range error for integral control //
depth_sum_error += range - depth_pid.setpoint;
if( range > depth_pid.setpoint )
{
vert_percent = depth_pid.kp*(range-depth_pid.setpoint)
+ depth_pid.ki*(depth_sum_error)
+ depth_pid.kd*((range_current-range_old)/DT);
}
else
{
// shut off vertical thruster //
vert_percent = 0;
}
// saturate depth controller //
if( vert_percent > DEPTH_SAT )
{
vert_percent = DEPTH_SAT;
}
else if( vert_percent < -DEPTH_SAT )
{
vert_percent = -DEPTH_SAT;
}
// set current depth to be the old depth //
depth_pid.old = depth_pid.current;
return vert_percent;
}
<|endoftext|> |
<commit_before>
#include <cstdio>
#include <iostream>
#include "utility.hpp"
// Inludes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
static bool syncNN = true;
dai::Pipeline createNNPipeline(std::string nnPath) {
dai::Pipeline p;
auto colorCam = p.create<dai::node::ColorCamera>();
auto xlinkOut = p.create<dai::node::XLinkOut>();
auto nn1 = p.create<dai::node::NeuralNetwork>();
auto nnOut = p.create<dai::node::XLinkOut>();
nn1->setBlobPath(nnPath);
xlinkOut->setStreamName("preview");
nnOut->setStreamName("detections");
colorCam->setPreviewSize(300, 300);
colorCam->setResolution(dai::ColorCameraProperties::SensorResolution::THE_1080_P);
colorCam->setInterleaved(false);
colorCam->setColorOrder(dai::ColorCameraProperties::ColorOrder::BGR);
// Link plugins CAM -> NN -> XLINK
colorCam->preview.link(nn1->input);
if(syncNN) {
nn1->passthrough.link(xlinkOut->input);
} else {
colorCam->preview.link(xlinkOut->input);
}
nn1->out.link(nnOut->input);
return p;
}
int main(int argc, char** argv) {
using namespace std;
// Default blob path provided by Hunter private data download
// Applicable for easier example usage only
std::string nnPath(BLOB_PATH);
// If path to blob specified, use that
if(argc > 1) {
nnPath = std::string(argv[1]);
}
// Print which blob we are using
printf("Using blob at path: %s\n", nnPath.c_str());
// Create pipeline
dai::Pipeline p = createNNPipeline(nnPath);
// Connect to device with above created pipeline
dai::Device d(p);
// Start the pipeline
d.startPipeline();
cv::Mat frame;
auto preview = d.getOutputQueue("preview");
auto detections = d.getOutputQueue("detections");
while(1) {
auto imgFrame = preview->get<dai::ImgFrame>();
if(imgFrame) {
printf("Frame - w: %d, h: %d\n", imgFrame->getWidth(), imgFrame->getHeight());
frame = toMat(imgFrame->getData(), imgFrame->getWidth(), imgFrame->getHeight(), 3, 1);
}
struct Detection {
unsigned int label;
float score;
float x_min;
float y_min;
float x_max;
float y_max;
};
vector<Detection> dets;
auto det = detections->get<dai::NNData>();
std::vector<float> detData = det->getFirstLayerFp16();
if(detData.size() > 0) {
int i = 0;
while(detData[i * 7] != -1.0f) {
Detection d;
d.label = detData[i * 7 + 1];
d.score = detData[i * 7 + 2];
d.x_min = detData[i * 7 + 3];
d.y_min = detData[i * 7 + 4];
d.x_max = detData[i * 7 + 5];
d.y_max = detData[i * 7 + 6];
i++;
dets.push_back(d);
}
}
for(const auto& d : dets) {
int x1 = d.x_min * frame.cols;
int y1 = d.y_min * frame.rows;
int x2 = d.x_max * frame.cols;
int y2 = d.y_max * frame.rows;
cv::rectangle(frame, cv::Rect(cv::Point(x1, y1), cv::Point(x2, y2)), cv::Scalar(255, 255, 255));
}
printf("===================== %lu detection(s) =======================\n", dets.size());
for(unsigned det = 0; det < dets.size(); ++det) {
printf("%5d | %6.4f | %7.4f | %7.4f | %7.4f | %7.4f\n",
dets[det].label,
dets[det].score,
dets[det].x_min,
dets[det].y_min,
dets[det].x_max,
dets[det].y_max);
}
cv::imshow("preview", frame);
int key = cv::waitKey(1);
if(key == 'q') {
return 0;
}
}
return 0;
}
<commit_msg>Upgraded rgb mobilenet example<commit_after>#include <chrono>
#include <cstdio>
#include <iostream>
#include "utility.hpp"
// Inludes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
// MobilenetSSD label texts
static const std::vector<std::string> labelMap = {"background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus",
"car", "cat", "chair", "cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"};
static std::atomic<bool> syncNN{true};
int main(int argc, char** argv) {
using namespace std;
using namespace std::chrono;
// Default blob path provided by Hunter private data download
// Applicable for easier example usage only
std::string nnPath(BLOB_PATH);
// If path to blob specified, use that
if(argc > 1) {
nnPath = std::string(argv[1]);
}
// Print which blob we are using
printf("Using blob at path: %s\n", nnPath.c_str());
// Create pipeline
dai::Pipeline pipeline;
// Define source
auto camRgb = pipeline.create<dai::node::ColorCamera>();
auto xoutRgb = pipeline.create<dai::node::XLinkOut>();
auto nn = pipeline.create<dai::node::MobileNetDetectionNetwork>();
auto nnOut = pipeline.create<dai::node::XLinkOut>();
// Properties
camRgb->setPreviewSize(300, 300); // NN input
camRgb->setInterleaved(false);
camRgb->setFps(40);
// Define a neural network that will make predictions based on the source frames
nn->setConfidenceThreshold(0.5);
nn->setBlobPath(nnPath);
nn->setNumInferenceThreads(2);
nn->input.setBlocking(false);
xoutRgb->setStreamName("rgb");
nnOut->setStreamName("nn");
// Create outputs
if (syncNN) {
nn->passthrough.link(xoutRgb->input);
} else {
camRgb->preview.link(xoutRgb->input);
}
camRgb->preview.link(nn->input);
nn->out.link(nnOut->input);
// Connect to device with above created pipeline
dai::Device device(pipeline);
// Start the pipeline
device.startPipeline();
// Queues
auto qRgb = device.getOutputQueue("rgb", 4, false);
auto qDet = device.getOutputQueue("nn", 4, false);
// Add bounding boxes and text to the frame and show it to the user
auto displayFrame = [](std::string name, auto frame, auto detections) {
auto color = cv::Scalar(255, 0, 0);
// nn data, being the bounding box locations, are in <0..1> range - they need to be normalized with frame width/height
for(auto& detection : detections) {
int x1 = detection.xmin * frame.cols;
int y1 = detection.ymin * frame.rows;
int x2 = detection.xmax * frame.cols;
int y2 = detection.ymax * frame.rows;
int labelIndex = detection.label;
std::string labelStr = to_string(labelIndex);
if(labelIndex < labelMap.size()) {
labelStr = labelMap[labelIndex];
}
cv::putText(frame, labelStr, cv::Point(x1 + 10, y1 + 20), cv::FONT_HERSHEY_TRIPLEX, 0.5, color);
std::stringstream confStr;
confStr << std::fixed << std::setprecision(2) << detection.confidence * 100;
cv::putText(frame, confStr.str(), cv::Point(x1 + 10, y1 + 40), cv::FONT_HERSHEY_TRIPLEX, 0.5, color);
cv::rectangle(frame, cv::Rect(cv::Point(x1, y1), cv::Point(x2, y2)), color, cv::FONT_HERSHEY_SIMPLEX);
}
// Show the frame
cv::imshow(name, frame);
};
auto startTime = steady_clock::now();
int counter = 0;
float fps = 0;
while(true) {
auto inRgb = qRgb->get<dai::ImgFrame>();
auto inDet = qDet->get<dai::ImgDetections>();
auto detections = inDet->detections;
cv::Mat frame = inRgb->getCvFrame();
counter++;
auto currentTime = steady_clock::now();
auto elapsed = duration_cast<duration<float>>(currentTime - startTime);
if(elapsed > seconds(1)) {
fps = counter / elapsed.count();
counter = 0;
startTime = currentTime;
}
std::stringstream fpsStr;
fpsStr << "NN fps: " <<std::fixed << std::setprecision(2) << fps;
cv::putText(frame, fpsStr.str(), cv::Point(2, inRgb->getHeight() - 4), cv::FONT_HERSHEY_TRIPLEX, 0.4, 255, 0, 0);
displayFrame("video", frame, detections);
int key = cv::waitKey(1);
if(key == 'q' || key == 'Q')
return 0;
}
return 0;
}<|endoftext|> |
<commit_before>#include <iostream>
#include "libaps.h"
#include "constants.h"
#include <thread>
using namespace std;
int main ()
{
cout << "BBN X6-1000 Test Executable" << endl;
set_malibu_threading_enable(false);
int numDevices;
numDevices = get_numDevices();
cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "") << " found" << endl;
if (numDevices < 1)
return 0;
char s[] = "stdout";
set_log(s);
cout << "Attempting to initialize libaps" << endl;
init();
char serialBuffer[100];
for (int cnt; cnt < numDevices; cnt++) {
get_deviceSerial(cnt, serialBuffer);
cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
}
int rc;
rc = connect_by_ID(0);
cout << "connect_by_ID(0) returned " << rc << endl;
cout << "current logic temperature = " << get_logic_temperature(0) << endl;
cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;
cout << "setting trigger source = EXTERNAL" << endl;
set_trigger_source(0, EXTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "setting trigger source = INTERNAL" << endl;
set_trigger_source(0, INTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
cout << "set channel(0) enabled = 1" << endl;
set_channel_enabled(0,0,true);
cout << "enable ramp output" << endl;
enable_test_generator(0,0,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "enable sine wave output" << endl;
disable_test_generator(0);
enable_test_generator(0,1,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "disabling channel" << endl;
disable_test_generator(0);
set_channel_enabled(0,0,false);
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
rc = disconnect_by_ID(0);
cout << "disconnect_by_ID(0) returned " << rc << endl;
return 0;
}<commit_msg>First output through X6_1000 class<commit_after>#include <iostream>
#include "libaps.h"
#include "constants.h"
#include <thread>
using namespace std;
int main ()
{
cout << "BBN X6-1000 Test Executable" << endl;
set_malibu_threading_enable(false);
set_logging_level(5);
int numDevices;
numDevices = get_numDevices();
cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "") << " found" << endl;
if (numDevices < 1)
return 0;
char s[] = "stdout";
set_log(s);
cout << "Attempting to initialize libaps" << endl;
init();
char serialBuffer[100];
for (int cnt; cnt < numDevices; cnt++) {
get_deviceSerial(cnt, serialBuffer);
cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
}
int rc;
rc = connect_by_ID(0);
cout << "connect_by_ID(0) returned " << rc << endl;
cout << "current logic temperature = " << get_logic_temperature(0) << endl;
cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;
cout << "setting trigger source = EXTERNAL" << endl;
set_trigger_source(0, EXTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "setting trigger source = INTERNAL" << endl;
set_trigger_source(0, INTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
cout << "set channel(0) enabled = 1" << endl;
set_channel_enabled(0,0,true);
cout << "enable ramp output" << endl;
enable_test_generator(0,0,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "enable sine wave output" << endl;
disable_test_generator(0);
enable_test_generator(0,1,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "disabling channel" << endl;
disable_test_generator(0);
set_channel_enabled(0,0,false);
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
rc = disconnect_by_ID(0);
cout << "disconnect_by_ID(0) returned " << rc << endl;
return 0;
}<|endoftext|> |
<commit_before>#pragma once
#include "kl/binary_rw.hpp"
#include <vector>
namespace kl {
template <typename T>
kl::binary_reader& operator>>(kl::binary_reader& r, std::vector<T>& vec)
{
const auto size = r.read<std::uint32_t>();
vec.clear();
vec.reserve(size);
for (std::uint32_t i = 0; i < size; ++i)
{
vec.push_back(r.read<T>());
if (r.err())
{
vec.clear();
break;
}
}
return r;
}
} // namespace kl
<commit_msg>specialize operator>> for vector<T> of trivial type T<commit_after>#pragma once
#include "kl/binary_rw.hpp"
#include "kl/type_traits.hpp"
#include <vector>
namespace kl {
namespace detail {
// Specialized operator>> for vector<T> of trivial type T
template <typename T>
void decode_vector(kl::binary_reader& r, std::vector<T>& vec,
std::true_type /*is_trivial*/)
{
const auto size = r.read<std::uint32_t>();
vec.clear();
if (size)
{
auto span = r.view(size * sizeof(T));
if (r.err())
return;
vec.resize(size);
// Use .data() so we get a pointer and memmove fast path
std::copy_n(span.data(), size, vec.begin());
}
}
template <typename T>
void decode_vector(kl::binary_reader& r, std::vector<T>& vec,
std::false_type /*is_trivial*/)
{
const auto size = r.read<std::uint32_t>();
vec.clear();
vec.reserve(size);
for (std::uint32_t i = 0; i < size; ++i)
{
vec.push_back(r.read<T>());
if (r.err())
{
vec.clear();
break;
}
}
}
} // namespace detail
template <typename T>
kl::binary_reader& operator>>(kl::binary_reader& r, std::vector<T>& vec)
{
detail::decode_vector(r, vec,
kl::bool_constant<std::is_trivial<T>::value>{});
return r;
}
} // namespace kl
<|endoftext|> |
<commit_before>#include "Dictionary.h"
#include <string>
#include <vector>
#include <map>
#include "NounDefinition.h"
#include "AdjunctDefinition.h"
#include "ModifierDefinition.h"
#include "Grammar.h"
#ifdef DEBUG
#include "../util/Sysout.h"
#endif // DEBUG
// =====
// Nouns
// =====
// Vector
std::map<gmr::NounId, NounDefinition*> Dictionary::registeredNouns;
std::map<std::string, gmr::NounId> Dictionary::nounIdBySingularForm;
std::map<std::string, gmr::NounId> Dictionary::nounIdByPluralForm;
//
gmr::NounId Dictionary::erroneousNounId;
// Add
void Dictionary::addNoun(gmr::NounId nounId, NounDefinition* newNoun)
{
#ifdef DEBUG
std::map<gmr::NounId, NounDefinition*>::iterator focus = registeredNouns.find(nounId);
if(focus != registeredNouns.end())
{
Sysout::print("[Warning] You are trying to add two nouns with the same id! ");
Sysout::println(Sysout::toString(nounId));
}
#endif // DEBUG
registeredNouns.insert(std::pair<gmr::NounId, NounDefinition*>(nounId, newNoun));
nounIdBySingularForm.insert(std::pair<std::string, gmr::NounId>(newNoun->getSingularForm(), nounId));
nounIdByPluralForm.insert(std::pair<std::string, gmr::NounId>(newNoun->getPluralForm(), nounId));
}
// Get
NounDefinition* Dictionary::getNoun(gmr::NounId nounId)
{
std::map<gmr::NounId, NounDefinition*>::iterator focus = registeredNouns.find(nounId);
if(focus == registeredNouns.end())
{
return registeredNouns.find(erroneousModifierId)->second;
}
return focus->second;
}
// Get Id
gmr::NounId Dictionary::getNounIdBySingular(std::string singularNounForm)
{
std::map<std::string, gmr::NounId>::iterator focus = nounIdBySingularForm.find(singularNounForm);
if(focus == nounIdBySingularForm.end())
{
return erroneousNounId;
}
return focus->second;
}
gmr::NounId Dictionary::getNounIdByPlural(std::string pluralNounForm)
{
std::map<std::string, gmr::NounId>::iterator focus = nounIdByPluralForm.find(pluralNounForm);
if(focus == nounIdByPluralForm.end())
{
return erroneousNounId;
}
return focus->second;
}
// Add
void Dictionary::addNounAsErroneous(gmr::NounId nounId, NounDefinition* newNoun)
{
registeredNouns.insert(std::pair<gmr::NounId, NounDefinition*>(nounId, newNoun));
erroneousNounId = nounId;
}
gmr::NounId Dictionary::getErroneousNounId()
{
return erroneousNounId;
}
// ========
// Adjuncts
// ========
// Vector
std::vector<AdjunctDefinition*> Dictionary::registeredAdjuncts;
//
gmr::AdjunctId Dictionary::erroneousAdjunctId;
// Add
gmr::AdjunctId Dictionary::addAdjunct(AdjunctDefinition* newAdjunct)
{
registeredAdjuncts.push_back(newAdjunct);
return registeredAdjuncts.size() - 1;
}
// Add
gmr::AdjunctId Dictionary::addAdjunctAsErroneous(AdjunctDefinition* newAdjunct)
{
registeredAdjuncts.push_back(newAdjunct);
erroneousAdjunctId = registeredAdjuncts.size() - 1;
return registeredAdjuncts.size() - 1;
}
// Get
AdjunctDefinition* Dictionary::getAdjunct(gmr::AdjunctId adjunctId)
{
return registeredAdjuncts.at(adjunctId);
}
gmr::AdjunctId Dictionary::getErroneousAdjunctId()
{
return erroneousAdjunctId;
}
// =========
// Modifiers
// =========
// Maps
std::map<gmr::ModifierId, ModifierDefinition*> Dictionary::registeredModifiers;
std::map<std::string, gmr::ModifierId> Dictionary::modifierIdByForm;
//
gmr::ModifierId Dictionary::erroneousModifierId;
// Add
void Dictionary::addModifier(gmr::ModifierId modifierId, ModifierDefinition* newModifier)
{
#ifdef DEBUG
std::map<gmr::ModifierId, ModifierDefinition*>::iterator focus = registeredModifiers.find(modifierIdId);
if(focus != registeredModifiers.end())
{
Sysout::print("[Warning] You are trying to add two modifiers with the same id! ");
Sysout::println(Sysout::toString(modifierId));
}
#endif // DEBUG
registeredModifiers.insert(std::pair<gmr::ModifierId, ModifierDefinition*>(modifierId, newModifier));
modifierIdByForm.insert(std::pair<std::string, gmr::ModifierId>(newModifier->getForm(), modifierId));
}
// Get
ModifierDefinition* Dictionary::getModifier(gmr::ModifierId modifierId)
{
std::map<gmr::ModifierId, ModifierDefinition*>::iterator focus = registeredModifiers.find(modifierId);
if(focus == registeredModifiers.end())
{
return registeredModifiers.find(erroneousModifierId)->second;
}
return focus->second;
}
// Get Id
gmr::ModifierId Dictionary::getModifierId(std::string modifierForm)
{
std::map<std::string, gmr::ModifierId>::iterator focus = modifierIdByForm.find(modifierForm);
if(focus == modifierIdByForm.end())
{
return erroneousModifierId;
}
return focus->second;
}
// Add Erroneous
void Dictionary::addModifierAsErroneous(gmr::ModifierId modifierId, ModifierDefinition* newModifier)
{
registeredModifiers.insert(std::pair<gmr::ModifierId, ModifierDefinition*>(modifierId, newModifier));
erroneousModifierId = modifierId;
}
// Get Erroneous
gmr::ModifierId Dictionary::getErroneousModifierId()
{
return erroneousModifierId;
}
// ========
// Articles
// ========
// I'm different!
// Vector
std::map<std::string, gmr::ArticleProperties> Dictionary::registeredArticles;
// Add by name
void Dictionary::addArticle(std::string name, gmr::Definity mtype, gmr::Plurality mquantity)
{
gmr::ArticleProperties a;
a.type = mtype;
a.plurality = mquantity;
registeredArticles.insert(std::pair<std::string, gmr::ArticleProperties>(name, a));
}
// Get by name
gmr::ArticleProperties Dictionary::getArticle(std::string name)
{
std::map<std::string, gmr::ArticleProperties>::iterator focus = registeredArticles.find(name);
if(focus == registeredArticles.end())
{
// Returns a default value
gmr::ArticleProperties erroneous;
erroneous.type = gmr::undefinite;
erroneous.plurality = gmr::ambiguous;
return erroneous;
}
return focus->second;
}
std::string Dictionary::getArticleForm(gmr::AdjunctType definity, gmr::Plurality plurality)
{
return "put something better here";
}
<commit_msg>Fixed variable name<commit_after>#include "Dictionary.h"
#include <string>
#include <vector>
#include <map>
#include "NounDefinition.h"
#include "AdjunctDefinition.h"
#include "ModifierDefinition.h"
#include "Grammar.h"
#ifdef DEBUG
#include "../util/Sysout.h"
#endif // DEBUG
// =====
// Nouns
// =====
// Vector
std::map<gmr::NounId, NounDefinition*> Dictionary::registeredNouns;
std::map<std::string, gmr::NounId> Dictionary::nounIdBySingularForm;
std::map<std::string, gmr::NounId> Dictionary::nounIdByPluralForm;
//
gmr::NounId Dictionary::erroneousNounId;
// Add
void Dictionary::addNoun(gmr::NounId nounId, NounDefinition* newNoun)
{
#ifdef DEBUG
std::map<gmr::NounId, NounDefinition*>::iterator focus = registeredNouns.find(nounId);
if(focus != registeredNouns.end())
{
Sysout::print("[Warning] You are trying to add two nouns with the same id! ");
Sysout::println(Sysout::toString(nounId));
}
#endif // DEBUG
registeredNouns.insert(std::pair<gmr::NounId, NounDefinition*>(nounId, newNoun));
nounIdBySingularForm.insert(std::pair<std::string, gmr::NounId>(newNoun->getSingularForm(), nounId));
nounIdByPluralForm.insert(std::pair<std::string, gmr::NounId>(newNoun->getPluralForm(), nounId));
}
// Get
NounDefinition* Dictionary::getNoun(gmr::NounId nounId)
{
std::map<gmr::NounId, NounDefinition*>::iterator focus = registeredNouns.find(nounId);
if(focus == registeredNouns.end())
{
return registeredNouns.find(erroneousModifierId)->second;
}
return focus->second;
}
// Get Id
gmr::NounId Dictionary::getNounIdBySingular(std::string singularNounForm)
{
std::map<std::string, gmr::NounId>::iterator focus = nounIdBySingularForm.find(singularNounForm);
if(focus == nounIdBySingularForm.end())
{
return erroneousNounId;
}
return focus->second;
}
gmr::NounId Dictionary::getNounIdByPlural(std::string pluralNounForm)
{
std::map<std::string, gmr::NounId>::iterator focus = nounIdByPluralForm.find(pluralNounForm);
if(focus == nounIdByPluralForm.end())
{
return erroneousNounId;
}
return focus->second;
}
// Add
void Dictionary::addNounAsErroneous(gmr::NounId nounId, NounDefinition* newNoun)
{
registeredNouns.insert(std::pair<gmr::NounId, NounDefinition*>(nounId, newNoun));
erroneousNounId = nounId;
}
gmr::NounId Dictionary::getErroneousNounId()
{
return erroneousNounId;
}
// ========
// Adjuncts
// ========
// Vector
std::vector<AdjunctDefinition*> Dictionary::registeredAdjuncts;
//
gmr::AdjunctId Dictionary::erroneousAdjunctId;
// Add
gmr::AdjunctId Dictionary::addAdjunct(AdjunctDefinition* newAdjunct)
{
registeredAdjuncts.push_back(newAdjunct);
return registeredAdjuncts.size() - 1;
}
// Add
gmr::AdjunctId Dictionary::addAdjunctAsErroneous(AdjunctDefinition* newAdjunct)
{
registeredAdjuncts.push_back(newAdjunct);
erroneousAdjunctId = registeredAdjuncts.size() - 1;
return registeredAdjuncts.size() - 1;
}
// Get
AdjunctDefinition* Dictionary::getAdjunct(gmr::AdjunctId adjunctId)
{
return registeredAdjuncts.at(adjunctId);
}
gmr::AdjunctId Dictionary::getErroneousAdjunctId()
{
return erroneousAdjunctId;
}
// =========
// Modifiers
// =========
// Maps
std::map<gmr::ModifierId, ModifierDefinition*> Dictionary::registeredModifiers;
std::map<std::string, gmr::ModifierId> Dictionary::modifierIdByForm;
//
gmr::ModifierId Dictionary::erroneousModifierId;
// Add
void Dictionary::addModifier(gmr::ModifierId modifierId, ModifierDefinition* newModifier)
{
#ifdef DEBUG
std::map<gmr::ModifierId, ModifierDefinition*>::iterator focus = registeredModifiers.find(modifierId);
if(focus != registeredModifiers.end())
{
Sysout::print("[Warning] You are trying to add two modifiers with the same id! ");
Sysout::println(Sysout::toString(modifierId));
}
#endif // DEBUG
registeredModifiers.insert(std::pair<gmr::ModifierId, ModifierDefinition*>(modifierId, newModifier));
modifierIdByForm.insert(std::pair<std::string, gmr::ModifierId>(newModifier->getForm(), modifierId));
}
// Get
ModifierDefinition* Dictionary::getModifier(gmr::ModifierId modifierId)
{
std::map<gmr::ModifierId, ModifierDefinition*>::iterator focus = registeredModifiers.find(modifierId);
if(focus == registeredModifiers.end())
{
return registeredModifiers.find(erroneousModifierId)->second;
}
return focus->second;
}
// Get Id
gmr::ModifierId Dictionary::getModifierId(std::string modifierForm)
{
std::map<std::string, gmr::ModifierId>::iterator focus = modifierIdByForm.find(modifierForm);
if(focus == modifierIdByForm.end())
{
return erroneousModifierId;
}
return focus->second;
}
// Add Erroneous
void Dictionary::addModifierAsErroneous(gmr::ModifierId modifierId, ModifierDefinition* newModifier)
{
registeredModifiers.insert(std::pair<gmr::ModifierId, ModifierDefinition*>(modifierId, newModifier));
erroneousModifierId = modifierId;
}
// Get Erroneous
gmr::ModifierId Dictionary::getErroneousModifierId()
{
return erroneousModifierId;
}
// ========
// Articles
// ========
// I'm different!
// Vector
std::map<std::string, gmr::ArticleProperties> Dictionary::registeredArticles;
// Add by name
void Dictionary::addArticle(std::string name, gmr::Definity mtype, gmr::Plurality mquantity)
{
gmr::ArticleProperties a;
a.type = mtype;
a.plurality = mquantity;
registeredArticles.insert(std::pair<std::string, gmr::ArticleProperties>(name, a));
}
// Get by name
gmr::ArticleProperties Dictionary::getArticle(std::string name)
{
std::map<std::string, gmr::ArticleProperties>::iterator focus = registeredArticles.find(name);
if(focus == registeredArticles.end())
{
// Returns a default value
gmr::ArticleProperties erroneous;
erroneous.type = gmr::undefinite;
erroneous.plurality = gmr::ambiguous;
return erroneous;
}
return focus->second;
}
std::string Dictionary::getArticleForm(gmr::AdjunctType definity, gmr::Plurality plurality)
{
return "put something better here";
}
<|endoftext|> |
<commit_before>/********** tell emacs we use -*- c++ -*- style comments *******************
$Revision: 1.12 $ $Author: trey $ $Date: 2006-10-19 19:31:16 $
@file HDP.cc
@brief Implementation of Bonet and Geffner's HDP algorithm.
Copyright (c) 2006, Trey Smith. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
***************************************************************************/
/**********************************************************************
This is my implementation of the HDP algorithm, based on the paper
"Faster heuristic Search Algorithms for Planning with
Uncertainty and Full Feedback."
B. Bonet and H. Geffner. In Proc. of IJCAI, 2003.
Inevitably they could not include all the details of the algorithm in
their paper, so it is possible that my implementation differs from
theirs in important ways. They have not signed off on this
implementation: use at your own risk. (And please inform me if you
find any errors!)
This code also implements my variant HDP+L algorithm [not yet
published] when the compile-time flag '-DUSE_HDP_LOWER_BOUND=1' is
set. In addition to the usual upper bound, HDP+L keeps a lower bound
and uses that to generate the output policy. Empirically, this
improves anytime performance when the upper and lower bounds have not
yet converged.
-Trey Smith, Feb. 2006
**********************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <stack>
#include "zmdpCommonDefs.h"
#include "zmdpCommonTime.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "HDP.h"
using namespace std;
using namespace sla;
using namespace MatrixUtils;
namespace zmdp {
HDP::HDP(void)
{}
void HDP::getNodeHandler(MDPNode& cn)
{
HDPExtraNodeData* searchData = new HDPExtraNodeData;
cn.searchData = searchData;
searchData->isSolved = cn.isTerminal;
searchData->idx = RT_IDX_PLUS_INFINITY;
}
void HDP::staticGetNodeHandler(MDPNode& s, void* handlerData)
{
HDP* x = (HDP *) handlerData;
x->getNodeHandler(s);
}
bool& HDP::getIsSolved(const MDPNode& cn)
{
return ((HDPExtraNodeData *) cn.searchData)->isSolved;
}
int& HDP::getLow(const MDPNode& cn)
{
return ((HDPExtraNodeData *) cn.searchData)->low;
}
int& HDP::getIdx(const MDPNode& cn)
{
return ((HDPExtraNodeData *) cn.searchData)->idx;
}
void HDP::cacheQ(MDPNode& cn)
{
double oldUBVal = cn.ubVal;
// bounds->update() changes both Q values and cn.ubVal
bounds->update(cn, NULL);
trackBackup(cn);
// keep the changes to Q but undo the change to cn.ubVal
cn.ubVal = oldUBVal;
}
// assumes correct Q values are already cached (using cacheQ)
double HDP::residual(MDPNode& cn)
{
int maxUBAction = bounds->getMaxUBAction(cn);
return fabs(cn.ubVal - cn.Q[maxUBAction].ubVal);
}
void HDP::updateInternal(MDPNode& cn)
{
cacheQ(cn);
int maxUBAction = bounds->getMaxUBAction(cn);
cn.ubVal = cn.Q[maxUBAction].ubVal;
}
bool HDP::trialRecurse(MDPNode& cn, int depth)
{
#if USE_DEBUG_PRINT
printf(" trialRecurse: depth=%d ubVal=%g\n",
depth, cn.ubVal);
printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str());
#endif
// base case
if (getIsSolved(cn)) {
#if USE_DEBUG_PRINT
printf(" trialRecurse: solved node (terminating)\n");
#endif
return false;
}
// check residual
cacheQ(cn);
int maxUBAction = bounds->getMaxUBAction(cn);
// FIX do not recalculate maxUBAction in residual()
if (residual(cn) > targetPrecision) {
cn.ubVal = cn.Q[maxUBAction].ubVal;
#if USE_DEBUG_PRINT
printf(" trialRecurse: big residual (terminating)\n");
#endif
return true;
}
// mark state as active
visited.push(&cn);
nodeStack.push(&cn);
getIdx(cn) = getLow(cn) = index;
index++;
// recursive call
bool flag = false;
MDPQEntry& Qa = cn.Q[maxUBAction];
//printf(" pre low=%d idx=%d\n", getLow(cn), getIdx(cn));
FOR (o, Qa.getNumOutcomes()) {
MDPEdge* e = Qa.outcomes[o];
if (NULL != e) {
MDPNode& sn = *e->nextState;
//printf(" a=%d o=%d sn=[%s] sn.idx=%d\n", maxUBAction, o, denseRep(sn.s).c_str(), getIdx(sn));
if (RT_IDX_PLUS_INFINITY == getIdx(sn)) {
if (trialRecurse(sn, depth+1)) {
flag = true;
}
getLow(cn) = std::min(getLow(cn), getLow(sn));
} else if (nodeStack.contains(&sn)) {
getLow(cn) = std::min(getLow(cn), getLow(sn));
}
}
}
//printf(" post low=%d idx=%d\n", getLow(cn), getIdx(cn));
// update if necessary
if (flag) {
bounds->update(cn, NULL);
trackBackup(cn);
return true;
}
// try to label
else if (getIdx(cn) == getLow(cn)) {
printf(" marking %d nodes solved\n", (int)nodeStack.size());
while (nodeStack.top() != &cn) {
MDPNode& sn = *nodeStack.pop();
getIsSolved(sn) = true;
}
nodeStack.pop();
getIsSolved(cn) = true;
}
return flag;
}
bool HDP::doTrial(MDPNode& cn)
{
if (getIsSolved(cn)) {
printf("-*- doTrial: root node is solved, terminating\n");
return true;
}
#if USE_DEBUG_PRINT
printf("-*- doTrial: trial %d\n", (numTrials+1));
#endif
index = 0;
trialRecurse(cn, 0);
// reset idx to +infinity for visited states
while (!visited.empty()) {
getIdx(*visited.top()) = RT_IDX_PLUS_INFINITY;
visited.pop();
}
nodeStack.clear();
RT_CLEAR_STD_STACK(visited);
numTrials++;
return false;
}
void HDP::derivedClassInit(void)
{
bounds->setGetNodeHandler(&HDP::staticGetNodeHandler, this);
}
}; // namespace zmdp
/***************************************************************************
* REVISION HISTORY:
* $Log: not supported by cvs2svn $
* Revision 1.11 2006/06/14 00:22:40 trey
* fixed printf format warning
*
* Revision 1.10 2006/05/20 03:50:54 trey
* fixed printf format to avoid warning
*
* Revision 1.9 2006/04/28 17:57:41 trey
* changed to use apache license
*
* Revision 1.8 2006/04/07 19:41:30 trey
* removed initLowerBound, initUpperBound arguments to constructor
*
* Revision 1.7 2006/04/06 04:14:50 trey
* changed how bounds are initialized
*
* Revision 1.6 2006/04/04 17:23:58 trey
* modified to use IncrementalBounds methods
*
* Revision 1.5 2006/03/17 20:06:13 trey
* fixed compile warning
*
* Revision 1.4 2006/02/27 20:12:36 trey
* cleaned up meta-information in header
*
* Revision 1.3 2006/02/20 00:04:49 trey
* added optional lower bound use
*
* Revision 1.2 2006/02/19 18:33:36 trey
* targetPrecision now stared as a field rather than passed around recursively
*
* Revision 1.1 2006/02/17 18:20:55 trey
* initial check-in
*
*
***************************************************************************/
<commit_msg>removed obsolete comment<commit_after>/********** tell emacs we use -*- c++ -*- style comments *******************
$Revision: 1.13 $ $Author: trey $ $Date: 2006-10-20 04:56:35 $
@file HDP.cc
@brief Implementation of Bonet and Geffner's HDP algorithm.
Copyright (c) 2006, Trey Smith. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
***************************************************************************/
/**********************************************************************
This is my implementation of the HDP algorithm, based on the paper
"Faster heuristic Search Algorithms for Planning with
Uncertainty and Full Feedback."
B. Bonet and H. Geffner. In Proc. of IJCAI, 2003.
Inevitably they could not include all the details of the algorithm in
their paper, so it is possible that my implementation differs from
theirs in important ways. They have not signed off on this
implementation: use at your own risk. (And please inform me if you
find any errors!)
-Trey Smith, Feb. 2006
**********************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <stack>
#include "zmdpCommonDefs.h"
#include "zmdpCommonTime.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "HDP.h"
using namespace std;
using namespace sla;
using namespace MatrixUtils;
namespace zmdp {
HDP::HDP(void)
{}
void HDP::getNodeHandler(MDPNode& cn)
{
HDPExtraNodeData* searchData = new HDPExtraNodeData;
cn.searchData = searchData;
searchData->isSolved = cn.isTerminal;
searchData->idx = RT_IDX_PLUS_INFINITY;
}
void HDP::staticGetNodeHandler(MDPNode& s, void* handlerData)
{
HDP* x = (HDP *) handlerData;
x->getNodeHandler(s);
}
bool& HDP::getIsSolved(const MDPNode& cn)
{
return ((HDPExtraNodeData *) cn.searchData)->isSolved;
}
int& HDP::getLow(const MDPNode& cn)
{
return ((HDPExtraNodeData *) cn.searchData)->low;
}
int& HDP::getIdx(const MDPNode& cn)
{
return ((HDPExtraNodeData *) cn.searchData)->idx;
}
void HDP::cacheQ(MDPNode& cn)
{
double oldUBVal = cn.ubVal;
// bounds->update() changes both Q values and cn.ubVal
bounds->update(cn, NULL);
trackBackup(cn);
// keep the changes to Q but undo the change to cn.ubVal
cn.ubVal = oldUBVal;
}
// assumes correct Q values are already cached (using cacheQ)
double HDP::residual(MDPNode& cn)
{
int maxUBAction = bounds->getMaxUBAction(cn);
return fabs(cn.ubVal - cn.Q[maxUBAction].ubVal);
}
void HDP::updateInternal(MDPNode& cn)
{
cacheQ(cn);
int maxUBAction = bounds->getMaxUBAction(cn);
cn.ubVal = cn.Q[maxUBAction].ubVal;
}
bool HDP::trialRecurse(MDPNode& cn, int depth)
{
#if USE_DEBUG_PRINT
printf(" trialRecurse: depth=%d ubVal=%g\n",
depth, cn.ubVal);
printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str());
#endif
// base case
if (getIsSolved(cn)) {
#if USE_DEBUG_PRINT
printf(" trialRecurse: solved node (terminating)\n");
#endif
return false;
}
// check residual
cacheQ(cn);
int maxUBAction = bounds->getMaxUBAction(cn);
// FIX do not recalculate maxUBAction in residual()
if (residual(cn) > targetPrecision) {
cn.ubVal = cn.Q[maxUBAction].ubVal;
#if USE_DEBUG_PRINT
printf(" trialRecurse: big residual (terminating)\n");
#endif
return true;
}
// mark state as active
visited.push(&cn);
nodeStack.push(&cn);
getIdx(cn) = getLow(cn) = index;
index++;
// recursive call
bool flag = false;
MDPQEntry& Qa = cn.Q[maxUBAction];
//printf(" pre low=%d idx=%d\n", getLow(cn), getIdx(cn));
FOR (o, Qa.getNumOutcomes()) {
MDPEdge* e = Qa.outcomes[o];
if (NULL != e) {
MDPNode& sn = *e->nextState;
//printf(" a=%d o=%d sn=[%s] sn.idx=%d\n", maxUBAction, o, denseRep(sn.s).c_str(), getIdx(sn));
if (RT_IDX_PLUS_INFINITY == getIdx(sn)) {
if (trialRecurse(sn, depth+1)) {
flag = true;
}
getLow(cn) = std::min(getLow(cn), getLow(sn));
} else if (nodeStack.contains(&sn)) {
getLow(cn) = std::min(getLow(cn), getLow(sn));
}
}
}
//printf(" post low=%d idx=%d\n", getLow(cn), getIdx(cn));
// update if necessary
if (flag) {
bounds->update(cn, NULL);
trackBackup(cn);
return true;
}
// try to label
else if (getIdx(cn) == getLow(cn)) {
printf(" marking %d nodes solved\n", (int)nodeStack.size());
while (nodeStack.top() != &cn) {
MDPNode& sn = *nodeStack.pop();
getIsSolved(sn) = true;
}
nodeStack.pop();
getIsSolved(cn) = true;
}
return flag;
}
bool HDP::doTrial(MDPNode& cn)
{
if (getIsSolved(cn)) {
printf("-*- doTrial: root node is solved, terminating\n");
return true;
}
#if USE_DEBUG_PRINT
printf("-*- doTrial: trial %d\n", (numTrials+1));
#endif
index = 0;
trialRecurse(cn, 0);
// reset idx to +infinity for visited states
while (!visited.empty()) {
getIdx(*visited.top()) = RT_IDX_PLUS_INFINITY;
visited.pop();
}
nodeStack.clear();
RT_CLEAR_STD_STACK(visited);
numTrials++;
return false;
}
void HDP::derivedClassInit(void)
{
bounds->setGetNodeHandler(&HDP::staticGetNodeHandler, this);
}
}; // namespace zmdp
/***************************************************************************
* REVISION HISTORY:
* $Log: not supported by cvs2svn $
* Revision 1.12 2006/10/19 19:31:16 trey
* added support for backup logging
*
* Revision 1.11 2006/06/14 00:22:40 trey
* fixed printf format warning
*
* Revision 1.10 2006/05/20 03:50:54 trey
* fixed printf format to avoid warning
*
* Revision 1.9 2006/04/28 17:57:41 trey
* changed to use apache license
*
* Revision 1.8 2006/04/07 19:41:30 trey
* removed initLowerBound, initUpperBound arguments to constructor
*
* Revision 1.7 2006/04/06 04:14:50 trey
* changed how bounds are initialized
*
* Revision 1.6 2006/04/04 17:23:58 trey
* modified to use IncrementalBounds methods
*
* Revision 1.5 2006/03/17 20:06:13 trey
* fixed compile warning
*
* Revision 1.4 2006/02/27 20:12:36 trey
* cleaned up meta-information in header
*
* Revision 1.3 2006/02/20 00:04:49 trey
* added optional lower bound use
*
* Revision 1.2 2006/02/19 18:33:36 trey
* targetPrecision now stared as a field rather than passed around recursively
*
* Revision 1.1 2006/02/17 18:20:55 trey
* initial check-in
*
*
***************************************************************************/
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "stan/prob/distributions_multinomial.hpp"
#include <Eigen/Dense>
using Eigen::Matrix;
using Eigen::Dynamic;
TEST(ProbDistributions,Multinomial) {
std::vector<int> ns;
ns.push_back(1);
ns.push_back(2);
ns.push_back(3);
Matrix<double,Dynamic,1> theta(3,1);
theta << 0.2, 0.3, 0.5;
EXPECT_FLOAT_EQ(-2.002481, stan::prob::multinomial_log(ns,theta));
}
TEST(ProbDistributions,MultinomialPropto) {
std::vector<int> ns;
ns.push_back(1);
ns.push_back(2);
ns.push_back(3);
Matrix<double,Dynamic,1> theta(3,1);
theta << 0.2, 0.3, 0.5;
EXPECT_FLOAT_EQ(0.0, stan::prob::multinomial_log<true>(ns,theta));
}
<commit_msg>cleanup<commit_after>#include <gtest/gtest.h>
#include "stan/prob/distributions_multinomial.hpp"
using Eigen::Matrix;
using Eigen::Dynamic;
TEST(ProbDistributions,Multinomial) {
std::vector<int> ns;
ns.push_back(1);
ns.push_back(2);
ns.push_back(3);
Matrix<double,Dynamic,1> theta(3,1);
theta << 0.2, 0.3, 0.5;
EXPECT_FLOAT_EQ(-2.002481, stan::prob::multinomial_log(ns,theta));
}
TEST(ProbDistributions,MultinomialPropto) {
std::vector<int> ns;
ns.push_back(1);
ns.push_back(2);
ns.push_back(3);
Matrix<double,Dynamic,1> theta(3,1);
theta << 0.2, 0.3, 0.5;
EXPECT_FLOAT_EQ(0.0, stan::prob::multinomial_log<true>(ns,theta));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: cachedata.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:19:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_CACHEDATA_HXX
#define CONFIGMGR_CACHEDATA_HXX
#ifndef CONFIGMGR_CACHELINE_HXX
#include "cacheline.hxx"
#endif
#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
namespace configmgr
{
////////////////////////////////////////////////////////////////////////////////
using ::rtl::OUString;
namespace backend
{
struct NodeInstance;
struct TemplateInstance;
struct UpdateInstance;
struct ConstUpdateInstance;
}
////////////////////////////////////////////////////////////////////////////////
/** A collection of CacheLines
*/
class CacheData
{
public:
typedef CacheLine Module;
typedef CacheLineRef ModuleRef;
typedef CacheLine::Path Path;
typedef CacheLine::Name ModuleName;
public:
CacheData(memory::HeapManager & _rHeapManager);
~CacheData();
/// retrieve the module tree name for the given path
static ModuleName extractModuleName(Path const& _aPath);
/// check if the given module exists already (and is not empty)
bool hasModule(ModuleName const & _aModule) const;
/// checks if the given module exists and has defaults available
bool hasModuleDefaults(memory::Accessor const & _aAccessor, ModuleName const & _aModule) const;
/// creates a new data segment reference for the given path if exists
memory::Segment * attachDataSegment(memory::SegmentAddress const & _aLocation, ModuleName const & _aModule);
/// gets a data segment reference for the given path if it exists
memory::Segment * getDataSegment(ModuleName const & _aModule);
/// gets a data segment address for the given module if it exists
memory::SegmentAddress getDataSegmentAddress(ModuleName const & _aModule) const;
/// checks whether a certain node exists in the tree
bool hasNode(memory::Accessor const & _aAccessor, Path const & _aLocation) const;
/// retrieve the given node without changing its ref count
data::NodeAddress getNode(memory::Accessor const & _aAccessor, Path const & _rPath);
/// retrieve the given template tree without changing its ref count
data::TreeAddress getTemplateTree(memory::Accessor const & _aAccessor, Path const & aTemplateName ) const;
/// retrieve the subtree at _aPath and clientAcquire() it
data::NodeAddress acquireNode(memory::Accessor const & _aAccessor, Path const & _aPath );
/// retrieve the subtree at _aPath and clientAcquire() it
data::TreeAddress acquireModule( ModuleName const & _aModule );
/// clientRelease() the tree at aComponentName, and return the resulting reference count
CacheLine::RefCount releaseModule( ModuleName const & _aModule, bool _bKeepDeadModule = false );
bool insertDefaults( memory::UpdateAccessor& _aAccessToken,
backend::NodeInstance const & _aDefaultInstance
) CFG_UNO_THROW_RTE();
/// merge the given changes into this tree - reflects old values to _anUpdate
void applyUpdate( memory::UpdateAccessor& _aUpdateToken,
backend::UpdateInstance & _anUpdate) CFG_UNO_THROW_RTE( );
// low-level interface for cache management
typedef std::map<ModuleName, ModuleRef> ModuleList;
ModuleList& accessModuleList() { return m_aModules; }
memory::HeapManager & getHeapManager() const { return m_rHeapManager; }
protected:
virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
data::TreeAddress internalGetPartialTree(memory::Accessor const & _aAccessor, Path const & _aPath ) const;
data::NodeAddress internalGetNode(memory::Accessor const & _aAccessor, const Path& _rPath) const;
ModuleRef internalAttachModule(const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
void internalAddModule(ModuleName const & _aName, ModuleRef const & _aModule);
ModuleRef internalGetModule(const ModuleName& _aName) const;
ModuleRef internalGetModule(const Path& _aLocation) const;
memory::HeapManager & internalHeapManager() { return m_rHeapManager; }
private:
ModuleList m_aModules;
memory::HeapManager & m_rHeapManager;
};
////////////////////////////////////////////////////////////////////////////////
/** A collection of CacheLines for templates
*/
class TemplateCacheData : public CacheData
{
public:
TemplateCacheData(memory::HeapManager & _rHeapManager)
: CacheData(_rHeapManager)
{
}
/// gets a data segment reference for the given path - creates if necessary
memory::Segment * createDataSegment(ModuleName const & _aModule);
/** add the given template tree at the given location,
return the tree that is now pertinent and clientAcquire() it once
*/
data::TreeAddress addTemplates( memory::UpdateAccessor& _aAccessToken,
backend::ComponentData const & _aComponentInstance
) CFG_UNO_THROW_RTE();
private:
virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
CacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE( );
};
//-----------------------------------------------------------------------------
/** A collection of CacheLines
*/
class ExtendedCacheData : public CacheData
{
public:
ExtendedCacheData(memory::HeapManager & _rHeapManager)
: CacheData(_rHeapManager)
{
}
/// gets a data segment reference for the given path - creates if necessary
memory::Segment * createDataSegment(ModuleName const & _aModule);
/** add the given subtree at the given location,
return the tree that is now pertinent and clientAcquire() it once
*/
data::TreeAddress addComponentData( memory::UpdateAccessor& _aAccessToken,
backend::ComponentInstance const & _aComponentInstance,
bool _bWithDefaults
) CFG_UNO_THROW_RTE();
typedef std::vector< ModuleName > PendingModuleList;
/// find the modules having pending changes
bool hasPending(ModuleName const & _aModule);
/// find the modules having pending changes
void findPendingModules( PendingModuleList & _rPendingList );
/// add or merge the given subtreechange at the given location
void addPending(backend::ConstUpdateInstance const & _anUpdate) CFG_UNO_THROW_RTE( );
/// remove and return pending changes for the given component
std::auto_ptr<SubtreeChange> releasePending(ModuleName const & _aModule) CFG_UNO_THROW_RTE( );
private:
virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
ExtendedCacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE( );
ExtendedCacheLineRef implExtended(ModuleRef const & _aSimpleRef) const;
};
//-----------------------------------------------------------------------------
} // namespace configmgr
#endif
<commit_msg>INTEGRATION: CWS cfgcleanup (1.5.70); FILE MERGED 2004/02/09 15:30:32 jb 1.5.70.1: #i25025# Eliminate warnings from gcc<commit_after>/*************************************************************************
*
* $RCSfile: cachedata.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2004-03-23 10:30:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_CACHEDATA_HXX
#define CONFIGMGR_CACHEDATA_HXX
#ifndef CONFIGMGR_CACHELINE_HXX
#include "cacheline.hxx"
#endif
#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
namespace configmgr
{
////////////////////////////////////////////////////////////////////////////////
using ::rtl::OUString;
namespace backend
{
struct NodeInstance;
struct TemplateInstance;
struct UpdateInstance;
struct ConstUpdateInstance;
}
////////////////////////////////////////////////////////////////////////////////
/** A collection of CacheLines
*/
class CacheData
{
public:
typedef CacheLine Module;
typedef CacheLineRef ModuleRef;
typedef CacheLine::Path Path;
typedef CacheLine::Name ModuleName;
public:
CacheData(memory::HeapManager & _rHeapManager);
virtual ~CacheData();
/// retrieve the module tree name for the given path
static ModuleName extractModuleName(Path const& _aPath);
/// check if the given module exists already (and is not empty)
bool hasModule(ModuleName const & _aModule) const;
/// checks if the given module exists and has defaults available
bool hasModuleDefaults(memory::Accessor const & _aAccessor, ModuleName const & _aModule) const;
/// creates a new data segment reference for the given path if exists
memory::Segment * attachDataSegment(memory::SegmentAddress const & _aLocation, ModuleName const & _aModule);
/// gets a data segment reference for the given path if it exists
memory::Segment * getDataSegment(ModuleName const & _aModule);
/// gets a data segment address for the given module if it exists
memory::SegmentAddress getDataSegmentAddress(ModuleName const & _aModule) const;
/// checks whether a certain node exists in the tree
bool hasNode(memory::Accessor const & _aAccessor, Path const & _aLocation) const;
/// retrieve the given node without changing its ref count
data::NodeAddress getNode(memory::Accessor const & _aAccessor, Path const & _rPath);
/// retrieve the given template tree without changing its ref count
data::TreeAddress getTemplateTree(memory::Accessor const & _aAccessor, Path const & aTemplateName ) const;
/// retrieve the subtree at _aPath and clientAcquire() it
data::NodeAddress acquireNode(memory::Accessor const & _aAccessor, Path const & _aPath );
/// retrieve the subtree at _aPath and clientAcquire() it
data::TreeAddress acquireModule( ModuleName const & _aModule );
/// clientRelease() the tree at aComponentName, and return the resulting reference count
CacheLine::RefCount releaseModule( ModuleName const & _aModule, bool _bKeepDeadModule = false );
bool insertDefaults( memory::UpdateAccessor& _aAccessToken,
backend::NodeInstance const & _aDefaultInstance
) CFG_UNO_THROW_RTE();
/// merge the given changes into this tree - reflects old values to _anUpdate
void applyUpdate( memory::UpdateAccessor& _aUpdateToken,
backend::UpdateInstance & _anUpdate) CFG_UNO_THROW_RTE( );
// low-level interface for cache management
typedef std::map<ModuleName, ModuleRef> ModuleList;
ModuleList& accessModuleList() { return m_aModules; }
memory::HeapManager & getHeapManager() const { return m_rHeapManager; }
protected:
virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
data::TreeAddress internalGetPartialTree(memory::Accessor const & _aAccessor, Path const & _aPath ) const;
data::NodeAddress internalGetNode(memory::Accessor const & _aAccessor, const Path& _rPath) const;
ModuleRef internalAttachModule(const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
void internalAddModule(ModuleName const & _aName, ModuleRef const & _aModule);
ModuleRef internalGetModule(const ModuleName& _aName) const;
ModuleRef internalGetModule(const Path& _aLocation) const;
memory::HeapManager & internalHeapManager() { return m_rHeapManager; }
private:
ModuleList m_aModules;
memory::HeapManager & m_rHeapManager;
};
////////////////////////////////////////////////////////////////////////////////
/** A collection of CacheLines for templates
*/
class TemplateCacheData : public CacheData
{
public:
TemplateCacheData(memory::HeapManager & _rHeapManager)
: CacheData(_rHeapManager)
{
}
/// gets a data segment reference for the given path - creates if necessary
memory::Segment * createDataSegment(ModuleName const & _aModule);
/** add the given template tree at the given location,
return the tree that is now pertinent and clientAcquire() it once
*/
data::TreeAddress addTemplates( memory::UpdateAccessor& _aAccessToken,
backend::ComponentData const & _aComponentInstance
) CFG_UNO_THROW_RTE();
private:
virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
CacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE( );
};
//-----------------------------------------------------------------------------
/** A collection of CacheLines
*/
class ExtendedCacheData : public CacheData
{
public:
ExtendedCacheData(memory::HeapManager & _rHeapManager)
: CacheData(_rHeapManager)
{
}
/// gets a data segment reference for the given path - creates if necessary
memory::Segment * createDataSegment(ModuleName const & _aModule);
/** add the given subtree at the given location,
return the tree that is now pertinent and clientAcquire() it once
*/
data::TreeAddress addComponentData( memory::UpdateAccessor& _aAccessToken,
backend::ComponentInstance const & _aComponentInstance,
bool _bWithDefaults
) CFG_UNO_THROW_RTE();
typedef std::vector< ModuleName > PendingModuleList;
/// find the modules having pending changes
bool hasPending(ModuleName const & _aModule);
/// find the modules having pending changes
void findPendingModules( PendingModuleList & _rPendingList );
/// add or merge the given subtreechange at the given location
void addPending(backend::ConstUpdateInstance const & _anUpdate) CFG_UNO_THROW_RTE( );
/// remove and return pending changes for the given component
std::auto_ptr<SubtreeChange> releasePending(ModuleName const & _aModule) CFG_UNO_THROW_RTE( );
private:
virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE( );
ExtendedCacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE( );
ExtendedCacheLineRef implExtended(ModuleRef const & _aSimpleRef) const;
};
//-----------------------------------------------------------------------------
} // namespace configmgr
#endif
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file MCLS_EpetraAdapater.hpp
* \author Stuart R. Slattery
* \brief Epetra Helpers.
*/
//---------------------------------------------------------------------------//
#ifndef MCLS_EPETRAHELPERS_HPP
#define MCLS_EPETRAHELPERS_HPP
#include <MCLS_DBC.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>
#include <Teuchos_as.hpp>
#include <Epetra_Map.h>
#include <Epetra_RowMatrix.h>
#include <Epetra_CrsMatrix.h>
#include <Epetra_Export.h>
#include <Epetra_RowMatrixTransposer.h>
#include <EpetraExt_MatrixMatrix.h>
//---------------------------------------------------------------------------//
/*!
* \class UndefinedEpetraHelpers
* \brief Class for undefined EpetraHelper functions.
*
* Will throw a compile-time error if these traits are not specialized.
*/
template<class Matrix>
struct UndefinedEpetraHelpers
{
static inline void notDefined()
{
return Matrix::this_type_is_missing_a_specialization();
}
};
namespace MCLS
{
//---------------------------------------------------------------------------//
/*!
* \class EpetraMatrixHelpers
* \brief Helper functions for Epetra implementations.
*/
template<class Matrix>
class EpetraMatrixHelpers
{
public:
//@{
//! Typedefs.
typedef Matrix matrix_type;
//@}
/*!
* \brief Get the on-process global matrix column indices that, as global
* row indices, are off-process.
*/
static Teuchos::Array<int> getOffProcColsAsRows( const Matrix& matrix )
{
UndefinedEpetraHelpers<Matrix>::notDefined();
return Teuchos::Array<int>(0);
}
/*!
* \brief Get a copy of the transpose of a matrix.
*/
static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
{
UndefinedEpetraHelpers<Matrix>::notDefined();
return Teuchos::null;
}
/*
* \brief Create a reference-counted pointer to a new matrix with a
* specified number of off-process nearest-neighbor global rows.
*/
static Teuchos::RCP<matrix_type> copyNearestNeighbors(
const matrix_type& matrix, const int& num_neighbors )
{
UndefinedEpetraHelpers<Matrix>::notDefined();
return Teuchos::null;
}
/*!
* \brief Matrix-Matrix multiply C = A*B
*/
static void multiply( const Teuchos::RCP<const matrix_type>& A,
const Teuchos::RCP<const matrix_type>& B,
const Teuchos::RCP<matrix_type>& C )
{ UndefinedEpetraHelpers<Matrix>::notDefined(); }
};
//---------------------------------------------------------------------------//
/*!
* \class EpetraMatrixHelpers
* \brief EpetraMatrixHelpers specialization for Epetra_RowMatrix.
*/
template<>
class EpetraMatrixHelpers<Epetra_RowMatrix>
{
public:
//@{
//! Typedefs.
typedef Epetra_RowMatrix matrix_type;
//@}
/*!
* \brief Get the on-process global matrix column indices that, as global
* row indices, are off-process.
*/
static Teuchos::Array<int> getOffProcColsAsRows( const matrix_type& matrix )
{
MCLS_REQUIRE( matrix.Filled() );
const Epetra_Map& row_map = matrix.RowMatrixRowMap();
const Epetra_Map& col_map = matrix.RowMatrixColMap();
Teuchos::ArrayView<const int> global_cols( col_map.MyGlobalElements(),
col_map.NumMyElements() );
Teuchos::Array<int> off_proc_cols(0);
Teuchos::ArrayView<const int>::const_iterator global_col_it;
for ( global_col_it = global_cols.begin();
global_col_it != global_cols.end();
++global_col_it )
{
if ( !row_map.MyGID( *global_col_it ) )
{
off_proc_cols.push_back( *global_col_it );
}
}
return off_proc_cols;
}
/*!
* \brief Get a copy of the transpose of a matrix.
*/
static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
{
Epetra_RowMatrixTransposer transposer( const_cast<matrix_type*>(&matrix) );
Epetra_CrsMatrix* transpose_matrix;
int error = transposer.CreateTranspose( false, transpose_matrix );
MCLS_CHECK( 0 == error );
MCLS_ENSURE( transpose_matrix->Filled() );
return Teuchos::RCP<matrix_type>( transpose_matrix );
}
/*
* \brief Create a reference-counted pointer to a new matrix with a
* specified number of off-process nearest-neighbor global rows.
*/
static Teuchos::RCP<matrix_type> copyNearestNeighbors(
const matrix_type& matrix, const int& num_neighbors )
{
MCLS_REQUIRE( num_neighbors >= 0 );
// Setup for neighbor construction.
Teuchos::RCP<const Epetra_Map> empty_map = Teuchos::rcp(
new Epetra_Map( 0, 0, matrix.Comm() ) );
Teuchos::RCP<Epetra_CrsMatrix> neighbor_matrix =
Teuchos::rcp( new Epetra_CrsMatrix( Copy, *empty_map, 0 ) );
int error = neighbor_matrix->FillComplete();
MCLS_CHECK( 0 == error );
Teuchos::ArrayView<const int> global_rows;
Teuchos::ArrayView<const int>::const_iterator global_rows_it;
Teuchos::Array<int>::iterator ghost_global_bound;
// Get the initial off proc columns.
Teuchos::Array<int> ghost_global_rows = getOffProcColsAsRows( matrix );
// Build the neighbors by traversing the graph.
for ( int i = 0; i < num_neighbors; ++i )
{
// Get rid of the global rows that belong to the original
// matrix. We don't need to store these, just the neighbors.
global_rows = Teuchos::ArrayView<const int>(
matrix.RowMatrixRowMap().MyGlobalElements(),
matrix.RowMatrixRowMap().NumMyElements() );
for ( global_rows_it = global_rows.begin();
global_rows_it != global_rows.end();
++global_rows_it )
{
ghost_global_bound = std::remove( ghost_global_rows.begin(),
ghost_global_rows.end(),
*global_rows_it );
ghost_global_rows.resize( std::distance(ghost_global_rows.begin(),
ghost_global_bound) );
}
// Get the current set of global rows in the neighbor matrix.
global_rows = Teuchos::ArrayView<const int>(
neighbor_matrix->RowMatrixRowMap().MyGlobalElements(),
neighbor_matrix->RowMatrixRowMap().NumMyElements() );
// Append the on proc neighbor columns to the off proc columns.
for ( global_rows_it = global_rows.begin();
global_rows_it != global_rows.end();
++global_rows_it )
{
ghost_global_rows.push_back( *global_rows_it );
}
// Make a new map of the combined global rows and off proc columns.
Teuchos::RCP<const Epetra_Map> ghost_map = Teuchos::rcp(
new Epetra_Map( -1,
Teuchos::as<int>(ghost_global_rows.size()),
ghost_global_rows.getRawPtr(),
0,
neighbor_matrix->Comm() ) );
// Export the neighbor matrix with the new neighbor.
Epetra_Export ghost_exporter( matrix.RowMatrixRowMap(), *ghost_map );
neighbor_matrix = Teuchos::rcp(
new Epetra_CrsMatrix( Copy, *ghost_map, 0 ) );
neighbor_matrix->Export( matrix, ghost_exporter, Insert );
error = neighbor_matrix->FillComplete();
MCLS_CHECK( 0 == error );
// Get the next rows in the graph.
ghost_global_rows = getOffProcColsAsRows( *neighbor_matrix );
}
MCLS_ENSURE( !neighbor_matrix.is_null() );
MCLS_ENSURE( neighbor_matrix->Filled() );
return neighbor_matrix;
}
/*!
* \brief Matrix-Matrix multiply C = A*B
*/
static void multiply( const Teuchos::RCP<const matrix_type>& A,
const Teuchos::RCP<const matrix_type>& B,
const Teuchos::RCP<matrix_type>& C )
{
Teuchos::RCP<const Epetra_CrsMatrix> A_crs =
Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( A );
Teuchos::RCP<const Epetra_CrsMatrix> B_crs =
Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( B );
Teuchos::RCP<Epetra_CrsMatrix> C_crs =
Teuchos::rcp_dynamic_cast<Epetra_CrsMatrix>( C );
if ( Teuchos::is_null(A_crs) )
{
A_crs = createCrsMatrix( A );
}
if ( Teuchos::is_null(B_crs) )
{
B_crs = createCrsMatrix( B );
}
if ( Teuchos::is_null(C_crs) )
{
C_crs = Teuchos::rcp(
new Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), 0) );
}
EpetraExt::MatrixMatrix::Multiply(
*A_crs, false, *B_crs, false, *C_crs );
}
/*!
* \brief Create a copy of a RowMatrix in a CrsMatrix.
*/
static Teuchos::RCP<Epetra_CrsMatrix>
createCrsMatrix( const Teuchos::RCP<const matrix_type>& A )
{
const Epetra_Map &row_map = A->RowMatrixRowMap();
const Epetra_Map &col_map = A->RowMatrixColMap();
Teuchos::RCP<Epetra_CrsMatrix> A_crs = Teuchos::rcp(
new Epetra_CrsMatrix( Copy, row_map, col_map, 0 ) );
int num_local_rows = row_map.NumMyElements();
Teuchos::Array<int> my_global_rows( num_local_rows );
row_map.MyGlobalElements( my_global_rows.getRawPtr() );
int num_local_cols = col_map.NumMyElements() ;
Teuchos::Array<int> my_global_cols( num_local_cols );
col_map.MyGlobalElements( my_global_cols.getRawPtr() );
int max_entries = A->MaxNumEntries();
int num_entries = 0;
Teuchos::Array<int> local_indices(max_entries);
Teuchos::Array<int> global_indices(max_entries);
Teuchos::Array<double> values(max_entries);
int error = 0;
for( int local_row = 0; local_row < num_local_rows; ++local_row )
{
error = A->ExtractMyRowCopy( local_row,
max_entries,
num_entries,
values.getRawPtr(),
local_indices.getRawPtr() );
MCLS_CHECK( 0 == error );
for (int j = 0 ; j < num_entries; ++j )
{
global_indices[j] = my_global_cols[ local_indices[j] ];
}
error = A_crs->InsertGlobalValues( my_global_rows[local_row],
num_entries,
values.getRawPtr(),
global_indices.getRawPtr() );
MCLS_CHECK( 0 == error );
}
error = A_crs->FillComplete();
MCLS_CHECK( 0 == error );
return A_crs;
}
};
//---------------------------------------------------------------------------//
} // end namespace MCLS
#endif // end MCLS_EPETRAHELPERS_HPP
//---------------------------------------------------------------------------//
// end MCLS_EpetraHelpers.hpp
//---------------------------------------------------------------------------//
<commit_msg>reverting transpose construction to contiguous storage for better performance<commit_after>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file MCLS_EpetraAdapater.hpp
* \author Stuart R. Slattery
* \brief Epetra Helpers.
*/
//---------------------------------------------------------------------------//
#ifndef MCLS_EPETRAHELPERS_HPP
#define MCLS_EPETRAHELPERS_HPP
#include <MCLS_DBC.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>
#include <Teuchos_as.hpp>
#include <Epetra_Map.h>
#include <Epetra_RowMatrix.h>
#include <Epetra_CrsMatrix.h>
#include <Epetra_Export.h>
#include <Epetra_RowMatrixTransposer.h>
#include <EpetraExt_MatrixMatrix.h>
//---------------------------------------------------------------------------//
/*!
* \class UndefinedEpetraHelpers
* \brief Class for undefined EpetraHelper functions.
*
* Will throw a compile-time error if these traits are not specialized.
*/
template<class Matrix>
struct UndefinedEpetraHelpers
{
static inline void notDefined()
{
return Matrix::this_type_is_missing_a_specialization();
}
};
namespace MCLS
{
//---------------------------------------------------------------------------//
/*!
* \class EpetraMatrixHelpers
* \brief Helper functions for Epetra implementations.
*/
template<class Matrix>
class EpetraMatrixHelpers
{
public:
//@{
//! Typedefs.
typedef Matrix matrix_type;
//@}
/*!
* \brief Get the on-process global matrix column indices that, as global
* row indices, are off-process.
*/
static Teuchos::Array<int> getOffProcColsAsRows( const Matrix& matrix )
{
UndefinedEpetraHelpers<Matrix>::notDefined();
return Teuchos::Array<int>(0);
}
/*!
* \brief Get a copy of the transpose of a matrix.
*/
static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
{
UndefinedEpetraHelpers<Matrix>::notDefined();
return Teuchos::null;
}
/*
* \brief Create a reference-counted pointer to a new matrix with a
* specified number of off-process nearest-neighbor global rows.
*/
static Teuchos::RCP<matrix_type> copyNearestNeighbors(
const matrix_type& matrix, const int& num_neighbors )
{
UndefinedEpetraHelpers<Matrix>::notDefined();
return Teuchos::null;
}
/*!
* \brief Matrix-Matrix multiply C = A*B
*/
static void multiply( const Teuchos::RCP<const matrix_type>& A,
const Teuchos::RCP<const matrix_type>& B,
const Teuchos::RCP<matrix_type>& C )
{ UndefinedEpetraHelpers<Matrix>::notDefined(); }
};
//---------------------------------------------------------------------------//
/*!
* \class EpetraMatrixHelpers
* \brief EpetraMatrixHelpers specialization for Epetra_RowMatrix.
*/
template<>
class EpetraMatrixHelpers<Epetra_RowMatrix>
{
public:
//@{
//! Typedefs.
typedef Epetra_RowMatrix matrix_type;
//@}
/*!
* \brief Get the on-process global matrix column indices that, as global
* row indices, are off-process.
*/
static Teuchos::Array<int> getOffProcColsAsRows( const matrix_type& matrix )
{
MCLS_REQUIRE( matrix.Filled() );
const Epetra_Map& row_map = matrix.RowMatrixRowMap();
const Epetra_Map& col_map = matrix.RowMatrixColMap();
Teuchos::ArrayView<const int> global_cols( col_map.MyGlobalElements(),
col_map.NumMyElements() );
Teuchos::Array<int> off_proc_cols(0);
Teuchos::ArrayView<const int>::const_iterator global_col_it;
for ( global_col_it = global_cols.begin();
global_col_it != global_cols.end();
++global_col_it )
{
if ( !row_map.MyGID( *global_col_it ) )
{
off_proc_cols.push_back( *global_col_it );
}
}
return off_proc_cols;
}
/*!
* \brief Get a copy of the transpose of a matrix.
*/
static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
{
Epetra_RowMatrixTransposer transposer( const_cast<matrix_type*>(&matrix) );
Epetra_CrsMatrix* transpose_matrix;
int error = transposer.CreateTranspose( true, transpose_matrix );
MCLS_CHECK( 0 == error );
MCLS_ENSURE( transpose_matrix->Filled() );
return Teuchos::RCP<matrix_type>( transpose_matrix );
}
/*
* \brief Create a reference-counted pointer to a new matrix with a
* specified number of off-process nearest-neighbor global rows.
*/
static Teuchos::RCP<matrix_type> copyNearestNeighbors(
const matrix_type& matrix, const int& num_neighbors )
{
MCLS_REQUIRE( num_neighbors >= 0 );
// Setup for neighbor construction.
Teuchos::RCP<const Epetra_Map> empty_map = Teuchos::rcp(
new Epetra_Map( 0, 0, matrix.Comm() ) );
Teuchos::RCP<Epetra_CrsMatrix> neighbor_matrix =
Teuchos::rcp( new Epetra_CrsMatrix( Copy, *empty_map, 0 ) );
int error = neighbor_matrix->FillComplete();
MCLS_CHECK( 0 == error );
Teuchos::ArrayView<const int> global_rows;
Teuchos::ArrayView<const int>::const_iterator global_rows_it;
Teuchos::Array<int>::iterator ghost_global_bound;
// Get the initial off proc columns.
Teuchos::Array<int> ghost_global_rows = getOffProcColsAsRows( matrix );
// Build the neighbors by traversing the graph.
for ( int i = 0; i < num_neighbors; ++i )
{
// Get rid of the global rows that belong to the original
// matrix. We don't need to store these, just the neighbors.
global_rows = Teuchos::ArrayView<const int>(
matrix.RowMatrixRowMap().MyGlobalElements(),
matrix.RowMatrixRowMap().NumMyElements() );
for ( global_rows_it = global_rows.begin();
global_rows_it != global_rows.end();
++global_rows_it )
{
ghost_global_bound = std::remove( ghost_global_rows.begin(),
ghost_global_rows.end(),
*global_rows_it );
ghost_global_rows.resize( std::distance(ghost_global_rows.begin(),
ghost_global_bound) );
}
// Get the current set of global rows in the neighbor matrix.
global_rows = Teuchos::ArrayView<const int>(
neighbor_matrix->RowMatrixRowMap().MyGlobalElements(),
neighbor_matrix->RowMatrixRowMap().NumMyElements() );
// Append the on proc neighbor columns to the off proc columns.
for ( global_rows_it = global_rows.begin();
global_rows_it != global_rows.end();
++global_rows_it )
{
ghost_global_rows.push_back( *global_rows_it );
}
// Make a new map of the combined global rows and off proc columns.
Teuchos::RCP<const Epetra_Map> ghost_map = Teuchos::rcp(
new Epetra_Map( -1,
Teuchos::as<int>(ghost_global_rows.size()),
ghost_global_rows.getRawPtr(),
0,
neighbor_matrix->Comm() ) );
// Export the neighbor matrix with the new neighbor.
Epetra_Export ghost_exporter( matrix.RowMatrixRowMap(), *ghost_map );
neighbor_matrix = Teuchos::rcp(
new Epetra_CrsMatrix( Copy, *ghost_map, 0 ) );
neighbor_matrix->Export( matrix, ghost_exporter, Insert );
error = neighbor_matrix->FillComplete();
MCLS_CHECK( 0 == error );
// Get the next rows in the graph.
ghost_global_rows = getOffProcColsAsRows( *neighbor_matrix );
}
MCLS_ENSURE( !neighbor_matrix.is_null() );
MCLS_ENSURE( neighbor_matrix->Filled() );
return neighbor_matrix;
}
/*!
* \brief Matrix-Matrix multiply C = A*B
*/
static void multiply( const Teuchos::RCP<const matrix_type>& A,
const Teuchos::RCP<const matrix_type>& B,
const Teuchos::RCP<matrix_type>& C )
{
Teuchos::RCP<const Epetra_CrsMatrix> A_crs =
Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( A );
Teuchos::RCP<const Epetra_CrsMatrix> B_crs =
Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( B );
Teuchos::RCP<Epetra_CrsMatrix> C_crs =
Teuchos::rcp_dynamic_cast<Epetra_CrsMatrix>( C );
if ( Teuchos::is_null(A_crs) )
{
A_crs = createCrsMatrix( A );
}
if ( Teuchos::is_null(B_crs) )
{
B_crs = createCrsMatrix( B );
}
if ( Teuchos::is_null(C_crs) )
{
C_crs = Teuchos::rcp(
new Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), 0) );
}
EpetraExt::MatrixMatrix::Multiply(
*A_crs, false, *B_crs, false, *C_crs );
}
/*!
* \brief Create a copy of a RowMatrix in a CrsMatrix.
*/
static Teuchos::RCP<Epetra_CrsMatrix>
createCrsMatrix( const Teuchos::RCP<const matrix_type>& A )
{
const Epetra_Map &row_map = A->RowMatrixRowMap();
const Epetra_Map &col_map = A->RowMatrixColMap();
Teuchos::RCP<Epetra_CrsMatrix> A_crs = Teuchos::rcp(
new Epetra_CrsMatrix( Copy, row_map, col_map, 0 ) );
int num_local_rows = row_map.NumMyElements();
Teuchos::Array<int> my_global_rows( num_local_rows );
row_map.MyGlobalElements( my_global_rows.getRawPtr() );
int num_local_cols = col_map.NumMyElements() ;
Teuchos::Array<int> my_global_cols( num_local_cols );
col_map.MyGlobalElements( my_global_cols.getRawPtr() );
int max_entries = A->MaxNumEntries();
int num_entries = 0;
Teuchos::Array<int> local_indices(max_entries);
Teuchos::Array<int> global_indices(max_entries);
Teuchos::Array<double> values(max_entries);
int error = 0;
for( int local_row = 0; local_row < num_local_rows; ++local_row )
{
error = A->ExtractMyRowCopy( local_row,
max_entries,
num_entries,
values.getRawPtr(),
local_indices.getRawPtr() );
MCLS_CHECK( 0 == error );
for (int j = 0 ; j < num_entries; ++j )
{
global_indices[j] = my_global_cols[ local_indices[j] ];
}
error = A_crs->InsertGlobalValues( my_global_rows[local_row],
num_entries,
values.getRawPtr(),
global_indices.getRawPtr() );
MCLS_CHECK( 0 == error );
}
error = A_crs->FillComplete();
MCLS_CHECK( 0 == error );
return A_crs;
}
};
//---------------------------------------------------------------------------//
} // end namespace MCLS
#endif // end MCLS_EPETRAHELPERS_HPP
//---------------------------------------------------------------------------//
// end MCLS_EpetraHelpers.hpp
//---------------------------------------------------------------------------//
<|endoftext|> |
<commit_before>#include <sirius.h>
#include <fstream>
#include <string>
using namespace sirius;
void test_hloc(std::vector<int> mpi_grid_dims__, double cutoff__, int num_bands__, int reduce_gvec__,
int use_gpu__, int gpu_ptr__)
{
device_t pu = static_cast<device_t>(use_gpu__);
matrix3d<double> M = {{10, 0, 0}, {0, 10, 0}, {0, 0, 10}};
for (int i = 0; i < 3; i++) {
printf(" a%1i : %18.10f %18.10f %18.10f \n", i + 1, M(0, i), M(1, i), M(2, i));
}
Simulation_context params;
params.set_processing_unit(pu);
params.unit_cell().set_lattice_vectors(M);
params.mpi_grid_dims(mpi_grid_dims__);
params.pw_cutoff(cutoff__ + 1);
params.gk_cutoff(cutoff__ / 2);
params.electronic_structure_method("pseudopotential");
params.use_symmetry(false);
params.initialize();
auto& gvec = params.gvec();
auto& gvecp = params.gvec_partition();
auto& fft = params.spfft();
if (Communicator::world().rank() == 0) {
printf("total number of G-vectors: %i\n", gvec.num_gvec());
printf("local number of G-vectors: %i\n", gvec.gvec_count(0));
printf("FFT grid size: %i %i %i\n", fft.dim_x(), fft.dim_y(), fft.dim_z());
printf("number of FFT threads: %i\n", omp_get_max_threads());
printf("number of FFT groups: %i\n", params.comm_ortho_fft().size());
//printf("MPI grid: %i %i\n", mpi_grid.communicator(1 << 0).size(), mpi_grid.communicator(1 << 1).size());
printf("number of z-columns: %i\n", gvec.num_zcol());
}
Local_operator hloc(params, fft, gvecp);
//Wave_functions phi(gvecp, 4 * num_bands__, memory_t::host);
//for (int i = 0; i < 4 * num_bands__; i++) {
// for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
// phi.pw_coeffs(0).prime(j, i) = utils::random<double_complex>();
// }
// phi.pw_coeffs(0).prime(0, i) = 1.0;
//}
//Wave_functions hphi(gvecp, 4 * num_bands__, memory_t::host);
//if (pu == device_t::GPU) {
// phi.pw_coeffs(0).allocate(memory_t::device);
// phi.pw_coeffs(0).copy_to(memory_t::device, 0, 4 * num_bands__);
// hphi.pw_coeffs(0).allocate(memory_t::device);
//}
//hloc.prepare(gvecp);
//Communicator::world().barrier();
//utils::timer t1("h_loc");
//for (int i = 0; i < 4; i++) {
// hloc.apply_h(fft, spin_range(0), phi, hphi, i * num_bands__, num_bands__);
//}
//Communicator::world().barrier();
//t1.stop();
//hloc.dismiss();
//double diff{0};
//for (int i = 0; i < 4 * num_bands__; i++) {
// for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
// int ig = gvec.offset() + j;
// auto gc = gvec.gvec_cart<index_domain_t::global>(ig);
// diff += std::pow(std::abs((2.71828 + 0.5 * dot(gc, gc)) * phi.pw_coeffs(0).prime(j, i) - hphi.pw_coeffs(0).prime(j, i)), 2);
// }
//}
//if (diff != diff) {
// TERMINATE("NaN");
//}
//Communicator::world().allreduce(&diff, 1);
//diff = std::sqrt(diff / 4 / num_bands__ / gvec.num_gvec());
//if (Communicator::world().rank() == 0) {
// printf("RMS: %18.16f\n", diff);
//}
//if (diff > 1e-12) {
// TERMINATE("RMS is too large");
//}
}
int main(int argn, char** argv)
{
cmd_args args;
args.register_key("--mpi_grid_dims=", "{int int} dimensions of MPI grid");
args.register_key("--cutoff=", "{double} wave-functions cutoff");
args.register_key("--reduce_gvec=", "{int} 0: use full set of G-vectors, 1: use reduced set of G-vectors");
args.register_key("--num_bands=", "{int} number of bands");
args.register_key("--use_gpu=", "{int} 0: CPU only, 1: hybrid CPU+GPU");
args.register_key("--gpu_ptr=", "{int} 0: start from CPU, 1: start from GPU");
args.register_key("--repeat=", "{int} number of repetitions");
args.register_key("--t_file=", "{string} name of timing output file");
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
auto mpi_grid_dims = args.value< std::vector<int> >("mpi_grid_dims", {1, 1});
auto cutoff = args.value<double>("cutoff", 10.0);
auto reduce_gvec = args.value<int>("reduce_gvec", 0);
auto num_bands = args.value<int>("num_bands", 10);
auto use_gpu = args.value<int>("use_gpu", 0);
auto gpu_ptr = args.value<int>("gpu_ptr", 0);
auto repeat = args.value<int>("repeat", 3);
auto t_file = args.value<std::string>("t_file", std::string(""));
sirius::initialize(1);
for (int i = 0; i < repeat; i++) {
test_hloc(mpi_grid_dims, cutoff, num_bands, reduce_gvec, use_gpu, gpu_ptr);
}
int my_rank = Communicator::world().rank();
sirius::finalize(1);
if (my_rank == 0) {
const auto timing_result = ::utils::global_rtgraph_timer.process();
std::cout << timing_result.print();
//if (!t_file.empty()) {
// std::ofstream json_file(t_file);
// json_file << std::setw(2) << utils::timer::serialize() << std::endl;
//}
}
}
<commit_msg>restore test_hloc<commit_after>#include <sirius.h>
#include <fstream>
#include <string>
using namespace sirius;
void test_hloc(std::vector<int> mpi_grid_dims__, double cutoff__, int num_bands__, int reduce_gvec__,
int use_gpu__, int gpu_ptr__)
{
device_t pu = static_cast<device_t>(use_gpu__);
matrix3d<double> M = {{10, 0, 0}, {0, 10, 0}, {0, 0, 10}};
for (int i = 0; i < 3; i++) {
printf(" a%1i : %18.10f %18.10f %18.10f \n", i + 1, M(0, i), M(1, i), M(2, i));
}
Simulation_context params;
params.set_processing_unit(pu);
params.unit_cell().set_lattice_vectors(M);
params.mpi_grid_dims(mpi_grid_dims__);
params.pw_cutoff(cutoff__ + 1);
params.gk_cutoff(cutoff__ / 2);
params.electronic_structure_method("pseudopotential");
params.use_symmetry(false);
params.initialize();
auto& gvec = params.gvec();
auto& gvecp = params.gvec_partition();
auto& fft = params.spfft();
if (Communicator::world().rank() == 0) {
printf("total number of G-vectors: %i\n", gvec.num_gvec());
printf("local number of G-vectors: %i\n", gvec.gvec_count(0));
printf("FFT grid size: %i %i %i\n", fft.dim_x(), fft.dim_y(), fft.dim_z());
printf("number of FFT threads: %i\n", omp_get_max_threads());
printf("number of FFT groups: %i\n", params.comm_ortho_fft().size());
//printf("MPI grid: %i %i\n", mpi_grid.communicator(1 << 0).size(), mpi_grid.communicator(1 << 1).size());
printf("number of z-columns: %i\n", gvec.num_zcol());
}
Local_operator hloc(params, fft, gvecp);
Wave_functions phi(gvecp, 4 * num_bands__, memory_t::host);
for (int i = 0; i < 4 * num_bands__; i++) {
for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
phi.pw_coeffs(0).prime(j, i) = utils::random<double_complex>();
}
phi.pw_coeffs(0).prime(0, i) = 1.0;
}
Wave_functions hphi(gvecp, 4 * num_bands__, memory_t::host);
if (pu == device_t::GPU) {
phi.pw_coeffs(0).allocate(memory_t::device);
phi.pw_coeffs(0).copy_to(memory_t::device, 0, 4 * num_bands__);
hphi.pw_coeffs(0).allocate(memory_t::device);
}
hloc.prepare_k(gvecp);
for (int i = 0; i < 4; i++) {
hloc.apply_h(fft, gvecp, spin_range(0), phi, hphi, i * num_bands__, num_bands__);
}
//hloc.dismiss();
double diff{0};
for (int i = 0; i < 4 * num_bands__; i++) {
for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
int ig = gvec.offset() + j;
auto gc = gvec.gvec_cart<index_domain_t::global>(ig);
diff += std::pow(std::abs((2.71828 + 0.5 * dot(gc, gc)) * phi.pw_coeffs(0).prime(j, i) - hphi.pw_coeffs(0).prime(j, i)), 2);
}
}
if (diff != diff) {
TERMINATE("NaN");
}
Communicator::world().allreduce(&diff, 1);
diff = std::sqrt(diff / 4 / num_bands__ / gvec.num_gvec());
if (Communicator::world().rank() == 0) {
printf("RMS: %18.16f\n", diff);
}
if (diff > 1e-12) {
TERMINATE("RMS is too large");
}
}
int main(int argn, char** argv)
{
cmd_args args;
args.register_key("--mpi_grid_dims=", "{int int} dimensions of MPI grid");
args.register_key("--cutoff=", "{double} wave-functions cutoff");
args.register_key("--reduce_gvec=", "{int} 0: use full set of G-vectors, 1: use reduced set of G-vectors");
args.register_key("--num_bands=", "{int} number of bands");
args.register_key("--use_gpu=", "{int} 0: CPU only, 1: hybrid CPU+GPU");
args.register_key("--gpu_ptr=", "{int} 0: start from CPU, 1: start from GPU");
args.register_key("--repeat=", "{int} number of repetitions");
args.register_key("--t_file=", "{string} name of timing output file");
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
auto mpi_grid_dims = args.value< std::vector<int> >("mpi_grid_dims", {1, 1});
auto cutoff = args.value<double>("cutoff", 10.0);
auto reduce_gvec = args.value<int>("reduce_gvec", 0);
auto num_bands = args.value<int>("num_bands", 10);
auto use_gpu = args.value<int>("use_gpu", 0);
auto gpu_ptr = args.value<int>("gpu_ptr", 0);
auto repeat = args.value<int>("repeat", 3);
auto t_file = args.value<std::string>("t_file", std::string(""));
sirius::initialize(1);
for (int i = 0; i < repeat; i++) {
test_hloc(mpi_grid_dims, cutoff, num_bands, reduce_gvec, use_gpu, gpu_ptr);
}
int my_rank = Communicator::world().rank();
sirius::finalize(1);
if (my_rank == 0) {
const auto timing_result = ::utils::global_rtgraph_timer.process();
std::cout << timing_result.print();
//if (!t_file.empty()) {
// std::ofstream json_file(t_file);
// json_file << std::setw(2) << utils::timer::serialize() << std::endl;
//}
}
}
<|endoftext|> |
<commit_before><commit_msg>Remove net/url_request/fraudulent_certificate_reporter.cc.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: myucp_datasupplier.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:39:46 $
*
* 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 DBA_DATASUPPLIER_HXX
#define DBA_DATASUPPLIER_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSET_HXX
#include <ucbhelper/resultset.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#include <memory>
namespace dbaccess {
struct DataSupplier_Impl;
class OContentHelper;
class DataSupplier : public ucbhelper::ResultSetDataSupplier
{
::std::auto_ptr<DataSupplier_Impl> m_pImpl;
public:
DataSupplier( const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< ODocumentContainer >& rxContent,
sal_Int32 nOpenMode );
virtual ~DataSupplier();
virtual rtl::OUString queryContentIdentifierString( sal_uInt32 nIndex );
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >
queryContentIdentifier( sal_uInt32 nIndex );
virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent >
queryContent( sal_uInt32 nIndex );
virtual sal_Bool getResult( sal_uInt32 nIndex );
virtual sal_uInt32 totalCount();
virtual sal_uInt32 currentCount();
virtual sal_Bool isCountFinal();
virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XRow >
queryPropertyValues( sal_uInt32 nIndex );
virtual void releasePropertyValues( sal_uInt32 nIndex );
virtual void close();
virtual void validate()
throw( com::sun::star::ucb::ResultSetException );
};
}
#endif // DBA_DATASUPPLIER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.166); FILE MERGED 2008/03/31 13:26:47 rt 1.5.166.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: myucp_datasupplier.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 DBA_DATASUPPLIER_HXX
#define DBA_DATASUPPLIER_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSET_HXX
#include <ucbhelper/resultset.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#include <memory>
namespace dbaccess {
struct DataSupplier_Impl;
class OContentHelper;
class DataSupplier : public ucbhelper::ResultSetDataSupplier
{
::std::auto_ptr<DataSupplier_Impl> m_pImpl;
public:
DataSupplier( const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< ODocumentContainer >& rxContent,
sal_Int32 nOpenMode );
virtual ~DataSupplier();
virtual rtl::OUString queryContentIdentifierString( sal_uInt32 nIndex );
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >
queryContentIdentifier( sal_uInt32 nIndex );
virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent >
queryContent( sal_uInt32 nIndex );
virtual sal_Bool getResult( sal_uInt32 nIndex );
virtual sal_uInt32 totalCount();
virtual sal_uInt32 currentCount();
virtual sal_Bool isCountFinal();
virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XRow >
queryPropertyValues( sal_uInt32 nIndex );
virtual void releasePropertyValues( sal_uInt32 nIndex );
virtual void close();
virtual void validate()
throw( com::sun::star::ucb::ResultSetException );
};
}
#endif // DBA_DATASUPPLIER_HXX
<|endoftext|> |
<commit_before>#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "chplalloc.h"
#include "misc.h"
#include "stringutil.h"
char* glomstrings(int numstrings, ...) {
int i;
char** stringlist = (char**)MALLOC(numstrings * sizeof(char*));
va_list ap;
va_start(ap, numstrings);
for (i=0; i<numstrings; i++) {
stringlist[i] = va_arg(ap, char*);
}
va_end(ap);
unsigned int totlen = 0;
for (i=0; i<numstrings; i++) {
totlen += strlen(stringlist[i]);
}
char* newstring = (char*)MALLOC((totlen + 1)*sizeof(char));
newstring[0] = '\0';
for (i=0; i<numstrings; i++) {
strcat(newstring, stringlist[i]);
}
if (strlen(newstring) > totlen) {
INT_FATAL("glomstrings() buffer overflow");
}
return newstring;
}
char* copystring(char* str) {
return glomstrings(1, str);
}
char* intstring(int i) {
char scratch[8];
sprintf(scratch, "%d", i);
return glomstrings(1, scratch);
}
<commit_msg><commit_after>#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "chplalloc.h"
#include "misc.h"
#include "stringutil.h"
char* glomstrings(int numstrings, ...) {
int i;
char** stringlist = (char**)MALLOC(numstrings * sizeof(char*));
va_list ap;
va_start(ap, numstrings);
for (i=0; i<numstrings; i++) {
stringlist[i] = va_arg(ap, char*);
}
va_end(ap);
unsigned int totlen = 0;
for (i=0; i<numstrings; i++) {
totlen += strlen(stringlist[i]);
}
char* newstring = (char*)MALLOC((totlen + 1)*sizeof(char));
newstring[0] = '\0';
for (i=0; i<numstrings; i++) {
strcat(newstring, stringlist[i]);
}
if (strlen(newstring) > totlen) {
INT_FATAL("glomstrings() buffer overflow");
}
return newstring;
}
char* copystring(char* str) {
return glomstrings(1, str);
}
char* intstring(int i) {
const size_t size = 64;
char scratch[size];
size_t charsWritten = snprintf(scratch, size, "%d", i);
if (charsWritten > size) {
INT_FATAL("intstring() buffer overflow");
}
return glomstrings(1, scratch);
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2012
\file main.cpp
\author ([email protected])
\date 13.05.2012
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/format.hpp>
#define BOOST_TEST_MODULE RDORealFormatTest
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE(RDORealFormatTest)
BOOST_AUTO_TEST_CASE(MantissaPrecision)
{
double value = 10e+237;
std::stringstream stream;
stream << boost::format("%1$.10E") % value;
std::string str = stream.str();
std::cout << str << std::endl;
BOOST_CHECK(stream.str() == "1.0000000000E+238");
}
BOOST_AUTO_TEST_SUITE_END() // RDORealFormatTest
<commit_msg> - другое число<commit_after>/*!
\copyright (c) RDO-Team, 2012
\file main.cpp
\author ([email protected])
\date 13.05.2012
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/format.hpp>
#define BOOST_TEST_MODULE RDORealFormatTest
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE(RDORealFormatTest)
BOOST_AUTO_TEST_CASE(MantissaPrecision)
{
double value = 10e+37;
std::stringstream stream;
stream << boost::format("%1$.10E") % value;
std::string str = stream.str();
std::cout << str << std::endl;
BOOST_CHECK(stream.str() == "1.0000000000E+038");
}
BOOST_AUTO_TEST_SUITE_END() // RDORealFormatTest
<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// 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.
//
//-------------------------------------------------------------------------
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <inttypes.h>
#include <unistd.h>
#include "font.h"
#include "cpuTrace.h"
//-------------------------------------------------------------------------
void
CCpuTrace::
getCpuStats(
SCpuStats& cpuStats)
{
FILE *fp = fopen("/proc/stat", "r");
if (fp == 0)
{
perror("unable to open /proc/stat");
exit(EXIT_FAILURE);
}
fscanf(fp, "%*s");
fscanf(fp, "%" SCNu32, &(cpuStats.user));
fscanf(fp, "%" SCNu32, &(cpuStats.nice));
fscanf(fp, "%" SCNu32, &(cpuStats.system));
fscanf(fp, "%" SCNu32, &(cpuStats.idle));
fscanf(fp, "%" SCNu32, &(cpuStats.iowait));
fscanf(fp, "%" SCNu32, &(cpuStats.irq));
fscanf(fp, "%" SCNu32, &(cpuStats.softirq));
fscanf(fp, "%" SCNu32, &(cpuStats.steal));
fscanf(fp, "%" SCNu32, &(cpuStats.guest));
fscanf(fp, "%" SCNu32, &(cpuStats.guest_nice));
fclose(fp);
}
//-------------------------------------------------------------------------
void
CCpuTrace::
diffCpuStats(
const SCpuStats& lhs,
const SCpuStats& rhs,
SCpuStats& result)
{
result.user = lhs.user - rhs.user;
result.nice = lhs.nice - rhs.nice;
result.system = lhs.system - rhs.system;
result.idle = lhs.idle - rhs.idle;
result.iowait = lhs.iowait - rhs.iowait;
result.irq = lhs.irq - rhs.irq;
result.softirq = lhs.softirq - rhs.softirq;
result.steal = lhs.steal - rhs.steal;
result.guest = lhs.guest - rhs.guest;
result.guest_nice = lhs.guest_nice - rhs.guest_nice;
}
//-------------------------------------------------------------------------
CCpuTrace::
CCpuTrace(
int16_t width,
int16_t traceHeight,
int16_t yPosition,
int16_t gridHeight)
:
CTrace(width,
traceHeight,
yPosition,
gridHeight,
3,
"CPU",
std::vector<std::string>{"user", "nice", "system"},
std::vector<CRGB565>{{4,90,141},{116,169,207},{241,238,246}}),
m_traceHeight{traceHeight}
{
getCpuStats(m_currentStats);
}
//-------------------------------------------------------------------------
void
CCpuTrace::
show(
const CFrameBuffer565& fb,
time_t now)
{
SCpuStats diff;
memcpy(&m_previousStats, &m_currentStats, sizeof(m_previousStats));
getCpuStats(m_currentStats);
diffCpuStats(m_currentStats, m_previousStats, diff);
uint32_t totalCpu = diff.user
+ diff.nice
+ diff.system
+ diff.idle
+ diff.iowait
+ diff.irq
+ diff.softirq
+ diff.steal
+ diff.guest
+ diff.guest_nice;
int8_t user = (diff.user * m_traceHeight) / totalCpu;
int8_t nice = (diff.nice * m_traceHeight) / totalCpu;
int8_t system = (diff.system * m_traceHeight) / totalCpu;
update(std::vector<int8_t>{user, nice, system}, now);
putImage(fb);
}
<commit_msg>tabs -> 4 spaces<commit_after>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// 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.
//
//-------------------------------------------------------------------------
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <inttypes.h>
#include <unistd.h>
#include "font.h"
#include "cpuTrace.h"
//-------------------------------------------------------------------------
void
CCpuTrace::
getCpuStats(
SCpuStats& cpuStats)
{
FILE *fp = fopen("/proc/stat", "r");
if (fp == 0)
{
perror("unable to open /proc/stat");
exit(EXIT_FAILURE);
}
fscanf(fp, "%*s");
fscanf(fp, "%" SCNu32, &(cpuStats.user));
fscanf(fp, "%" SCNu32, &(cpuStats.nice));
fscanf(fp, "%" SCNu32, &(cpuStats.system));
fscanf(fp, "%" SCNu32, &(cpuStats.idle));
fscanf(fp, "%" SCNu32, &(cpuStats.iowait));
fscanf(fp, "%" SCNu32, &(cpuStats.irq));
fscanf(fp, "%" SCNu32, &(cpuStats.softirq));
fscanf(fp, "%" SCNu32, &(cpuStats.steal));
fscanf(fp, "%" SCNu32, &(cpuStats.guest));
fscanf(fp, "%" SCNu32, &(cpuStats.guest_nice));
fclose(fp);
}
//-------------------------------------------------------------------------
void
CCpuTrace::
diffCpuStats(
const SCpuStats& lhs,
const SCpuStats& rhs,
SCpuStats& result)
{
result.user = lhs.user - rhs.user;
result.nice = lhs.nice - rhs.nice;
result.system = lhs.system - rhs.system;
result.idle = lhs.idle - rhs.idle;
result.iowait = lhs.iowait - rhs.iowait;
result.irq = lhs.irq - rhs.irq;
result.softirq = lhs.softirq - rhs.softirq;
result.steal = lhs.steal - rhs.steal;
result.guest = lhs.guest - rhs.guest;
result.guest_nice = lhs.guest_nice - rhs.guest_nice;
}
//-------------------------------------------------------------------------
CCpuTrace::
CCpuTrace(
int16_t width,
int16_t traceHeight,
int16_t yPosition,
int16_t gridHeight)
:
CTrace(width,
traceHeight,
yPosition,
gridHeight,
3,
"CPU",
std::vector<std::string>{"user", "nice", "system"},
std::vector<CRGB565>{{4,90,141},{116,169,207},{241,238,246}}),
m_traceHeight{traceHeight}
{
getCpuStats(m_currentStats);
}
//-------------------------------------------------------------------------
void
CCpuTrace::
show(
const CFrameBuffer565& fb,
time_t now)
{
SCpuStats diff;
memcpy(&m_previousStats, &m_currentStats, sizeof(m_previousStats));
getCpuStats(m_currentStats);
diffCpuStats(m_currentStats, m_previousStats, diff);
uint32_t totalCpu = diff.user
+ diff.nice
+ diff.system
+ diff.idle
+ diff.iowait
+ diff.irq
+ diff.softirq
+ diff.steal
+ diff.guest
+ diff.guest_nice;
int8_t user = (diff.user * m_traceHeight) / totalCpu;
int8_t nice = (diff.nice * m_traceHeight) / totalCpu;
int8_t system = (diff.system * m_traceHeight) / totalCpu;
update(std::vector<int8_t>{user, nice, system}, now);
putImage(fb);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CustomAnimationCreateDialog.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2008-04-02 09:43:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
#define _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
#ifndef _SD_CUSTOMANIMATIONPRESET_HXX
#include "CustomAnimationPreset.hxx"
#endif
#ifndef _SV_TABDLG_HXX
#include <vcl/tabdlg.hxx>
#endif
enum PathKind { NONE, CURVE, POLYGON, FREEFORM };
class TabControl;
class OKButton;
class CancelButton;
class HelpButton;
namespace sd {
// --------------------------------------------------------------------
class CustomAnimationCreateTabPage;
class CustomAnimationPane;
class CustomAnimationCreateDialog : public TabDialog
{
friend class CustomAnimationCreateTabPage;
public:
CustomAnimationCreateDialog( ::Window* pParent, CustomAnimationPane* pPane, const std::vector< ::com::sun::star::uno::Any >& rTargets, bool bHasText, const ::rtl::OUString& rsPresetId, double fDuration );
~CustomAnimationCreateDialog();
PathKind getCreatePathKind() const;
CustomAnimationPresetPtr getSelectedPreset() const;
double getSelectedDuration() const;
private:
CustomAnimationCreateTabPage* getCurrentPage() const;
void preview( const CustomAnimationPresetPtr& pPreset ) const;
void setPosition();
void storePosition();
DECL_LINK( implActivatePagekHdl, Control* );
DECL_LINK( implDeactivatePagekHdl, Control* );
private:
CustomAnimationPane* mpPane;
const std::vector< ::com::sun::star::uno::Any >& mrTargets;
double mfDuration;
bool mbIsPreview;
TabControl* mpTabControl;
OKButton* mpOKButton;
CancelButton* mpCancelButton;
HelpButton* mpHelpButton;
CustomAnimationCreateTabPage* mpTabPages[4];
};
}
#endif // _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.166); FILE MERGED 2008/04/01 15:34:09 thb 1.7.166.3: #i85898# Stripping all external header guards 2008/04/01 12:38:35 thb 1.7.166.2: #i85898# Stripping all external header guards 2008/03/31 13:56:55 rt 1.7.166.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: CustomAnimationCreateDialog.hxx,v $
* $Revision: 1.9 $
*
* 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 _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
#define _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
#include "CustomAnimationPreset.hxx"
#include <vcl/tabdlg.hxx>
enum PathKind { NONE, CURVE, POLYGON, FREEFORM };
class TabControl;
class OKButton;
class CancelButton;
class HelpButton;
namespace sd {
// --------------------------------------------------------------------
class CustomAnimationCreateTabPage;
class CustomAnimationPane;
class CustomAnimationCreateDialog : public TabDialog
{
friend class CustomAnimationCreateTabPage;
public:
CustomAnimationCreateDialog( ::Window* pParent, CustomAnimationPane* pPane, const std::vector< ::com::sun::star::uno::Any >& rTargets, bool bHasText, const ::rtl::OUString& rsPresetId, double fDuration );
~CustomAnimationCreateDialog();
PathKind getCreatePathKind() const;
CustomAnimationPresetPtr getSelectedPreset() const;
double getSelectedDuration() const;
private:
CustomAnimationCreateTabPage* getCurrentPage() const;
void preview( const CustomAnimationPresetPtr& pPreset ) const;
void setPosition();
void storePosition();
DECL_LINK( implActivatePagekHdl, Control* );
DECL_LINK( implDeactivatePagekHdl, Control* );
private:
CustomAnimationPane* mpPane;
const std::vector< ::com::sun::star::uno::Any >& mrTargets;
double mfDuration;
bool mbIsPreview;
TabControl* mpTabControl;
OKButton* mpOKButton;
CancelButton* mpCancelButton;
HelpButton* mpHelpButton;
CustomAnimationCreateTabPage* mpTabPages[4];
};
}
#endif // _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "rocksdb/utilities/write_batch_with_index.h"
#include "rocksdb/comparator.h"
#include "db/column_family.h"
#include "db/skiplist.h"
#include "util/arena.h"
namespace rocksdb {
namespace {
class ReadableWriteBatch : public WriteBatch {
public:
explicit ReadableWriteBatch(size_t reserved_bytes = 0)
: WriteBatch(reserved_bytes) {}
// Retrieve some information from a write entry in the write batch, given
// the start offset of the write entry.
Status GetEntryFromDataOffset(size_t data_offset, WriteType* type, Slice* Key,
Slice* value, Slice* blob) const;
};
} // namespace
// Key used by skip list, as the binary searchable index of WriteBatchWithIndex.
struct WriteBatchIndexEntry {
WriteBatchIndexEntry(size_t o, uint32_t c)
: offset(o), column_family(c), search_key(nullptr) {}
WriteBatchIndexEntry(const Slice* sk, uint32_t c)
: offset(0), column_family(c), search_key(sk) {}
size_t offset; // offset of an entry in write batch's string buffer.
uint32_t column_family; // column family of the entry
const Slice* search_key; // if not null, instead of reading keys from
// write batch, use it to compare. This is used
// for lookup key.
};
class WriteBatchEntryComparator {
public:
WriteBatchEntryComparator(const Comparator* comparator,
const ReadableWriteBatch* write_batch)
: comparator_(comparator), write_batch_(write_batch) {}
// Compare a and b. Return a negative value if a is less than b, 0 if they
// are equal, and a positive value if a is greater than b
int operator()(const WriteBatchIndexEntry* entry1,
const WriteBatchIndexEntry* entry2) const;
private:
const Comparator* comparator_;
const ReadableWriteBatch* write_batch_;
};
typedef SkipList<WriteBatchIndexEntry*, const WriteBatchEntryComparator&>
WriteBatchEntrySkipList;
struct WriteBatchWithIndex::Rep {
Rep(const Comparator* index_comparator, size_t reserved_bytes = 0)
: write_batch(reserved_bytes),
comparator(index_comparator, &write_batch),
skip_list(comparator, &arena) {}
ReadableWriteBatch write_batch;
WriteBatchEntryComparator comparator;
Arena arena;
WriteBatchEntrySkipList skip_list;
WriteBatchIndexEntry* GetEntry(ColumnFamilyHandle* column_family) {
return GetEntryWithCfId(GetColumnFamilyID(column_family));
}
WriteBatchIndexEntry* GetEntryWithCfId(uint32_t column_family_id) {
auto* mem = arena.Allocate(sizeof(WriteBatchIndexEntry));
auto* index_entry = new (mem)
WriteBatchIndexEntry(write_batch.GetDataSize(), column_family_id);
return index_entry;
}
};
class WBWIIteratorImpl : public WBWIIterator {
public:
WBWIIteratorImpl(uint32_t column_family_id,
WriteBatchEntrySkipList* skip_list,
const ReadableWriteBatch* write_batch)
: column_family_id_(column_family_id),
skip_list_iter_(skip_list),
write_batch_(write_batch),
valid_(false) {}
virtual ~WBWIIteratorImpl() {}
virtual bool Valid() const override { return valid_; }
virtual void Seek(const Slice& key) override {
valid_ = true;
WriteBatchIndexEntry search_entry(&key, column_family_id_);
skip_list_iter_.Seek(&search_entry);
ReadEntry();
}
virtual void Next() override {
skip_list_iter_.Next();
ReadEntry();
}
virtual const WriteEntry& Entry() const override { return current_; }
virtual Status status() const override { return status_; }
private:
uint32_t column_family_id_;
WriteBatchEntrySkipList::Iterator skip_list_iter_;
const ReadableWriteBatch* write_batch_;
Status status_;
bool valid_;
WriteEntry current_;
void ReadEntry() {
if (!status_.ok() || !skip_list_iter_.Valid()) {
valid_ = false;
return;
}
const WriteBatchIndexEntry* iter_entry = skip_list_iter_.key();
if (iter_entry == nullptr ||
iter_entry->column_family != column_family_id_) {
valid_ = false;
return;
}
Slice blob;
status_ = write_batch_->GetEntryFromDataOffset(
iter_entry->offset, ¤t_.type, ¤t_.key, ¤t_.value,
&blob);
if (!status_.ok()) {
valid_ = false;
} else if (current_.type != kPutRecord && current_.type != kDeleteRecord &&
current_.type != kMergeRecord) {
valid_ = false;
status_ = Status::Corruption("write batch index is corrupted");
}
}
};
Status ReadableWriteBatch::GetEntryFromDataOffset(size_t data_offset,
WriteType* type, Slice* Key,
Slice* value,
Slice* blob) const {
if (type == nullptr || Key == nullptr || value == nullptr ||
blob == nullptr) {
return Status::InvalidArgument("Output parameters cannot be null");
}
if (data_offset >= GetDataSize()) {
return Status::InvalidArgument("data offset exceed write batch size");
}
Slice input = Slice(rep_.data() + data_offset, rep_.size() - data_offset);
char tag;
uint32_t column_family;
Status s =
ReadRecordFromWriteBatch(&input, &tag, &column_family, Key, value, blob);
switch (tag) {
case kTypeColumnFamilyValue:
case kTypeValue:
*type = kPutRecord;
break;
case kTypeColumnFamilyDeletion:
case kTypeDeletion:
*type = kDeleteRecord;
break;
case kTypeColumnFamilyMerge:
case kTypeMerge:
*type = kMergeRecord;
break;
case kTypeLogData:
*type = kLogDataRecord;
break;
default:
return Status::Corruption("unknown WriteBatch tag");
}
return Status::OK();
}
WriteBatchWithIndex::WriteBatchWithIndex(const Comparator* index_comparator,
size_t reserved_bytes)
: rep(new Rep(index_comparator, reserved_bytes)) {}
WriteBatchWithIndex::~WriteBatchWithIndex() { delete rep; }
WriteBatch* WriteBatchWithIndex::GetWriteBatch() { return &rep->write_batch; }
WBWIIterator* WriteBatchWithIndex::NewIterator() {
return new WBWIIteratorImpl(0, &(rep->skip_list), &rep->write_batch);
}
WBWIIterator* WriteBatchWithIndex::NewIterator(
ColumnFamilyHandle* column_family) {
return new WBWIIteratorImpl(GetColumnFamilyID(column_family),
&(rep->skip_list), &rep->write_batch);
}
void WriteBatchWithIndex::Put(ColumnFamilyHandle* column_family,
const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Put(column_family, key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Put(const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Put(key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Merge(ColumnFamilyHandle* column_family,
const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Merge(column_family, key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Merge(const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Merge(key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::PutLogData(const Slice& blob) {
rep->write_batch.PutLogData(blob);
}
void WriteBatchWithIndex::Delete(ColumnFamilyHandle* column_family,
const Slice& key) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Delete(column_family, key);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Delete(const Slice& key) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Delete(key);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Delete(ColumnFamilyHandle* column_family,
const SliceParts& key) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Delete(column_family, key);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Delete(const SliceParts& key) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Delete(key);
rep->skip_list.Insert(index_entry);
}
int WriteBatchEntryComparator::operator()(
const WriteBatchIndexEntry* entry1,
const WriteBatchIndexEntry* entry2) const {
if (entry1->column_family > entry2->column_family) {
return 1;
} else if (entry1->column_family < entry2->column_family) {
return -1;
}
Status s;
Slice key1, key2;
if (entry1->search_key == nullptr) {
Slice value, blob;
WriteType write_type;
s = write_batch_->GetEntryFromDataOffset(entry1->offset, &write_type, &key1,
&value, &blob);
if (!s.ok()) {
return 1;
}
} else {
key1 = *(entry1->search_key);
}
if (entry2->search_key == nullptr) {
Slice value, blob;
WriteType write_type;
s = write_batch_->GetEntryFromDataOffset(entry2->offset, &write_type, &key2,
&value, &blob);
if (!s.ok()) {
return -1;
}
} else {
key2 = *(entry2->search_key);
}
int cmp = comparator_->Compare(key1, key2);
if (cmp != 0) {
return cmp;
} else if (entry1->offset > entry2->offset) {
return 1;
} else if (entry1->offset < entry2->offset) {
return -1;
}
return 0;
}
} // namespace rocksdb
<commit_msg>fix unity build<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "rocksdb/utilities/write_batch_with_index.h"
#include "rocksdb/comparator.h"
#include "db/column_family.h"
#include "db/skiplist.h"
#include "util/arena.h"
namespace rocksdb {
class ReadableWriteBatch : public WriteBatch {
public:
explicit ReadableWriteBatch(size_t reserved_bytes = 0)
: WriteBatch(reserved_bytes) {}
// Retrieve some information from a write entry in the write batch, given
// the start offset of the write entry.
Status GetEntryFromDataOffset(size_t data_offset, WriteType* type, Slice* Key,
Slice* value, Slice* blob) const;
};
// Key used by skip list, as the binary searchable index of WriteBatchWithIndex.
struct WriteBatchIndexEntry {
WriteBatchIndexEntry(size_t o, uint32_t c)
: offset(o), column_family(c), search_key(nullptr) {}
WriteBatchIndexEntry(const Slice* sk, uint32_t c)
: offset(0), column_family(c), search_key(sk) {}
size_t offset; // offset of an entry in write batch's string buffer.
uint32_t column_family; // column family of the entry
const Slice* search_key; // if not null, instead of reading keys from
// write batch, use it to compare. This is used
// for lookup key.
};
class WriteBatchEntryComparator {
public:
WriteBatchEntryComparator(const Comparator* comparator,
const ReadableWriteBatch* write_batch)
: comparator_(comparator), write_batch_(write_batch) {}
// Compare a and b. Return a negative value if a is less than b, 0 if they
// are equal, and a positive value if a is greater than b
int operator()(const WriteBatchIndexEntry* entry1,
const WriteBatchIndexEntry* entry2) const;
private:
const Comparator* comparator_;
const ReadableWriteBatch* write_batch_;
};
typedef SkipList<WriteBatchIndexEntry*, const WriteBatchEntryComparator&>
WriteBatchEntrySkipList;
struct WriteBatchWithIndex::Rep {
Rep(const Comparator* index_comparator, size_t reserved_bytes = 0)
: write_batch(reserved_bytes),
comparator(index_comparator, &write_batch),
skip_list(comparator, &arena) {}
ReadableWriteBatch write_batch;
WriteBatchEntryComparator comparator;
Arena arena;
WriteBatchEntrySkipList skip_list;
WriteBatchIndexEntry* GetEntry(ColumnFamilyHandle* column_family) {
return GetEntryWithCfId(GetColumnFamilyID(column_family));
}
WriteBatchIndexEntry* GetEntryWithCfId(uint32_t column_family_id) {
auto* mem = arena.Allocate(sizeof(WriteBatchIndexEntry));
auto* index_entry = new (mem)
WriteBatchIndexEntry(write_batch.GetDataSize(), column_family_id);
return index_entry;
}
};
class WBWIIteratorImpl : public WBWIIterator {
public:
WBWIIteratorImpl(uint32_t column_family_id,
WriteBatchEntrySkipList* skip_list,
const ReadableWriteBatch* write_batch)
: column_family_id_(column_family_id),
skip_list_iter_(skip_list),
write_batch_(write_batch),
valid_(false) {}
virtual ~WBWIIteratorImpl() {}
virtual bool Valid() const override { return valid_; }
virtual void Seek(const Slice& key) override {
valid_ = true;
WriteBatchIndexEntry search_entry(&key, column_family_id_);
skip_list_iter_.Seek(&search_entry);
ReadEntry();
}
virtual void Next() override {
skip_list_iter_.Next();
ReadEntry();
}
virtual const WriteEntry& Entry() const override { return current_; }
virtual Status status() const override { return status_; }
private:
uint32_t column_family_id_;
WriteBatchEntrySkipList::Iterator skip_list_iter_;
const ReadableWriteBatch* write_batch_;
Status status_;
bool valid_;
WriteEntry current_;
void ReadEntry() {
if (!status_.ok() || !skip_list_iter_.Valid()) {
valid_ = false;
return;
}
const WriteBatchIndexEntry* iter_entry = skip_list_iter_.key();
if (iter_entry == nullptr ||
iter_entry->column_family != column_family_id_) {
valid_ = false;
return;
}
Slice blob;
status_ = write_batch_->GetEntryFromDataOffset(
iter_entry->offset, ¤t_.type, ¤t_.key, ¤t_.value,
&blob);
if (!status_.ok()) {
valid_ = false;
} else if (current_.type != kPutRecord && current_.type != kDeleteRecord &&
current_.type != kMergeRecord) {
valid_ = false;
status_ = Status::Corruption("write batch index is corrupted");
}
}
};
Status ReadableWriteBatch::GetEntryFromDataOffset(size_t data_offset,
WriteType* type, Slice* Key,
Slice* value,
Slice* blob) const {
if (type == nullptr || Key == nullptr || value == nullptr ||
blob == nullptr) {
return Status::InvalidArgument("Output parameters cannot be null");
}
if (data_offset >= GetDataSize()) {
return Status::InvalidArgument("data offset exceed write batch size");
}
Slice input = Slice(rep_.data() + data_offset, rep_.size() - data_offset);
char tag;
uint32_t column_family;
Status s =
ReadRecordFromWriteBatch(&input, &tag, &column_family, Key, value, blob);
switch (tag) {
case kTypeColumnFamilyValue:
case kTypeValue:
*type = kPutRecord;
break;
case kTypeColumnFamilyDeletion:
case kTypeDeletion:
*type = kDeleteRecord;
break;
case kTypeColumnFamilyMerge:
case kTypeMerge:
*type = kMergeRecord;
break;
case kTypeLogData:
*type = kLogDataRecord;
break;
default:
return Status::Corruption("unknown WriteBatch tag");
}
return Status::OK();
}
WriteBatchWithIndex::WriteBatchWithIndex(const Comparator* index_comparator,
size_t reserved_bytes)
: rep(new Rep(index_comparator, reserved_bytes)) {}
WriteBatchWithIndex::~WriteBatchWithIndex() { delete rep; }
WriteBatch* WriteBatchWithIndex::GetWriteBatch() { return &rep->write_batch; }
WBWIIterator* WriteBatchWithIndex::NewIterator() {
return new WBWIIteratorImpl(0, &(rep->skip_list), &rep->write_batch);
}
WBWIIterator* WriteBatchWithIndex::NewIterator(
ColumnFamilyHandle* column_family) {
return new WBWIIteratorImpl(GetColumnFamilyID(column_family),
&(rep->skip_list), &rep->write_batch);
}
void WriteBatchWithIndex::Put(ColumnFamilyHandle* column_family,
const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Put(column_family, key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Put(const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Put(key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Merge(ColumnFamilyHandle* column_family,
const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Merge(column_family, key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Merge(const Slice& key, const Slice& value) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Merge(key, value);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::PutLogData(const Slice& blob) {
rep->write_batch.PutLogData(blob);
}
void WriteBatchWithIndex::Delete(ColumnFamilyHandle* column_family,
const Slice& key) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Delete(column_family, key);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Delete(const Slice& key) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Delete(key);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Delete(ColumnFamilyHandle* column_family,
const SliceParts& key) {
auto* index_entry = rep->GetEntry(column_family);
rep->write_batch.Delete(column_family, key);
rep->skip_list.Insert(index_entry);
}
void WriteBatchWithIndex::Delete(const SliceParts& key) {
auto* index_entry = rep->GetEntryWithCfId(0);
rep->write_batch.Delete(key);
rep->skip_list.Insert(index_entry);
}
int WriteBatchEntryComparator::operator()(
const WriteBatchIndexEntry* entry1,
const WriteBatchIndexEntry* entry2) const {
if (entry1->column_family > entry2->column_family) {
return 1;
} else if (entry1->column_family < entry2->column_family) {
return -1;
}
Status s;
Slice key1, key2;
if (entry1->search_key == nullptr) {
Slice value, blob;
WriteType write_type;
s = write_batch_->GetEntryFromDataOffset(entry1->offset, &write_type, &key1,
&value, &blob);
if (!s.ok()) {
return 1;
}
} else {
key1 = *(entry1->search_key);
}
if (entry2->search_key == nullptr) {
Slice value, blob;
WriteType write_type;
s = write_batch_->GetEntryFromDataOffset(entry2->offset, &write_type, &key2,
&value, &blob);
if (!s.ok()) {
return -1;
}
} else {
key2 = *(entry2->search_key);
}
int cmp = comparator_->Compare(key1, key2);
if (cmp != 0) {
return cmp;
} else if (entry1->offset > entry2->offset) {
return 1;
} else if (entry1->offset < entry2->offset) {
return -1;
}
return 0;
}
} // namespace rocksdb
<|endoftext|> |
<commit_before>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Dan Petrie <dpetrie AT SIPez DOT com>
// SYSTEM INCLUDES
#include <assert.h>
#include <math.h>
// APPLICATION INCLUDES
#include <mp/MpInputDeviceManager.h>
#include <mp/MpSineWaveGeneratorDeviceDriver.h>
#include <os/OsServerTask.h>
#include <os/OsTimer.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
// 0 is the Highest priority
#define SINE_WAVE_DEVICE_PRIORITY 0
// STATIC VARIABLE INITIALIZATIONS
// PRIVATE CLASSES
class MpSineWaveGeneratorServer : public OsServerTask
{
public:
MpSineWaveGeneratorServer(unsigned int startFrameTime,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond,
unsigned int magnitude,
unsigned int periodMicroseconds,
int underOverRunTime,
MpInputDeviceHandle deviceId,
MpInputDeviceManager& inputDeviceManager)
: OsServerTask("MpSineWaveGeneratorServer-%d", NULL, DEF_MAX_MSGS, SINE_WAVE_DEVICE_PRIORITY),
mNextFrameTime(startFrameTime),
mSamplesPerFrame(samplesPerFrame),
mSamplesPerSecond(samplesPerSecond),
mMagnatude(magnitude),
mSinePeriodMicroseconds(periodMicroseconds),
mUnderOverRunTime(underOverRunTime),
mDeviceId(deviceId),
mpInputDeviceManager(&inputDeviceManager),
mpFrameData(NULL),
mTimer(getMessageQueue(), 0)
{
mpFrameData = new MpAudioSample[samplesPerFrame];
};
virtual ~MpSineWaveGeneratorServer()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer start");
// Do not continue until the task is safely shutdown
waitUntilShutDown();
assert(isShutDown());
if(mpFrameData)
{
delete[] mpFrameData;
mpFrameData = NULL;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer end");
};
virtual UtlBoolean start(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start start");
// start the task
UtlBoolean result = OsServerTask::start();
OsTime noDelay(0, 0);
int microSecondsPerFrame =
(mSamplesPerFrame * 1000000 / mSamplesPerSecond) -
mUnderOverRunTime;
assert(microSecondsPerFrame > 0);
OsTime framePeriod(0, microSecondsPerFrame);
// Start re-occurring timer which causes handleMessage to be called
// periodically
mTimer.periodicEvery(noDelay, framePeriod);
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start end");
return(result);
};
virtual void requestShutdown(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown start");
// Stop the timer first so it stops queuing messages
mTimer.stop();
// Then stop the server task
OsServerTask::requestShutdown();
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown end");
};
UtlBoolean handleMessage(OsMsg& rMsg)
{
#ifdef RTL_ENABLED
RTL_BLOCK("MpSineWaveGeneratorServer.handleMessage");
#endif
// Build a frame of signal and push it to the device manager
assert(mpFrameData);
for(unsigned int frameIndex = 0; frameIndex < mSamplesPerFrame; frameIndex++)
{
mpFrameData[frameIndex] =
MpSineWaveGeneratorDeviceDriver::calculateSample(mNextFrameTime,
mMagnatude,
mSinePeriodMicroseconds,
frameIndex,
mSamplesPerFrame,
mSamplesPerSecond);
}
mpInputDeviceManager->pushFrame(mDeviceId,
mSamplesPerFrame,
mpFrameData,
mNextFrameTime);
mNextFrameTime += mSamplesPerFrame * 1000 / mSamplesPerSecond;
return(TRUE);
}
private:
MpFrameTime mNextFrameTime;
unsigned int mSamplesPerFrame;
unsigned int mSamplesPerSecond;
unsigned int mMagnatude;
unsigned int mSinePeriodMicroseconds;
int mUnderOverRunTime;
MpInputDeviceHandle mDeviceId;
MpInputDeviceManager* mpInputDeviceManager;
MpAudioSample* mpFrameData;
OsTimer mTimer;
};
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
MpSineWaveGeneratorDeviceDriver::MpSineWaveGeneratorDeviceDriver(const UtlString& name,
MpInputDeviceManager& deviceManager,
unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
: MpInputDeviceDriver(name, deviceManager),
mMagnitude(magnitude),
mPeriodInMicroseconds(periodInMicroseconds),
mUnderOverRunTime(underOverRunTime),
mpReaderTask(NULL)
{
}
// Destructor
MpSineWaveGeneratorDeviceDriver::~MpSineWaveGeneratorDeviceDriver()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver start");
if(mpReaderTask)
{
OsStatus stat = disableDevice();
assert(stat == OS_SUCCESS);
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver end");
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpSineWaveGeneratorDeviceDriver::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice start");
OsStatus result = OS_INVALID;
assert(mpReaderTask == NULL);
if(mpReaderTask == NULL)
{
mpReaderTask =
new MpSineWaveGeneratorServer(currentFrameTime,
samplesPerFrame,
samplesPerSec,
mMagnitude,
mPeriodInMicroseconds,
mUnderOverRunTime,
getDeviceId(),
*mpInputDeviceManager);
if(mpReaderTask->start())
{
result = OS_SUCCESS;
mIsEnabled = TRUE;
}
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice end");
return(result);
}
OsStatus MpSineWaveGeneratorDeviceDriver::disableDevice()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice start");
OsStatus result = OS_TASK_NOT_STARTED;
//assert(mpReaderTask);
if(mpReaderTask)
{
mpReaderTask->requestShutdown();
delete mpReaderTask;
mpReaderTask = NULL;
result = OS_SUCCESS;
mIsEnabled = FALSE;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice end");
return(result);
}
/* ============================ ACCESSORS ================================= */
MpAudioSample
MpSineWaveGeneratorDeviceDriver::calculateSample(MpFrameTime frameStartTime,
unsigned int magnitude,
unsigned int periodInMicroseconds,
unsigned int frameSampleIndex,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond)
{
double time = ((frameStartTime + frameSampleIndex * 1000.0 / samplesPerSecond)
/ ((double) periodInMicroseconds) * 1000.0 ) * 2.0 * M_PI;
MpAudioSample sample = (MpAudioSample)(sin(time) * (double)magnitude);
return(sample);
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<commit_msg>Fixed sine wave calculation to prevent integer round off.<commit_after>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Dan Petrie <dpetrie AT SIPez DOT com>
// SYSTEM INCLUDES
#include <assert.h>
#include <math.h>
// APPLICATION INCLUDES
#include <mp/MpInputDeviceManager.h>
#include <mp/MpSineWaveGeneratorDeviceDriver.h>
#include <os/OsServerTask.h>
#include <os/OsTimer.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
// 0 is the Highest priority
#define SINE_WAVE_DEVICE_PRIORITY 0
// STATIC VARIABLE INITIALIZATIONS
// PRIVATE CLASSES
class MpSineWaveGeneratorServer : public OsServerTask
{
public:
MpSineWaveGeneratorServer(unsigned int startFrameTime,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond,
unsigned int magnitude,
unsigned int periodMicroseconds,
int underOverRunTime,
MpInputDeviceHandle deviceId,
MpInputDeviceManager& inputDeviceManager)
: OsServerTask("MpSineWaveGeneratorServer-%d", NULL, DEF_MAX_MSGS, SINE_WAVE_DEVICE_PRIORITY),
mNextFrameTime(startFrameTime),
mSamplesPerFrame(samplesPerFrame),
mSamplesPerSecond(samplesPerSecond),
mMagnatude(magnitude),
mSinePeriodMicroseconds(periodMicroseconds),
mUnderOverRunTime(underOverRunTime),
mDeviceId(deviceId),
mpInputDeviceManager(&inputDeviceManager),
mpFrameData(NULL),
mTimer(getMessageQueue(), 0)
{
mpFrameData = new MpAudioSample[samplesPerFrame];
};
virtual ~MpSineWaveGeneratorServer()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer start");
// Do not continue until the task is safely shutdown
waitUntilShutDown();
assert(isShutDown());
if(mpFrameData)
{
delete[] mpFrameData;
mpFrameData = NULL;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer end");
};
virtual UtlBoolean start(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start start");
// start the task
UtlBoolean result = OsServerTask::start();
OsTime noDelay(0, 0);
int microSecondsPerFrame =
(mSamplesPerFrame * 1000000 / mSamplesPerSecond) -
mUnderOverRunTime;
assert(microSecondsPerFrame > 0);
OsTime framePeriod(0, microSecondsPerFrame);
// Start re-occurring timer which causes handleMessage to be called
// periodically
mTimer.periodicEvery(noDelay, framePeriod);
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start end");
return(result);
};
virtual void requestShutdown(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown start");
// Stop the timer first so it stops queuing messages
mTimer.stop();
// Then stop the server task
OsServerTask::requestShutdown();
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown end");
};
UtlBoolean handleMessage(OsMsg& rMsg)
{
#ifdef RTL_ENABLED
RTL_BLOCK("MpSineWaveGeneratorServer.handleMessage");
#endif
// Build a frame of signal and push it to the device manager
assert(mpFrameData);
for(unsigned int frameIndex = 0; frameIndex < mSamplesPerFrame; frameIndex++)
{
mpFrameData[frameIndex] =
MpSineWaveGeneratorDeviceDriver::calculateSample(mNextFrameTime,
mMagnatude,
mSinePeriodMicroseconds,
frameIndex,
mSamplesPerFrame,
mSamplesPerSecond);
}
mpInputDeviceManager->pushFrame(mDeviceId,
mSamplesPerFrame,
mpFrameData,
mNextFrameTime);
mNextFrameTime += mSamplesPerFrame * 1000 / mSamplesPerSecond;
return(TRUE);
}
private:
MpFrameTime mNextFrameTime;
unsigned int mSamplesPerFrame;
unsigned int mSamplesPerSecond;
unsigned int mMagnatude;
unsigned int mSinePeriodMicroseconds;
int mUnderOverRunTime;
MpInputDeviceHandle mDeviceId;
MpInputDeviceManager* mpInputDeviceManager;
MpAudioSample* mpFrameData;
OsTimer mTimer;
};
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
MpSineWaveGeneratorDeviceDriver::MpSineWaveGeneratorDeviceDriver(const UtlString& name,
MpInputDeviceManager& deviceManager,
unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
: MpInputDeviceDriver(name, deviceManager),
mMagnitude(magnitude),
mPeriodInMicroseconds(periodInMicroseconds),
mUnderOverRunTime(underOverRunTime),
mpReaderTask(NULL)
{
}
// Destructor
MpSineWaveGeneratorDeviceDriver::~MpSineWaveGeneratorDeviceDriver()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver start");
if(mpReaderTask)
{
OsStatus stat = disableDevice();
assert(stat == OS_SUCCESS);
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver end");
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpSineWaveGeneratorDeviceDriver::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice start");
OsStatus result = OS_INVALID;
assert(mpReaderTask == NULL);
if(mpReaderTask == NULL)
{
mpReaderTask =
new MpSineWaveGeneratorServer(currentFrameTime,
samplesPerFrame,
samplesPerSec,
mMagnitude,
mPeriodInMicroseconds,
mUnderOverRunTime,
getDeviceId(),
*mpInputDeviceManager);
if(mpReaderTask->start())
{
result = OS_SUCCESS;
mIsEnabled = TRUE;
}
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice end");
return(result);
}
OsStatus MpSineWaveGeneratorDeviceDriver::disableDevice()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice start");
OsStatus result = OS_TASK_NOT_STARTED;
//assert(mpReaderTask);
if(mpReaderTask)
{
mpReaderTask->requestShutdown();
delete mpReaderTask;
mpReaderTask = NULL;
result = OS_SUCCESS;
mIsEnabled = FALSE;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice end");
return(result);
}
/* ============================ ACCESSORS ================================= */
MpAudioSample
MpSineWaveGeneratorDeviceDriver::calculateSample(MpFrameTime frameStartTime,
unsigned int magnitude,
unsigned int periodInMicroseconds,
unsigned int frameSampleIndex,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond)
{
double time = ((frameStartTime + frameSampleIndex * 1000.0 / (double) samplesPerSecond)
/ ((double) periodInMicroseconds) * 1000.0 ) * 2.0 * M_PI;
MpAudioSample sample = (MpAudioSample)(sin(time) * (double)magnitude);
return(sample);
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<|endoftext|> |
<commit_before>#include "physics/n_body_system.hpp"
#include <memory>
#include <string>
#include "geometry/grassmann.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/body.hpp"
#include "physics/frame.hpp"
using principia::geometry::Vector;
namespace principia {
namespace physics {
class NBodySystemTest : public testing::Test {
protected:
void SetUp() override {
integrator_.Initialize(integrator_.Order5Optimal());
// The Earth-Moon system, roughly.
body1_ = new Body<InertialFrame>(6E24 * Mass::SIUnit());
body2_ = new Body<InertialFrame>(7E22 * Mass::SIUnit());
Vector<Length, InertialFrame> q1({0 * Length::SIUnit(),
0 * Length::SIUnit(),
0 * Length::SIUnit()});
Vector<Length, InertialFrame> q2({0 * Length::SIUnit(),
4E8 * Length::SIUnit(),
0 * Length::SIUnit()});
Vector<Speed, InertialFrame> p1({0 * Speed::SIUnit(),
0 * Speed::SIUnit(),
0 * Speed::SIUnit()});
//TODO(phl): Despite the name, this wants a speed...
Vector<Speed, InertialFrame> p2({1E3 * Speed::SIUnit(),
0 * Speed::SIUnit(),
0 * Speed::SIUnit()});
body1_->AppendToTrajectory({q1}, {p1}, {0 * Time::SIUnit()});
body2_->AppendToTrajectory({q2}, {p2}, {0 * Time::SIUnit()});
system_.reset(new NBodySystem(
new std::vector<Body<InertialFrame>*>({body1_, body2_})));
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(Vector<Scalar, Frame> const& vector) {
R3Element<Scalar> const& coordinates = vector.coordinates();
std::string result = "{";
result += quantities::ToString(coordinates.x);
result += ",";
result += quantities::ToString(coordinates.y);
result += ",";
result += quantities::ToString(coordinates.z);
result += "}";
return result;
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(
std::vector<Vector<Scalar, Frame>> const& vectors) {
static std::string const mathematica_line =
"(*****************************************************)";
std::string result = mathematica_line + "\n";
result += "ToExpression[StringReplace[\"\n{";
std::string separator = "";
for (const auto& vector : vectors) {
result += separator;
result += ToMathematicaString(vector);
separator = ",\n";
}
result +=
"}\",\n{\" m\"->\"\",\"e\"->\"*^\", \"\\n\"->\"\", \" \"->\"\"}]];\n";
result += mathematica_line;
return result;
}
Body<InertialFrame>* body1_;
Body<InertialFrame>* body2_;
SPRKIntegrator integrator_;
std::unique_ptr<NBodySystem> system_;
};
TEST_F(NBodySystemTest, T) {
std::vector<Vector<Length, InertialFrame>> positions;
std::vector<Vector<Speed, InertialFrame>> momenta;
std::vector<Time> times;
system_->Integrate(integrator_, 3E6 * Time::SIUnit(), 3E4 * Time::SIUnit(), 1);
body1_->GetTrajectory(&positions, &momenta, ×);
LOG(ERROR) << ToMathematicaString(positions);
body2_->GetTrajectory(&positions, &momenta, ×);
LOG(ERROR) << ToMathematicaString(positions);
}
} // namespace physics
} // namespace principia<commit_msg>Trying to understand the 2-body problem.<commit_after>#include "physics/n_body_system.hpp"
#include <memory>
#include <string>
#include "geometry/grassmann.hpp"
#include "geometry/point.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/body.hpp"
#include "physics/frame.hpp"
#include "quantities/constants.hpp"
#include "quantities/numbers.hpp"
using principia::constants::GravitationalConstant;
using principia::geometry::Barycentre;
using principia::geometry::Point;
using principia::geometry::Vector;
namespace principia {
namespace physics {
class NBodySystemTest : public testing::Test {
protected:
void SetUp() override {
integrator_.Initialize(integrator_.Order5Optimal());
// The Earth-Moon system, roughly.
body1_ = new Body<InertialFrame>(6E24 * Mass::SIUnit());
body2_ = new Body<InertialFrame>(7E22 * Mass::SIUnit());
Point<Vector<Length, InertialFrame>> const
q1(Vector<Length, InertialFrame>({0 * Length::SIUnit(),
0 * Length::SIUnit(),
0 * Length::SIUnit()}));
Point<Vector<Length, InertialFrame>> const
q2(Vector<Length, InertialFrame>({0 * Length::SIUnit(),
4E8 * Length::SIUnit(),
0 * Length::SIUnit()}));
Point<Vector<Length, InertialFrame>> const centre_of_mass =
Barycentre(q1, body1_->mass(), q2, body2_->mass());
Point<Vector<Speed, InertialFrame>> const
v1(Vector<Speed, InertialFrame>({0 * Speed::SIUnit(),
0 * Speed::SIUnit(),
0 * Speed::SIUnit()}));
// 1E3 m/s puts us at the apogee at the beginning, because the speed for a
// circular orbit with this separation would be 1006.36 m/s.
Point<Vector<Speed, InertialFrame>> const
v2(Vector<Speed, InertialFrame>({1E3 * Speed::SIUnit(),
0 * Speed::SIUnit(),
0 * Speed::SIUnit()}));
Point<Vector<Speed, InertialFrame>> const overall_velocity =
Barycentre(v1, body1_->mass(), v2, body2_->mass());
body1_->AppendToTrajectory({q1 - centre_of_mass},
{v1 - overall_velocity},
{0 * Time::SIUnit()});
body2_->AppendToTrajectory({q2 - centre_of_mass},
{v2 - overall_velocity},
{0 * Time::SIUnit()});
Length const r2 = (q2 - centre_of_mass).Norm();
Length const semi_major_axis =
1 / (2 / r2 -
(v2 - overall_velocity).Norm().Pow<2>() /
(body1_->gravitational_parameter() +
body2_->gravitational_parameter()));
Length const r1 = (q1 - centre_of_mass).Norm();
Length const semi_major_axis1 =
1 / (2 / r1 -
(v1 - overall_velocity).Norm().Pow<2>() /
(body1_->gravitational_parameter() +
body2_->gravitational_parameter()));
LOG(ERROR)<<semi_major_axis<<" "<<semi_major_axis1;
period_ = 2 * π * Sqrt(
(semi_major_axis1 + semi_major_axis).Pow<3>() /
(GravitationalConstant * (body1_->mass() + body2_->mass())));
system_.reset(new NBodySystem(
new std::vector<Body<InertialFrame>*>({body1_, body2_})));
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(Vector<Scalar, Frame> const& vector) {
R3Element<Scalar> const& coordinates = vector.coordinates();
std::string result = "{";
result += quantities::ToString(coordinates.x);
result += ",";
result += quantities::ToString(coordinates.y);
result += ",";
result += quantities::ToString(coordinates.z);
result += "}";
return result;
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(
std::vector<Vector<Scalar, Frame>> const& vectors) {
static std::string const mathematica_line =
"(*****************************************************)";
std::string result = mathematica_line + "\n";
result += "ToExpression[StringReplace[\"\n{";
std::string separator = "";
for (const auto& vector : vectors) {
result += separator;
result += ToMathematicaString(vector);
separator = ",\n";
}
result +=
"}\",\n{\" m\"->\"\",\"e\"->\"*^\", \"\\n\"->\"\", \" \"->\"\"}]];\n";
result += mathematica_line;
return result;
}
Body<InertialFrame>* body1_;
Body<InertialFrame>* body2_;
SPRKIntegrator integrator_;
Time period_;
std::unique_ptr<NBodySystem> system_;
};
TEST_F(NBodySystemTest, T) {
std::vector<Vector<Length, InertialFrame>> positions;
std::vector<Vector<Speed, InertialFrame>> momenta;
std::vector<Time> times;
LOG(ERROR)<<period_;
system_->Integrate(integrator_, 1.1*period_, period_ / 1000, 1);
body1_->GetTrajectory(&positions, &momenta, ×);
LOG(ERROR) << ToMathematicaString(positions);
body2_->GetTrajectory(&positions, &momenta, ×);
LOG(ERROR) << ToMathematicaString(positions);
}
} // namespace physics
} // namespace principia<|endoftext|> |
<commit_before><commit_msg>Create 1189 - Left Area.cpp<commit_after><|endoftext|> |
<commit_before>#include "BombDefender.h"
#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>
#include <VBO.h>
#include <OpenGLTexture.h>
using namespace std;
using namespace gpufw;
std::shared_ptr<canvas::Context> context;
int positionX = 120;
int positionY = 120;
std::shared_ptr<canvas::Surface> yoSurface;
std::shared_ptr<canvas::OpenGLTexture> texture;
bool BombDefender::Init() {
test_program = std::shared_ptr<gpufw::shader_program>(new gpufw::shader_program);
test_program->loadShaders(getPlatform().getGLSLVersion(), "simple_sprite_shader.glsl");
test_program->bindAttribLocation(0, "a_texCoord");
test_program->bindAttribLocation(1, "a_position");
test_program->link();
auto contextF = getPlatform().createContextFactory();
context = contextF->createContext(256, 256, canvas::InternalFormat::RGBA8, true);
context->globalAlpha = 1.0f;
context->font.size = 50;
context->textBaseline = "top";
yoSurface = context->createSurface("picture.jpg");
context->drawImage(*yoSurface, 0, 0, 256, 256);
texture = std::shared_ptr<canvas::OpenGLTexture>(new canvas::OpenGLTexture(context->getDefaultSurface()));
}
void BombDefender::onDraw() {
Sprite sprite;
drawSprite(sprite);
// auto contextF = getPlatform().createContextFactory();
// context = contextF->createContext(500, 500, canvas::InternalFormat::RGBA8, true);
//
// context->globalAlpha = 1.0f;
// context->font.size = 50;
// context->textBaseline = "top";
// yoSurface = context->createSurface("picture.jpg");
//
// context->drawImage(*yoSurface, positionX, positionY, 200, 200);
// positionX--;
// positionY--;
// __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Application ondraw");
// dynamic_cast<AndroidPlatform&>(getPlatform()).showCanvas(dynamic_cast<canvas::ContextAndroid&>(*context));
}
void BombDefender::drawSprite(const Sprite & sprite){
glm::mat4 projMat = glm::ortho(0.0f, 640.0f, 0.0f, 480.0f, -1000.0f, +1000.0f);
glm::mat4 mat(1.0f);
use(*test_program);
test_program->setUniform("proj_mv_matrix", projMat * mat);
test_program->setUniform("s_texture", 0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_FALSE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->getTextureId());
VBO vbo;
vbo.quad2d(10.0f, 10.0f,
500.0f, 10.0f,
500.0f, 500.0f,
10.0f, 500.0f);
bind(vbo);
// __android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender vertexBufferId id: %d", vbo.getVertexBufferId());
// __android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender IndexBufferId id: %d", vbo.getIndexBufferId());
vbo.draw();
glBindTexture(GL_TEXTURE_2D, 0);
}
void BombDefender::onShutdown() {
}
void
BombDefender::use(const gpufw::shader_program & program) {
int id = program.getProgramObjectId();
// __android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender use id: %d", id);
if (!id) {
assert(0);
}
glUseProgram(id);
}
void
BombDefender::bind(const VBO & vbo) {
if (vbo.hasVertexArrayObjects()) {
assert(vbo.getVertexArrayId());
glBindVertexArray(vbo.getVertexArrayId());
} else {
assert(vbo.getVertexBufferId() && vbo.getIndexBufferId());
glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId());
vbo.setPointers();
}
}
std::shared_ptr<BombDefender> application;
void applicationMain(FWPlatformBase * platform) {
application = std::make_shared<BombDefender>(platform);
platform->setApplication(application.get());
}
<commit_msg>Add texture nullcheck<commit_after>#include "BombDefender.h"
#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>
#include <VBO.h>
#include <OpenGLTexture.h>
using namespace std;
using namespace gpufw;
std::shared_ptr<canvas::Context> context;
int positionX = 120;
int positionY = 120;
std::shared_ptr<canvas::Surface> yoSurface;
std::shared_ptr<canvas::OpenGLTexture> texture;
bool BombDefender::Init() {
test_program = std::shared_ptr<gpufw::shader_program>(new gpufw::shader_program);
test_program->loadShaders(getPlatform().getGLSLVersion(), "simple_sprite_shader.glsl");
test_program->bindAttribLocation(0, "a_texCoord");
test_program->bindAttribLocation(1, "a_position");
test_program->link();
auto contextF = getPlatform().createContextFactory();
context = contextF->createContext(256, 256, canvas::InternalFormat::RGBA8, true);
context->globalAlpha = 1.0f;
context->font.size = 50;
context->textBaseline = "top";
yoSurface = context->createSurface("picture.jpg");
context->drawImage(*yoSurface, 0, 0, 256, 256);
texture = std::shared_ptr<canvas::OpenGLTexture>(new canvas::OpenGLTexture(context->getDefaultSurface()));
}
void BombDefender::onDraw() {
if (texture.get() == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Texture is null");
}
Sprite sprite;
drawSprite(sprite);
// auto contextF = getPlatform().createContextFactory();
// context = contextF->createContext(500, 500, canvas::InternalFormat::RGBA8, true);
//
// context->globalAlpha = 1.0f;
// context->font.size = 50;
// context->textBaseline = "top";
// yoSurface = context->createSurface("picture.jpg");
//
// context->drawImage(*yoSurface, positionX, positionY, 200, 200);
// positionX--;
// positionY--;
// __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Application ondraw");
// dynamic_cast<AndroidPlatform&>(getPlatform()).showCanvas(dynamic_cast<canvas::ContextAndroid&>(*context));
}
void BombDefender::drawSprite(const Sprite & sprite){
glm::mat4 projMat = glm::ortho(0.0f, 640.0f, 0.0f, 480.0f, -1000.0f, +1000.0f);
glm::mat4 mat(1.0f);
use(*test_program);
test_program->setUniform("proj_mv_matrix", projMat * mat);
test_program->setUniform("s_texture", 0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_FALSE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->getTextureId());
VBO vbo;
vbo.quad2d(10.0f, 10.0f,
500.0f, 10.0f,
500.0f, 500.0f,
10.0f, 500.0f);
bind(vbo);
// __android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender texture id: %d", texture->getTextureId());
// __android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender IndexBufferId id: %d", vbo.getIndexBufferId());
vbo.draw();
glBindTexture(GL_TEXTURE_2D, 0);
}
void BombDefender::onShutdown() {
}
void
BombDefender::use(const gpufw::shader_program & program) {
int id = program.getProgramObjectId();
// __android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender use id: %d", id);
if (!id) {
assert(0);
}
glUseProgram(id);
}
void
BombDefender::bind(const VBO & vbo) {
if (vbo.hasVertexArrayObjects()) {
assert(vbo.getVertexArrayId());
glBindVertexArray(vbo.getVertexArrayId());
} else {
assert(vbo.getVertexBufferId() && vbo.getIndexBufferId());
glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId());
vbo.setPointers();
}
}
std::shared_ptr<BombDefender> application;
void applicationMain(FWPlatformBase * platform) {
application = std::make_shared<BombDefender>(platform);
platform->setApplication(application.get());
}
<|endoftext|> |
<commit_before>#include "threads.h"
#include "console.h"
#include "memory.h"
#include "pen_string.h"
#include <pthread.h>
#include <fcntl.h>
#include <semaphore.h>
#include <unistd.h>
namespace pen
{
typedef struct thread
{
pthread_t handle;
} thread;
typedef struct mutex
{
pthread_mutex_t handle;
} mutex;
typedef struct semaphore
{
sem_t* handle;
} semaphore;
u32 semaphone_index = 0;
pen::thread* thread_create(PEN_THREAD_ROUTINE(thread_func), u32 stack_size, void* thread_params, thread_start_flags flags)
{
// allocate penthread handle
pen::thread* new_thread = (pen::thread*)pen::memory_alloc(sizeof(pen::thread));
// create the thread using posix
pthread_attr_t attr;
int err;
int thread_err;
err = pthread_attr_init(&attr);
assert(!err);
err = pthread_attr_setdetachstate(&attr, flags);
assert(!err);
thread_err = pthread_create(&new_thread->handle, &attr, thread_func, thread_params);
err = pthread_attr_destroy(&attr);
assert(!err);
assert(!thread_err);
return new_thread;
}
void thread_destroy(pen::thread* p_thread)
{
pthread_cancel(p_thread->handle);
pen::memory_free(p_thread);
}
pen::mutex* thread_mutex_create()
{
pen::mutex* new_mutex = (pen::mutex*)pen::memory_alloc(sizeof(pen::mutex));
int err;
pthread_mutexattr_t mta;
err = pthread_mutexattr_init(&mta);
err = pthread_mutex_init(&new_mutex->handle, &mta);
return new_mutex;
}
void thread_mutex_destroy(mutex* p_mutex)
{
pthread_mutex_destroy(&p_mutex->handle);
pen::memory_free(p_mutex);
}
void thread_mutex_lock(mutex* p_mutex)
{
pthread_mutex_lock(&p_mutex->handle);
}
u32 thread_mutex_try_lock(mutex* p_mutex)
{
int err = pthread_mutex_trylock(&p_mutex->handle);
return err == 0;
}
void thread_mutex_unlock(mutex* p_mutex)
{
pthread_mutex_unlock(&p_mutex->handle);
}
pen::semaphore* thread_semaphore_create(u32 initial_count, u32 max_count)
{
pen::semaphore* new_semaphore = (pen::semaphore*)pen::memory_alloc(sizeof(pen::semaphore));
char name_buf[16];
pen::string_format(&name_buf[0], 32, "sem%i", semaphone_index++);
sem_unlink(name_buf);
new_semaphore->handle = sem_open(name_buf, O_CREAT, 0, 0);
assert(!(new_semaphore->handle == (void*)-1));
return new_semaphore;
}
void thread_semaphore_destroy(semaphore* p_semaphore)
{
sem_close(p_semaphore->handle);
pen::memory_free(p_semaphore);
}
bool thread_semaphore_wait(semaphore* p_semaphore)
{
sem_wait(p_semaphore->handle);
return true;
}
bool thread_semaphore_try_wait(pen::semaphore* p_semaphore)
{
if (sem_trywait(p_semaphore->handle) == 0)
{
return true;
}
return false;
}
void thread_semaphore_signal(semaphore* p_semaphore, u32 count)
{
sem_post(p_semaphore->handle);
}
void thread_sleep_ms(u32 milliseconds)
{
usleep(milliseconds * 1000);
}
void thread_sleep_us(u32 microseconds)
{
usleep(microseconds);
}
} // namespace pen
<commit_msg>change struct decls<commit_after>#include "threads.h"
#include "console.h"
#include "memory.h"
#include "pen_string.h"
#include <pthread.h>
#include <fcntl.h>
#include <semaphore.h>
#include <unistd.h>
namespace pen
{
struct thread
{
pthread_t handle;
};
struct mutex
{
pthread_mutex_t handle;
};
struct semaphore
{
sem_t* handle;
};
u32 semaphone_index = 0;
pen::thread* thread_create(PEN_THREAD_ROUTINE(thread_func), u32 stack_size, void* thread_params, thread_start_flags flags)
{
// allocate penthread handle
pen::thread* new_thread = (pen::thread*)pen::memory_alloc(sizeof(pen::thread));
// create the thread using posix
pthread_attr_t attr;
int err;
int thread_err;
err = pthread_attr_init(&attr);
PEN_ASSERT(!err);
err = pthread_attr_setdetachstate(&attr, flags);
PEN_ASSERT(!err);
thread_err = pthread_create(&new_thread->handle, &attr, thread_func, thread_params);
err = pthread_attr_destroy(&attr);
PEN_ASSERT(!err);
PEN_ASSERT(!thread_err);
return new_thread;
}
void thread_destroy(pen::thread* p_thread)
{
pthread_cancel(p_thread->handle);
pen::memory_free(p_thread);
}
pen::mutex* thread_mutex_create()
{
pen::mutex* new_mutex = (pen::mutex*)pen::memory_alloc(sizeof(pen::mutex));
int err;
pthread_mutexattr_t mta;
err = pthread_mutexattr_init(&mta);
err = pthread_mutex_init(&new_mutex->handle, &mta);
return new_mutex;
}
void thread_mutex_destroy(mutex* p_mutex)
{
pthread_mutex_destroy(&p_mutex->handle);
pen::memory_free(p_mutex);
}
void thread_mutex_lock(mutex* p_mutex)
{
pthread_mutex_lock(&p_mutex->handle);
}
u32 thread_mutex_try_lock(mutex* p_mutex)
{
int err = pthread_mutex_trylock(&p_mutex->handle);
return err == 0;
}
void thread_mutex_unlock(mutex* p_mutex)
{
pthread_mutex_unlock(&p_mutex->handle);
}
pen::semaphore* thread_semaphore_create(u32 initial_count, u32 max_count)
{
pen::semaphore* new_semaphore = (pen::semaphore*)pen::memory_alloc(sizeof(pen::semaphore));
c8 name_buf[16];
pen::string_format(&name_buf[0], 32, "sem%i", semaphone_index++);
sem_unlink(name_buf);
new_semaphore->handle = sem_open(name_buf, O_CREAT, 0, 0);
assert(!(new_semaphore->handle == (void*)-1));
return new_semaphore;
}
void thread_semaphore_destroy(semaphore* p_semaphore)
{
sem_close(p_semaphore->handle);
pen::memory_free(p_semaphore);
}
bool thread_semaphore_wait(semaphore* p_semaphore)
{
sem_wait(p_semaphore->handle);
return true;
}
bool thread_semaphore_try_wait(pen::semaphore* p_semaphore)
{
if (sem_trywait(p_semaphore->handle) == 0)
return true;
return false;
}
void thread_semaphore_signal(semaphore* p_semaphore, u32 count)
{
sem_post(p_semaphore->handle);
}
void thread_sleep_ms(u32 milliseconds)
{
usleep(milliseconds * 1000);
}
void thread_sleep_us(u32 microseconds)
{
usleep(microseconds);
}
} // namespace pen
<|endoftext|> |
<commit_before>/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author Yurii Shyrma ([email protected]), created on 04.06.2018
//
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/axis.h>
#include <ops/declarable/helpers/reductions.h>
#if NOT_EXCLUDED(OP_reduce_variance)
namespace sd {
namespace ops {
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(reduce_variance, -1, 1, false, 0, 0) {
auto input = INPUT_VARIABLE(0);
auto output = OUTPUT_VARIABLE(0);
bool keepDims = false;//block.getTArguments()->size() > 0 ? (bool)T_ARG(0) : false;
bool biasCorrected = false;//block.getTArguments()->size() > 1 ? (bool)T_ARG(1) : false;
auto dimensions = *block.getIArguments();
if (block.width() > 1) {
auto axesVector = INPUT_VARIABLE(1);
helpers::adjustAxis(input->rankOf(), axesVector, dimensions);
}
if (block.getBArguments()->size()) {
keepDims = B_ARG(0);
if (block.getBArguments()->size() > 1)
biasCorrected = B_ARG(1);
}
else if (block.getTArguments()->size()) {
keepDims = (bool)T_ARG(0);
if (block.getTArguments()->size() > 1)
biasCorrected = (bool)T_ARG(1);
}
REQUIRE_TRUE(dimensions.size() <= input->rankOf(), 0, "REDUCE_VARIANCE OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions)
REQUIRE_TRUE(item >= -input->rankOf() && item < input->rankOf(), 0, "REDUCE_VARIANCE OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !" , input->rankOf(), input->rankOf(), item);
sd::ops::helpers::variance(*input, *output, dimensions, biasCorrected);
return Status::OK();
}
DECLARE_SHAPE_FN(reduce_variance) {
bool keepDims = false;//block.getTArguments()->size() > 0 ? (bool)T_ARG(0) : false;
auto dimensions = *block.getIArguments();
if (block.width() > 1) {
auto axesVector = INPUT_VARIABLE(1);
helpers::adjustAxis(INPUT_VARIABLE(0)->rankOf(), axesVector, dimensions);
}
if (block.getBArguments()->size()) {
keepDims = B_ARG(0);
}
else if (block.getTArguments()->size()) {
keepDims = (bool)T_ARG(0);
}
REQUIRE_TRUE(dimensions.size() <= INPUT_VARIABLE(0)->rankOf(), 0, "REDUCE_VARIANCE OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions)
REQUIRE_TRUE(item >= -inputShape->at(0)[0] && item < inputShape->at(0)[0], 0, "REDUCE_VARIANCE OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !" , inputShape->at(0)[0], inputShape->at(0)[0], item);
auto outShapeInfo = ShapeUtils::evalReduceShapeInfo(shape::order(inputShape->at(0)), dimensions, inputShape->at(0), keepDims, false, block.getWorkspace());
return SHAPELIST(outShapeInfo);
}
DECLARE_TYPES(reduce_variance) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setAllowedOutputTypes({ALL_FLOATS});
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(reduce_variance_bp, -1, 1, false, 0, 0) {
auto input = INPUT_VARIABLE(0);
auto gradO = INPUT_VARIABLE(1);
auto gradI = OUTPUT_VARIABLE(0);
bool keepDims = false;//block.getTArguments()->size() > 0 ? (bool)T_ARG(0) : false;
bool biasCorrected = false;//block.getTArguments()->size() > 1 ? (bool)T_ARG(1) : false;
auto dimensions = *block.getIArguments();
if (block.width() > 2) {
auto axesVector = INPUT_VARIABLE(2);
helpers::adjustAxis(input->rankOf(), axesVector, dimensions);
nd4j_debug("Shape of axes vector for reduce_variance_bp %d\n",0);
axesVector->printShapeInfo();
}
if (block.getBArguments()->size()) {
keepDims = B_ARG(0);
if (block.getBArguments()->size() > 1)
biasCorrected = B_ARG(1);
}
else if (block.getTArguments()->size()) {
keepDims = (bool)T_ARG(0);
if (block.getTArguments()->size() > 1)
biasCorrected = (bool)T_ARG(1);
}
REQUIRE_TRUE(dimensions.size() <= input->rankOf(), 0, "REDUCE_VARIANCE_BP OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions) {
REQUIRE_TRUE(item >= -input->rankOf() && item < input->rankOf(), 0,
"REDUCE_VARIANCE_BP OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !",
input->rankOf(), input->rankOf(), item);
nd4j_debug("Dimension item is %d\n",item);
}
const Nd4jLong N = input->lengthOf() / gradO->lengthOf();
const Nd4jLong NminusOne = biasCorrected ? N - 1 : N;
const double factor1 = 2.0 / NminusOne;
const double factor2 = 2.0 / (N * NminusOne);
nd4j_debug("Before mean in variance bp %d\n",0);
auto mean = input->reduceAlongDimension(reduce::Mean, dimensions, true);
nd4j_debug("After mean in variance bp %d\n",0);
gradI->assign( (*input - mean) * (2.0f / NminusOne)); // automatic broadcasting happens here
nd4j_debug("After assign in variance bp %d\n",0);
if(!keepDims) {
nd4j_debug("In not keep dims reduce variance bp %d\n",0);
auto gradOShapeKeepDims = ShapeUtils::evalReduceShapeInfo(gradO->ordering(), dimensions, *input, true, false, block.getWorkspace());
*gradI *= gradO->reshape(gradO->ordering(), ShapeUtils::pullShapeFromShapeInfo(gradOShapeKeepDims)); // for example could be something like [a,b] -> [1,a,1,b]
nd4j_debug("After not keep dims reduce variance bp %d\n",0);
} else
*gradI *= *gradO; // automatic broadcasting happens here
return Status::OK();
}
DECLARE_SHAPE_FN(reduce_variance_bp) {
auto in = inputShape->at(0);
auto rank = shape::rank(in);
auto dimensions = *block.getIArguments();
if (block.width() > 2) {
auto axesVector = INPUT_VARIABLE(2);
helpers::adjustAxis(rank, axesVector, dimensions);
}
REQUIRE_TRUE(dimensions.size() <= rank, 0, "REDUCE_VARIANCE_BP OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions)
REQUIRE_TRUE(item >= -inputShape->at(0)[0] && item < inputShape->at(0)[0], 0, "REDUCE_VARIANCE_BP OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !" , inputShape->at(0)[0], inputShape->at(0)[0], item);
Nd4jLong* gradIshapeInfo(nullptr);
COPY_SHAPE(in, gradIshapeInfo);
return SHAPELIST(CONSTANT(gradIshapeInfo));
}
DECLARE_TYPES(reduce_variance_bp) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setAllowedOutputTypes({ALL_FLOATS});
}
}
}
#endif
<commit_msg>Remove debug statements<commit_after>/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author Yurii Shyrma ([email protected]), created on 04.06.2018
//
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/axis.h>
#include <ops/declarable/helpers/reductions.h>
#if NOT_EXCLUDED(OP_reduce_variance)
namespace sd {
namespace ops {
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(reduce_variance, -1, 1, false, 0, 0) {
auto input = INPUT_VARIABLE(0);
auto output = OUTPUT_VARIABLE(0);
bool keepDims = false;//block.getTArguments()->size() > 0 ? (bool)T_ARG(0) : false;
bool biasCorrected = false;//block.getTArguments()->size() > 1 ? (bool)T_ARG(1) : false;
auto dimensions = *block.getIArguments();
if (block.width() > 1) {
auto axesVector = INPUT_VARIABLE(1);
helpers::adjustAxis(input->rankOf(), axesVector, dimensions);
}
if (block.getBArguments()->size()) {
keepDims = B_ARG(0);
if (block.getBArguments()->size() > 1)
biasCorrected = B_ARG(1);
}
else if (block.getTArguments()->size()) {
keepDims = (bool)T_ARG(0);
if (block.getTArguments()->size() > 1)
biasCorrected = (bool)T_ARG(1);
}
REQUIRE_TRUE(dimensions.size() <= input->rankOf(), 0, "REDUCE_VARIANCE OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions)
REQUIRE_TRUE(item >= -input->rankOf() && item < input->rankOf(), 0, "REDUCE_VARIANCE OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !" , input->rankOf(), input->rankOf(), item);
sd::ops::helpers::variance(*input, *output, dimensions, biasCorrected);
return Status::OK();
}
DECLARE_SHAPE_FN(reduce_variance) {
bool keepDims = false;//block.getTArguments()->size() > 0 ? (bool)T_ARG(0) : false;
auto dimensions = *block.getIArguments();
if (block.width() > 1) {
auto axesVector = INPUT_VARIABLE(1);
helpers::adjustAxis(INPUT_VARIABLE(0)->rankOf(), axesVector, dimensions);
}
if (block.getBArguments()->size()) {
keepDims = B_ARG(0);
}
else if (block.getTArguments()->size()) {
keepDims = (bool)T_ARG(0);
}
REQUIRE_TRUE(dimensions.size() <= INPUT_VARIABLE(0)->rankOf(), 0, "REDUCE_VARIANCE OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions)
REQUIRE_TRUE(item >= -inputShape->at(0)[0] && item < inputShape->at(0)[0], 0, "REDUCE_VARIANCE OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !" , inputShape->at(0)[0], inputShape->at(0)[0], item);
auto outShapeInfo = ShapeUtils::evalReduceShapeInfo(shape::order(inputShape->at(0)), dimensions, inputShape->at(0), keepDims, false, block.getWorkspace());
return SHAPELIST(outShapeInfo);
}
DECLARE_TYPES(reduce_variance) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setAllowedOutputTypes({ALL_FLOATS});
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(reduce_variance_bp, -1, 1, false, 0, 0) {
auto input = INPUT_VARIABLE(0);
auto gradO = INPUT_VARIABLE(1);
auto gradI = OUTPUT_VARIABLE(0);
bool keepDims = false;//block.getTArguments()->size() > 0 ? (bool)T_ARG(0) : false;
bool biasCorrected = false;//block.getTArguments()->size() > 1 ? (bool)T_ARG(1) : false;
auto dimensions = *block.getIArguments();
if (block.width() > 2) {
auto axesVector = INPUT_VARIABLE(2);
helpers::adjustAxis(input->rankOf(), axesVector, dimensions);
axesVector->printShapeInfo();
}
if (block.getBArguments()->size()) {
keepDims = B_ARG(0);
if (block.getBArguments()->size() > 1)
biasCorrected = B_ARG(1);
}
else if (block.getTArguments()->size()) {
keepDims = (bool)T_ARG(0);
if (block.getTArguments()->size() > 1)
biasCorrected = (bool)T_ARG(1);
}
REQUIRE_TRUE(dimensions.size() <= input->rankOf(), 0, "REDUCE_VARIANCE_BP OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions) {
REQUIRE_TRUE(item >= -input->rankOf() && item < input->rankOf(), 0,
"REDUCE_VARIANCE_BP OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !",
input->rankOf(), input->rankOf(), item);
nd4j_debug("Dimension item is %d\n",item);
}
const Nd4jLong N = input->lengthOf() / gradO->lengthOf();
const Nd4jLong NminusOne = biasCorrected ? N - 1 : N;
const double factor1 = 2.0 / NminusOne;
const double factor2 = 2.0 / (N * NminusOne);
auto mean = input->reduceAlongDimension(reduce::Mean, dimensions, true);
gradI->assign( (*input - mean) * (2.0f / NminusOne)); // automatic broadcasting happens here
if(!keepDims) {
auto gradOShapeKeepDims = ShapeUtils::evalReduceShapeInfo(gradO->ordering(), dimensions, *input, true, false, block.getWorkspace());
*gradI *= gradO->reshape(gradO->ordering(), ShapeUtils::pullShapeFromShapeInfo(gradOShapeKeepDims)); // for example could be something like [a,b] -> [1,a,1,b]
} else
*gradI *= *gradO; // automatic broadcasting happens here
return Status::OK();
}
DECLARE_SHAPE_FN(reduce_variance_bp) {
auto in = inputShape->at(0);
auto rank = shape::rank(in);
auto dimensions = *block.getIArguments();
if (block.width() > 2) {
auto axesVector = INPUT_VARIABLE(2);
helpers::adjustAxis(rank, axesVector, dimensions);
}
REQUIRE_TRUE(dimensions.size() <= rank, 0, "REDUCE_VARIANCE_BP OP: the number of dimensions to reduce along must be <= input array rank, but got %i instead" , dimensions.size());
for(const auto& item : dimensions)
REQUIRE_TRUE(item >= -inputShape->at(0)[0] && item < inputShape->at(0)[0], 0, "REDUCE_VARIANCE_BP OP: the input dimension to reduce along must be in range [-%i, %i), but got %i instead !" , inputShape->at(0)[0], inputShape->at(0)[0], item);
Nd4jLong* gradIshapeInfo(nullptr);
COPY_SHAPE(in, gradIshapeInfo);
return SHAPELIST(CONSTANT(gradIshapeInfo));
}
DECLARE_TYPES(reduce_variance_bp) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setAllowedOutputTypes({ALL_FLOATS});
}
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef ROADNET_H
#define ROADNET_H
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
#include <Eigen/Dense>
/** Road network description
This class serves a similar purpose to the class RoadNetwork in
dubins_traffic.py of the fmrb Python package. However, this is considered the
reference implementation.
\ingroup dubins_traffic
*/
class RoadNetwork
{
public:
/** Create RoadNetwork that is 4-connected grid of size (shape0, shape1). */
RoadNetwork( double length_,
const Eigen::Vector3d &transform_,
int shape0, int shape1 );
/** Create RoadNetwork from a description in a JSON container.
segments is not yet implemented. Thus, until then, it is only possible
to define a 4-connected grid using shape.
*/
RoadNetwork( std::istream &rndjson );
/** Output in RND format using JSON container to given stream. */
friend std::ostream & operator<<( std::ostream &out, const RoadNetwork &rd );
private:
void populate_4grid( int shape0, int shape1 );
private:
int version;
double length;
Eigen::Vector3d transform;
std::vector<Eigen::Vector4d> segments;
std::vector<int> shape;
};
void RoadNetwork::populate_4grid( int shape0, int shape1 )
{
assert( shape0 >= 1 && shape1 >= 1 );
for (int x = 0; x < shape1-1; x++) {
for (int y = 0; y < shape0-1; y++) {
segments.push_back( Eigen::Vector4d( x, y, x+1, y ) );
segments.push_back( Eigen::Vector4d( x, y, x, y+1 ) );
}
}
for (int x = 0; x < shape1-1; x++)
segments.push_back( Eigen::Vector4d( x, shape0-1, x+1, shape0-1 ) );
for (int y = 0; y < shape0-1; y++)
segments.push_back( Eigen::Vector4d( shape1-1, y, shape1-1, y+1 ) );
}
RoadNetwork::RoadNetwork( double length_,
const Eigen::Vector3d &transform_,
int shape0, int shape1 )
: version(0), length(length_), transform(transform_),
shape( {shape0, shape1} )
{
assert( length > 0 );
populate_4grid( shape0, shape1 );
}
RoadNetwork::RoadNetwork( std::istream &rndjson )
: version(-1), length(1.0), transform(0.0, 0.0, 0.0),
shape( {2, 2} )
{
enum state {waiting, rd_version, rd_length, rd_transform, rd_segments, rd_shape};
state parser = waiting;
std::string buf;
std::string rndjson_str;
rndjson >> buf;
while (!rndjson.eof()) {
rndjson_str.append( buf );
rndjson >> buf;
}
size_t pos = 0, nextpos;
while (pos < rndjson_str.size()) {
if (parser == waiting) {
if ((nextpos = rndjson_str.find( "version", pos )) != std::string::npos) {
parser = rd_version;
pos = nextpos + 7;
} else if ((nextpos = rndjson_str.find( "length", pos )) != std::string::npos) {
parser = rd_length;
pos = nextpos + 6;
} else if ((nextpos = rndjson_str.find( "transform", pos )) != std::string::npos) {
parser = rd_transform;
pos = nextpos + 9;
} else if ((nextpos = rndjson_str.find( "shape", pos )) != std::string::npos) {
parser = rd_shape;
pos = nextpos + 5;
} else {
break;
}
} else if (parser == rd_version || parser == rd_length) {
if ((nextpos = rndjson_str.find( ":", pos )) != std::string::npos) {
pos = nextpos + 1;
try {
int parsed_int = std::stoi( rndjson_str.substr( pos ) );
switch (parser) {
case rd_version:
version = parsed_int;
break;
case rd_length:
length = parsed_int;
break;
}
} catch (std::invalid_argument) {
std::cout << "stoi() conversion failed on \""
<< rndjson_str.substr( pos ) << "\"" << std::endl;
}
parser = waiting;
} else {
break;
}
} else if (parser == rd_transform || parser == rd_shape) {
std::vector<double> parsed_numbers;
if ((nextpos = rndjson_str.find( "[", pos )) != std::string::npos) {
pos = nextpos + 1;
while (true) {
try {
parsed_numbers.push_back( std::stod( rndjson_str.substr( pos ) ) );
} catch (std::invalid_argument) {
std::cout << "stod() conversion failed on \""
<< rndjson_str.substr( pos ) << "\"" << std::endl;
}
size_t closingpos = rndjson_str.find( "]", pos );
nextpos = rndjson_str.find( ",", pos );
if (closingpos == std::string::npos) {
break; // Missing ] implies malformed array.
} else if (nextpos != std::string::npos && nextpos < closingpos) {
pos = nextpos + 1;
} else {
pos = closingpos + 1;
break; // Found closing ] implies well-formed array.
}
}
switch (parser) {
case rd_transform:
assert( parsed_numbers.size() == 3 );
for (int idx = 0; idx < parsed_numbers.size(); idx++)
transform(idx) = parsed_numbers.at(idx);
break;
case rd_shape:
assert( parsed_numbers.size() == 2 );
for (int idx = 0; idx < parsed_numbers.size(); idx++)
shape[idx] = parsed_numbers.at(idx);
break;
}
parser = waiting;
} else {
break;
}
} else {
break;
}
}
}
std::ostream & operator<<( std::ostream &out, const RoadNetwork &rd )
{
out << "{ \"version\": " << rd.version << ", ";
out << "\"length\": " << rd.length << ", ";
out << "\"transform\": ["
<< rd.transform(0) << ", " << rd.transform(1) << ", " << rd.transform(2)
<< "], ";
out << "\"shape\": [" << rd.shape[0] << ", " << rd.shape[1] << "], ";
out << "\"segments\": [";
for (int segment_index = 0; segment_index < rd.segments.size(); segment_index++) {
out << "[";
for (int idx = 0; idx < 4; idx++) {
out << rd.segments[segment_index](idx);
if (idx < 3)
out << ", ";
}
out << "]";
if (segment_index < rd.segments.size()-1)
out << ", ";
}
out << "] }";
}
#endif
<commit_msg>Populate segments as 4-grid in constructor using JSON str<commit_after>#ifndef ROADNET_H
#define ROADNET_H
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
#include <Eigen/Dense>
/** Road network description
This class serves a similar purpose to the class RoadNetwork in
dubins_traffic.py of the fmrb Python package. However, this is considered the
reference implementation.
\ingroup dubins_traffic
*/
class RoadNetwork
{
public:
/** Create RoadNetwork that is 4-connected grid of size (shape0, shape1). */
RoadNetwork( double length_,
const Eigen::Vector3d &transform_,
int shape0, int shape1 );
/** Create RoadNetwork from a description in a JSON container.
segments is not yet implemented. Thus, until then, it is only possible
to define a 4-connected grid using shape.
*/
RoadNetwork( std::istream &rndjson );
/** Output in RND format using JSON container to given stream. */
friend std::ostream & operator<<( std::ostream &out, const RoadNetwork &rd );
private:
void populate_4grid( int shape0, int shape1 );
private:
int version;
double length;
Eigen::Vector3d transform;
std::vector<Eigen::Vector4d> segments;
std::vector<int> shape;
};
void RoadNetwork::populate_4grid( int shape0, int shape1 )
{
assert( shape0 >= 1 && shape1 >= 1 );
for (int x = 0; x < shape1-1; x++) {
for (int y = 0; y < shape0-1; y++) {
segments.push_back( Eigen::Vector4d( x, y, x+1, y ) );
segments.push_back( Eigen::Vector4d( x, y, x, y+1 ) );
}
}
for (int x = 0; x < shape1-1; x++)
segments.push_back( Eigen::Vector4d( x, shape0-1, x+1, shape0-1 ) );
for (int y = 0; y < shape0-1; y++)
segments.push_back( Eigen::Vector4d( shape1-1, y, shape1-1, y+1 ) );
}
RoadNetwork::RoadNetwork( double length_,
const Eigen::Vector3d &transform_,
int shape0, int shape1 )
: version(0), length(length_), transform(transform_),
shape( {shape0, shape1} )
{
assert( length > 0 );
populate_4grid( shape0, shape1 );
}
RoadNetwork::RoadNetwork( std::istream &rndjson )
: version(-1), length(1.0), transform(0.0, 0.0, 0.0),
shape( {2, 2} )
{
enum state {waiting, rd_version, rd_length, rd_transform, rd_segments, rd_shape};
state parser = waiting;
std::string buf;
std::string rndjson_str;
rndjson >> buf;
while (!rndjson.eof()) {
rndjson_str.append( buf );
rndjson >> buf;
}
size_t pos = 0, nextpos;
while (pos < rndjson_str.size()) {
if (parser == waiting) {
if ((nextpos = rndjson_str.find( "version", pos )) != std::string::npos) {
parser = rd_version;
pos = nextpos + 7;
} else if ((nextpos = rndjson_str.find( "length", pos )) != std::string::npos) {
parser = rd_length;
pos = nextpos + 6;
} else if ((nextpos = rndjson_str.find( "transform", pos )) != std::string::npos) {
parser = rd_transform;
pos = nextpos + 9;
} else if ((nextpos = rndjson_str.find( "shape", pos )) != std::string::npos) {
parser = rd_shape;
pos = nextpos + 5;
} else {
break;
}
} else if (parser == rd_version || parser == rd_length) {
if ((nextpos = rndjson_str.find( ":", pos )) != std::string::npos) {
pos = nextpos + 1;
try {
int parsed_int = std::stoi( rndjson_str.substr( pos ) );
switch (parser) {
case rd_version:
version = parsed_int;
break;
case rd_length:
length = parsed_int;
break;
}
} catch (std::invalid_argument) {
std::cout << "stoi() conversion failed on \""
<< rndjson_str.substr( pos ) << "\"" << std::endl;
}
parser = waiting;
} else {
break;
}
} else if (parser == rd_transform || parser == rd_shape) {
std::vector<double> parsed_numbers;
if ((nextpos = rndjson_str.find( "[", pos )) != std::string::npos) {
pos = nextpos + 1;
while (true) {
try {
parsed_numbers.push_back( std::stod( rndjson_str.substr( pos ) ) );
} catch (std::invalid_argument) {
std::cout << "stod() conversion failed on \""
<< rndjson_str.substr( pos ) << "\"" << std::endl;
}
size_t closingpos = rndjson_str.find( "]", pos );
nextpos = rndjson_str.find( ",", pos );
if (closingpos == std::string::npos) {
break; // Missing ] implies malformed array.
} else if (nextpos != std::string::npos && nextpos < closingpos) {
pos = nextpos + 1;
} else {
pos = closingpos + 1;
break; // Found closing ] implies well-formed array.
}
}
switch (parser) {
case rd_transform:
assert( parsed_numbers.size() == 3 );
for (int idx = 0; idx < parsed_numbers.size(); idx++)
transform(idx) = parsed_numbers.at(idx);
break;
case rd_shape:
assert( parsed_numbers.size() == 2 );
for (int idx = 0; idx < parsed_numbers.size(); idx++)
shape[idx] = parsed_numbers.at(idx);
break;
}
parser = waiting;
} else {
break;
}
} else {
break;
}
}
assert( length > 0 );
populate_4grid( shape[0], shape[1] );
}
std::ostream & operator<<( std::ostream &out, const RoadNetwork &rd )
{
out << "{ \"version\": " << rd.version << ", ";
out << "\"length\": " << rd.length << ", ";
out << "\"transform\": ["
<< rd.transform(0) << ", " << rd.transform(1) << ", " << rd.transform(2)
<< "], ";
out << "\"shape\": [" << rd.shape[0] << ", " << rd.shape[1] << "], ";
out << "\"segments\": [";
for (int segment_index = 0; segment_index < rd.segments.size(); segment_index++) {
out << "[";
for (int idx = 0; idx < 4; idx++) {
out << rd.segments[segment_index](idx);
if (idx < 3)
out << ", ";
}
out << "]";
if (segment_index < rd.segments.size()-1)
out << ", ";
}
out << "] }";
}
#endif
<|endoftext|> |
<commit_before>/*---------------------------------------------------------------
* Copyright (c) 1999,2000,2001,2002,2003
* The Board of Trustees of the University of Illinois
* All Rights Reserved.
*---------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software (Iperf) 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:
*
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and
* the following disclaimers.
*
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials
* provided with the distribution.
*
*
* Neither the names of the University of Illinois, NCSA,
* nor the names of its contributors may be used to endorse
* or promote products derived from this Software without
* specific prior written permission.
*
* 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 CONTIBUTORS 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.
* ________________________________________________________________
* National Laboratory for Applied Network Research
* National Center for Supercomputing Applications
* University of Illinois at Urbana-Champaign
* http://www.ncsa.uiuc.edu
* ________________________________________________________________
* main.cpp
* by Mark Gates <[email protected]>
* & Ajay Tirumala <[email protected]>
* -------------------------------------------------------------------
* main does initialization and creates the various objects that will
* actually run the iperf program, then waits in the Joinall().
* -------------------------------------------------------------------
* headers
* uses
* <stdlib.h>
* <string.h>
*
* <signal.h>
* ------------------------------------------------------------------- */
#define HEADERS()
#include "headers.h"
#include "Client.hpp"
#include "Settings.hpp"
#include "Listener.hpp"
#include "Speaker.hpp"
#include "Locale.hpp"
#include "Condition.hpp"
#include "List.h"
#include "util.h"
//#include "ocomm/o_log.h"
//#include "oml_orbit_winlab_iperf.h"
extern "C" {
#include <oml2/omlc.h>
#include <oml2/o_log.h>
OmlMP* tcp_measure;
OmlMP* udp_measure;
OmlMP* peer_information;
static OmlMPDef tcp_receiverport[] = {
{"ID", OML_LONG_VALUE},
{"Begin_interval", OML_DOUBLE_VALUE},
{"End_interval", OML_DOUBLE_VALUE},
{"Transfer", OML_STRING_VALUE},
{"Bandwidth", OML_STRING_VALUE},
{NULL, (OmlValueT)0}
};
static OmlMPDef udp_receiverport[] = {
{"ID", OML_LONG_VALUE},
{"Begin_interval", OML_DOUBLE_VALUE},
{"End_interval", OML_DOUBLE_VALUE},
{"Transfer", OML_STRING_VALUE},
{"Bandwidth", OML_STRING_VALUE},
{"Jitter", OML_DOUBLE_VALUE},
{"Packet_Lost", OML_LONG_VALUE},
{"Total_Packet", OML_LONG_VALUE},
{"PLR", OML_DOUBLE_VALUE},
{NULL, (OmlValueT)0}
};
static OmlMPDef peer_info[] = {
{"ID", OML_LONG_VALUE},
{"local_address", OML_STRING_VALUE},
{"local_port", OML_LONG_VALUE},
{"foreign_address", OML_STRING_VALUE},
{"foreign_port", OML_LONG_VALUE},
{NULL, (OmlValueT)0}
};
}
#ifdef WIN32
#include "service.h"
#endif
/* -------------------------------------------------------------------
* prototypes
* ------------------------------------------------------------------- */
void waitUntilQuit( void );
void sig_quit( int inSigno );
void cleanup( void );
/* -------------------------------------------------------------------
* global variables
* ------------------------------------------------------------------- */
#define GLOBAL()
Condition gQuit_cond;
/* -------------------------------------------------------------------
* sets up signal handlers
* parses settings from environment and command line
* starts up server or client thread
* waits for all threads to complete
* ------------------------------------------------------------------- */
int main( int argc, char *argv[] ) {
#ifdef WIN32
SERVICE_TABLE_ENTRY dispatchTable[] =
{
{ TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
{ NULL, NULL}
};
#endif
omlc_init("iperf", &argc, (const char**) argv, NULL);
printf("ADD MP \n");
tcp_measure = omlc_add_mp("TCP_received", tcp_receiverport);
udp_measure = omlc_add_mp("UDP_received", udp_receiverport);
peer_information = omlc_add_mp("Peer_Info", peer_info);
Listener *theListener = NULL;
Speaker *theSpeaker = NULL;
// signal handlers quietly exit on ^C and kill
// these are usually remapped later by the client or server
my_signal( SIGTERM, sig_exit );
my_signal( SIGINT, sig_exit );
#ifndef WIN32
signal(SIGPIPE,SIG_IGN);
#else
WSADATA wsaData;
int rc = WSAStartup( 0x202, &wsaData );
FAIL_errno( rc == SOCKET_ERROR, "WSAStartup" );
SetConsoleCtrlHandler( sig_dispatcher, true );
#endif
// perform any cleanup when quitting Iperf
atexit( cleanup );
ext_Settings* ext_gSettings = new ext_Settings;
Settings* gSettings = NULL;
// read settings from environment variables and command-line interface
gSettings = new Settings( ext_gSettings );
gSettings->ParseEnvironment();
gSettings->ParseCommandLine( argc, argv );
// start up client or server (listener)
if ( gSettings->GetServerMode() == kMode_Server ) {
// start up a listener
printf("OML_START 1\n");
theListener = new Listener( ext_gSettings );
printf("OML_START 2\n");
theListener->DeleteSelfAfterRun();
// Start the server as a daemon
if ( gSettings->GetDaemonMode() == true ) {
#ifdef WIN32
CmdInstallService(argc, argv);
DELETE_PTR( theListener );
DELETE_PTR( gSettings );
return 0;
#else
theListener->runAsDaemon(argv[0],LOG_DAEMON);
#endif
}
#ifdef WIN32
else {
if ( gSettings->GetRemoveService() == true ) {
// remove the service and continue to run as a normal process
if ( CmdRemoveService() ) {
printf("IPerf Service is removed.\n");
DELETE_PTR( theListener );
DELETE_PTR( gSettings );
return 0;
}
} else {
// try to start the service
if ( CmdStartService(argc, argv) ) {
printf("IPerf Service already exists.\n");
DELETE_PTR( theListener );
DELETE_PTR( gSettings );
return 0;
}
}
}
#endif
omlc_start();
theListener->Start();
if ( ext_gSettings->mThreads == 0 ) {
theListener->SetDaemon();
// the listener keeps going; we terminate on user input only
waitUntilQuit();
#ifdef HAVE_THREAD
if ( Thread::NumUserThreads() > 0 ) {
printf( wait_server_threads );
fflush( 0 );
}
#endif
}
} else if ( gSettings->GetServerMode() == kMode_Client ) {
#ifdef HAVE_THREAD
theSpeaker = new Speaker(ext_gSettings);
theSpeaker->OwnSettings();
theSpeaker->DeleteSelfAfterRun();
omlc_start();
theSpeaker->Start();
#else
// If we need to start up a listener do it now
ext_Settings *temp = NULL;
Settings::GenerateListenerSettings( ext_gSettings, &temp );
if ( temp != NULL ) {
theListener = new Listener( temp );
theListener->DeleteSelfAfterRun();
}
Client* theClient = new Client( ext_gSettings );
omlc_start();
theClient->InitiateServer();
theClient->Start();
if ( theListener != NULL ) {
theListener->Start();
}
#endif
} else {
// neither server nor client mode was specified
// print usage and exit
#ifdef WIN32
// starting the service by SCM, there is no arguments will be passed in.
// the arguments will pass into Service_Main entry.
if ( !StartServiceCtrlDispatcher(dispatchTable) )
printf(usage_short, argv[0], argv[0]);
#else
printf( usage_short, argv[0], argv[0] );
#endif
}
// wait for other (client, server) threads to complete
Thread::Joinall();
DELETE_PTR( gSettings ); // modified by qfeng
// all done!
return 0;
} // end main
/* -------------------------------------------------------------------
* Blocks the thread until a quit thread signal is sent
* ------------------------------------------------------------------- */
void waitUntilQuit( void ) {
#ifdef HAVE_THREAD
// signal handlers send quit signal on ^C and kill
gQuit_cond.Lock();
my_signal( SIGTERM, sig_quit );
my_signal( SIGINT, sig_quit );
#ifdef HAVE_USLEEP
// this sleep is a hack to get around an apparent bug? in IRIX
// where pthread_cancel doesn't work unless the thread
// starts up before the gQuit_cand.Wait() call below.
// A better solution is to just use sigwait here, but
// then I have to emulate that for Windows...
usleep( 10 );
#endif
// wait for quit signal
gQuit_cond.Wait();
gQuit_cond.Unlock();
#endif
} // end waitUntilQuit
/* -------------------------------------------------------------------
* Sends a quit thread signal to let the main thread quit nicely.
* ------------------------------------------------------------------- */
void sig_quit( int inSigno ) {
#ifdef HAVE_THREAD
// if we get a second signal after 1/10 second, exit
// some implementations send the signal to all threads, so the 1/10 sec
// allows us to ignore multiple receipts of the same signal
static Timestamp* first = NULL;
if ( first != NULL ) {
Timestamp now;
if ( now.subSec( *first ) > 0.1 ) {
sig_exit( inSigno );
}
} else {
first = new Timestamp();
}
// with threads, send a quit signal
gQuit_cond.Signal();
#else
// without threads, just exit quietly, same as sig_exit()
sig_exit( inSigno );
#endif
} // end sig_quit
/* -------------------------------------------------------------------
* Any necesary cleanup before Iperf quits. Called at program exit,
* either by exit() or terminating main().
* ------------------------------------------------------------------- */
void cleanup( void ) {
#ifdef WIN32
WSACleanup();
#endif
extern Iperf_ListEntry *clients;
Iperf_destroy ( &clients );
} // end cleanup
#ifdef WIN32
/*--------------------------------------------------------------------
* ServiceStart
*
* each time starting the service, this is the entry point of the service.
* Start the service, certainly it is on server-mode
*
*
*-------------------------------------------------------------------- */
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) {
Listener *theListener = NULL;
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_START_PENDING, // service state
NO_ERROR, // exit code
3000) ) // wait hint
goto clean;
ext_Settings* ext_gSettings = new ext_Settings;
Settings *gSettings;
// read settings from passing by StartService
gSettings = new Settings( ext_gSettings );
gSettings->ParseEnvironment();
gSettings->ParseCommandLine( dwArgc, lpszArgv );
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_START_PENDING, // service state
NO_ERROR, // exit code
3000) ) // wait hint
goto clean;
// if needed, redirect the output into a specified file
if ( gSettings->GetFileOutput() ) {
redirect(gSettings->GetOutputFileName());
}
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_START_PENDING, // service state
NO_ERROR, // exit code
3000) ) // wait hint
goto clean;
theListener = new Listener( ext_gSettings );
theListener->Start();
theListener->SetDaemon();
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_RUNNING, // service state
NO_ERROR, // exit code
0) ) // wait hint
goto clean;
// the listener keeps going; we terminate on user input only
waitUntilQuit();
#ifdef HAVE_THREAD
if ( Thread::NumUserThreads() > 0 ) {
printf( wait_server_threads );
fflush( 0 );
}
#endif
clean:
// wait for other (client, server) threads to complete
Thread::Joinall();
DELETE_PTR( theListener );
DELETE_PTR( gSettings ); // modified by qfeng
DELETE_PTR( ext_gSettings ); // modified by qfeng
}
//
// FUNCTION: ServiceStop
//
// PURPOSE: Stops the service
//
// PARAMETERS:
// none
//
// RETURN VALUE:
// none
//
// COMMENTS:
// If a ServiceStop procedure is going to
// take longer than 3 seconds to execute,
// it should spawn a thread to execute the
// stop code, and return. Otherwise, the
// ServiceControlManager will believe that
// the service has stopped responding.
//
VOID ServiceStop() {
#ifdef HAVE_THREAD
gQuit_cond.Signal();
#else
sig_exit(1);
#endif
}
#endif
<commit_msg>Remove some comments in iperf<commit_after>/*---------------------------------------------------------------
* Copyright (c) 1999,2000,2001,2002,2003
* The Board of Trustees of the University of Illinois
* All Rights Reserved.
*---------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software (Iperf) 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:
*
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and
* the following disclaimers.
*
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials
* provided with the distribution.
*
*
* Neither the names of the University of Illinois, NCSA,
* nor the names of its contributors may be used to endorse
* or promote products derived from this Software without
* specific prior written permission.
*
* 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 CONTIBUTORS 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.
* ________________________________________________________________
* National Laboratory for Applied Network Research
* National Center for Supercomputing Applications
* University of Illinois at Urbana-Champaign
* http://www.ncsa.uiuc.edu
* ________________________________________________________________
* main.cpp
* by Mark Gates <[email protected]>
* & Ajay Tirumala <[email protected]>
* -------------------------------------------------------------------
* main does initialization and creates the various objects that will
* actually run the iperf program, then waits in the Joinall().
* -------------------------------------------------------------------
* headers
* uses
* <stdlib.h>
* <string.h>
*
* <signal.h>
* ------------------------------------------------------------------- */
#define HEADERS()
#include "headers.h"
#include "Client.hpp"
#include "Settings.hpp"
#include "Listener.hpp"
#include "Speaker.hpp"
#include "Locale.hpp"
#include "Condition.hpp"
#include "List.h"
#include "util.h"
//#include "ocomm/o_log.h"
//#include "oml_orbit_winlab_iperf.h"
extern "C" {
#include <oml2/omlc.h>
#include <oml2/o_log.h>
OmlMP* tcp_measure;
OmlMP* udp_measure;
OmlMP* peer_information;
static OmlMPDef tcp_receiverport[] = {
{"ID", OML_LONG_VALUE},
{"Begin_interval", OML_DOUBLE_VALUE},
{"End_interval", OML_DOUBLE_VALUE},
{"Transfer", OML_STRING_VALUE},
{"Bandwidth", OML_STRING_VALUE},
{NULL, (OmlValueT)0}
};
static OmlMPDef udp_receiverport[] = {
{"ID", OML_LONG_VALUE},
{"Begin_interval", OML_DOUBLE_VALUE},
{"End_interval", OML_DOUBLE_VALUE},
{"Transfer", OML_STRING_VALUE},
{"Bandwidth", OML_STRING_VALUE},
{"Jitter", OML_DOUBLE_VALUE},
{"Packet_Lost", OML_LONG_VALUE},
{"Total_Packet", OML_LONG_VALUE},
{"PLR", OML_DOUBLE_VALUE},
{NULL, (OmlValueT)0}
};
static OmlMPDef peer_info[] = {
{"ID", OML_LONG_VALUE},
{"local_address", OML_STRING_VALUE},
{"local_port", OML_LONG_VALUE},
{"foreign_address", OML_STRING_VALUE},
{"foreign_port", OML_LONG_VALUE},
{NULL, (OmlValueT)0}
};
}
#ifdef WIN32
#include "service.h"
#endif
/* -------------------------------------------------------------------
* prototypes
* ------------------------------------------------------------------- */
void waitUntilQuit( void );
void sig_quit( int inSigno );
void cleanup( void );
/* -------------------------------------------------------------------
* global variables
* ------------------------------------------------------------------- */
#define GLOBAL()
Condition gQuit_cond;
/* -------------------------------------------------------------------
* sets up signal handlers
* parses settings from environment and command line
* starts up server or client thread
* waits for all threads to complete
* ------------------------------------------------------------------- */
int main( int argc, char *argv[] ) {
#ifdef WIN32
SERVICE_TABLE_ENTRY dispatchTable[] =
{
{ TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
{ NULL, NULL}
};
#endif
omlc_init("iperf", &argc, (const char**) argv, NULL);
printf("ADD MP \n");
tcp_measure = omlc_add_mp("TCP_received", tcp_receiverport);
udp_measure = omlc_add_mp("UDP_received", udp_receiverport);
peer_information = omlc_add_mp("Peer_Info", peer_info);
Listener *theListener = NULL;
Speaker *theSpeaker = NULL;
// signal handlers quietly exit on ^C and kill
// these are usually remapped later by the client or server
my_signal( SIGTERM, sig_exit );
my_signal( SIGINT, sig_exit );
#ifndef WIN32
signal(SIGPIPE,SIG_IGN);
#else
WSADATA wsaData;
int rc = WSAStartup( 0x202, &wsaData );
FAIL_errno( rc == SOCKET_ERROR, "WSAStartup" );
SetConsoleCtrlHandler( sig_dispatcher, true );
#endif
// perform any cleanup when quitting Iperf
atexit( cleanup );
ext_Settings* ext_gSettings = new ext_Settings;
Settings* gSettings = NULL;
// read settings from environment variables and command-line interface
gSettings = new Settings( ext_gSettings );
gSettings->ParseEnvironment();
gSettings->ParseCommandLine( argc, argv );
// start up client or server (listener)
if ( gSettings->GetServerMode() == kMode_Server ) {
// start up a listener
theListener = new Listener( ext_gSettings );
theListener->DeleteSelfAfterRun();
// Start the server as a daemon
if ( gSettings->GetDaemonMode() == true ) {
#ifdef WIN32
CmdInstallService(argc, argv);
DELETE_PTR( theListener );
DELETE_PTR( gSettings );
return 0;
#else
theListener->runAsDaemon(argv[0],LOG_DAEMON);
#endif
}
#ifdef WIN32
else {
if ( gSettings->GetRemoveService() == true ) {
// remove the service and continue to run as a normal process
if ( CmdRemoveService() ) {
printf("IPerf Service is removed.\n");
DELETE_PTR( theListener );
DELETE_PTR( gSettings );
return 0;
}
} else {
// try to start the service
if ( CmdStartService(argc, argv) ) {
printf("IPerf Service already exists.\n");
DELETE_PTR( theListener );
DELETE_PTR( gSettings );
return 0;
}
}
}
#endif
omlc_start();
theListener->Start();
if ( ext_gSettings->mThreads == 0 ) {
theListener->SetDaemon();
// the listener keeps going; we terminate on user input only
waitUntilQuit();
#ifdef HAVE_THREAD
if ( Thread::NumUserThreads() > 0 ) {
printf( wait_server_threads );
fflush( 0 );
}
#endif
}
} else if ( gSettings->GetServerMode() == kMode_Client ) {
#ifdef HAVE_THREAD
theSpeaker = new Speaker(ext_gSettings);
theSpeaker->OwnSettings();
theSpeaker->DeleteSelfAfterRun();
omlc_start();
theSpeaker->Start();
#else
// If we need to start up a listener do it now
ext_Settings *temp = NULL;
Settings::GenerateListenerSettings( ext_gSettings, &temp );
if ( temp != NULL ) {
theListener = new Listener( temp );
theListener->DeleteSelfAfterRun();
}
Client* theClient = new Client( ext_gSettings );
omlc_start();
theClient->InitiateServer();
theClient->Start();
if ( theListener != NULL ) {
theListener->Start();
}
#endif
} else {
// neither server nor client mode was specified
// print usage and exit
#ifdef WIN32
// starting the service by SCM, there is no arguments will be passed in.
// the arguments will pass into Service_Main entry.
if ( !StartServiceCtrlDispatcher(dispatchTable) )
printf(usage_short, argv[0], argv[0]);
#else
printf( usage_short, argv[0], argv[0] );
#endif
}
// wait for other (client, server) threads to complete
Thread::Joinall();
DELETE_PTR( gSettings ); // modified by qfeng
// all done!
return 0;
} // end main
/* -------------------------------------------------------------------
* Blocks the thread until a quit thread signal is sent
* ------------------------------------------------------------------- */
void waitUntilQuit( void ) {
#ifdef HAVE_THREAD
// signal handlers send quit signal on ^C and kill
gQuit_cond.Lock();
my_signal( SIGTERM, sig_quit );
my_signal( SIGINT, sig_quit );
#ifdef HAVE_USLEEP
// this sleep is a hack to get around an apparent bug? in IRIX
// where pthread_cancel doesn't work unless the thread
// starts up before the gQuit_cand.Wait() call below.
// A better solution is to just use sigwait here, but
// then I have to emulate that for Windows...
usleep( 10 );
#endif
// wait for quit signal
gQuit_cond.Wait();
gQuit_cond.Unlock();
#endif
} // end waitUntilQuit
/* -------------------------------------------------------------------
* Sends a quit thread signal to let the main thread quit nicely.
* ------------------------------------------------------------------- */
void sig_quit( int inSigno ) {
#ifdef HAVE_THREAD
// if we get a second signal after 1/10 second, exit
// some implementations send the signal to all threads, so the 1/10 sec
// allows us to ignore multiple receipts of the same signal
static Timestamp* first = NULL;
if ( first != NULL ) {
Timestamp now;
if ( now.subSec( *first ) > 0.1 ) {
sig_exit( inSigno );
}
} else {
first = new Timestamp();
}
// with threads, send a quit signal
gQuit_cond.Signal();
#else
// without threads, just exit quietly, same as sig_exit()
sig_exit( inSigno );
#endif
} // end sig_quit
/* -------------------------------------------------------------------
* Any necesary cleanup before Iperf quits. Called at program exit,
* either by exit() or terminating main().
* ------------------------------------------------------------------- */
void cleanup( void ) {
#ifdef WIN32
WSACleanup();
#endif
extern Iperf_ListEntry *clients;
Iperf_destroy ( &clients );
} // end cleanup
#ifdef WIN32
/*--------------------------------------------------------------------
* ServiceStart
*
* each time starting the service, this is the entry point of the service.
* Start the service, certainly it is on server-mode
*
*
*-------------------------------------------------------------------- */
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) {
Listener *theListener = NULL;
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_START_PENDING, // service state
NO_ERROR, // exit code
3000) ) // wait hint
goto clean;
ext_Settings* ext_gSettings = new ext_Settings;
Settings *gSettings;
// read settings from passing by StartService
gSettings = new Settings( ext_gSettings );
gSettings->ParseEnvironment();
gSettings->ParseCommandLine( dwArgc, lpszArgv );
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_START_PENDING, // service state
NO_ERROR, // exit code
3000) ) // wait hint
goto clean;
// if needed, redirect the output into a specified file
if ( gSettings->GetFileOutput() ) {
redirect(gSettings->GetOutputFileName());
}
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_START_PENDING, // service state
NO_ERROR, // exit code
3000) ) // wait hint
goto clean;
theListener = new Listener( ext_gSettings );
theListener->Start();
theListener->SetDaemon();
// report the status to the service control manager.
//
if ( !ReportStatusToSCMgr(
SERVICE_RUNNING, // service state
NO_ERROR, // exit code
0) ) // wait hint
goto clean;
// the listener keeps going; we terminate on user input only
waitUntilQuit();
#ifdef HAVE_THREAD
if ( Thread::NumUserThreads() > 0 ) {
printf( wait_server_threads );
fflush( 0 );
}
#endif
clean:
// wait for other (client, server) threads to complete
Thread::Joinall();
DELETE_PTR( theListener );
DELETE_PTR( gSettings ); // modified by qfeng
DELETE_PTR( ext_gSettings ); // modified by qfeng
}
//
// FUNCTION: ServiceStop
//
// PURPOSE: Stops the service
//
// PARAMETERS:
// none
//
// RETURN VALUE:
// none
//
// COMMENTS:
// If a ServiceStop procedure is going to
// take longer than 3 seconds to execute,
// it should spawn a thread to execute the
// stop code, and return. Otherwise, the
// ServiceControlManager will believe that
// the service has stopped responding.
//
VOID ServiceStop() {
#ifdef HAVE_THREAD
gQuit_cond.Signal();
#else
sig_exit(1);
#endif
}
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_cxa_scom.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _INIT_P9_CXA_SCOM_PROCEDURE_H_
#define _INIT_P9_CXA_SCOM_PROCEDURE_H_
#include <stddef.h>
#include <stdint.h>
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_cxa_scom_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>&,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>&);
extern "C"
{
fapi2::ReturnCode p9_cxa_scom(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1);
}
#endif
<commit_msg>Updates to initcompiler to support DD2 and cumulus<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_cxa_scom.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _INIT_P9_CXA_SCOM_PROCEDURE_H_
#define _INIT_P9_CXA_SCOM_PROCEDURE_H_
#include <stddef.h>
#include <stdint.h>
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_cxa_scom_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>&,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>&, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
extern "C"
{
fapi2::ReturnCode p9_cxa_scom(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2);
}
#endif
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(37, 203, 206);
gui.setup();
gui.setPosition(5, 40);
gui.add(degree.setup("degree", 137.5, 130.00, 140.00));
gui.add(spread.setup("spread", 11, 2, 40));
gui.add(extrude.setup("extrude", 0.3, 0.01, 0.90));
light.setup();
light.setPosition(-100, 200,0);
masterColor = ofFloatColor::red;
secondColor = ofFloatColor::yellow;
ofEnableDepthTest();
for(int i = 0; i < nCubes;i++){
children.push_back(ofBoxPrimitive(5,5,5));
}
}
//--------------------------------------------------------------
void ofApp::update(){
float rad = ofDegToRad(degree);
for (int i = 0; i < nCubes;i++) {
ofVec3f pos;
if (selectedType == "simple") {
pos = ofxPhyllotaxis::simple(i, rad, spread);
}
if (selectedType == "conical") {
pos = ofxPhyllotaxis::conical(i, rad, spread, extrude);
}
if (selectedType == "apple") {
pos = ofxPhyllotaxis::apple(i, rad, spread, nCubes);
}
children[i].setPosition(pos);
}
}
//--------------------------------------------------------------
void ofApp::draw(){
maybeDrawGui();
camera.begin();
secondMaterial.setEmissiveColor(masterColor);
for (int i = 0; i < nCubes;i++) {
float lerp = ofMap(i, 0, nCubes, 0.0, 1.0);
auto interpolatedColor = masterColor.getLerped(secondColor, lerp);
secondMaterial.setEmissiveColor(interpolatedColor);
secondMaterial.begin();
children[i].draw();
secondMaterial.end();
}
camera.end();
}
void ofApp::maybeDrawGui(){
if(!hideGui){
ofDisableDepthTest();
gui.draw();
ofPushStyle();
string displayGui = "press 'g' to toggle the gui, up and down to change presets";
ofDrawBitmapString(displayGui, 5, 10);
string types = "press 1, 2, 3 to try different implementation";
ofDrawBitmapString(types, 5, 20);
string currentType = "current: "+ selectedType;
ofDrawBitmapString(currentType, 5, 30);
ofPopStyle();
ofEnableDepthTest();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key){
case 'g':
hideGui = !hideGui;
break;
case 49:
selectedType = "conical";
break;
case 50:
selectedType = "apple";
break;
case 51:
selectedType = "simple";
break;
default:
break;
}
}
<commit_msg>Update ofApp.cpp<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(37, 203, 206);
gui.setup();
gui.setPosition(5, 40);
gui.add(degree.setup("degree", 137.5, 130.00, 140.00));
gui.add(spread.setup("spread", 11, 2, 40));
gui.add(extrude.setup("extrude", 0.3, 0.01, 0.90));
light.setup();
light.setPosition(-100, 200,0);
masterColor = ofFloatColor::red;
secondColor = ofFloatColor::yellow;
ofEnableDepthTest();
for(int i = 0; i < nCubes;i++){
children.push_back(ofBoxPrimitive(5,5,5));
}
}
//--------------------------------------------------------------
void ofApp::update(){
float rad = ofDegToRad(degree);
for (int i = 0; i < nCubes;i++) {
glm::vec3 pos;
if (selectedType == "simple") {
pos = ofxPhyllotaxis::simple(i, rad, spread);
}
if (selectedType == "conical") {
pos = ofxPhyllotaxis::conical(i, rad, spread, extrude);
}
if (selectedType == "apple") {
pos = ofxPhyllotaxis::apple(i, rad, spread, nCubes);
}
children[i].setPosition(pos);
}
}
//--------------------------------------------------------------
void ofApp::draw(){
maybeDrawGui();
camera.begin();
secondMaterial.setEmissiveColor(masterColor);
for (int i = 0; i < nCubes;i++) {
float lerp = ofMap(i, 0, nCubes, 0.0, 1.0);
auto interpolatedColor = masterColor.getLerped(secondColor, lerp);
secondMaterial.setEmissiveColor(interpolatedColor);
secondMaterial.begin();
children[i].draw();
secondMaterial.end();
}
camera.end();
}
void ofApp::maybeDrawGui(){
if(!hideGui){
ofDisableDepthTest();
gui.draw();
ofPushStyle();
string displayGui = "press 'g' to toggle the gui, up and down to change presets";
ofDrawBitmapString(displayGui, 5, 10);
string types = "press 1, 2, 3 to try different implementation";
ofDrawBitmapString(types, 5, 20);
string currentType = "current: "+ selectedType;
ofDrawBitmapString(currentType, 5, 30);
ofPopStyle();
ofEnableDepthTest();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key){
case 'g':
hideGui = !hideGui;
break;
case 49:
selectedType = "conical";
break;
case 50:
selectedType = "apple";
break;
case 51:
selectedType = "simple";
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <libetonyek/libetonyek.h>
#include <cassert>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/logic/tribool.hpp>
#include <libxml/xmlreader.h>
#include "libetonyek_utils.h"
#include "libetonyek_xml.h"
#include "IWORKPresentationRedirector.h"
#include "IWORKSpreadsheetRedirector.h"
#include "IWORKTextRedirector.h"
#include "IWORKTokenizer.h"
#include "IWORKZlibStream.h"
#include "KEY1Parser.h"
#include "KEY2Parser.h"
#include "KEY2Token.h"
#include "KEYCollector.h"
#include "KEYDictionary.h"
#include "NUMCollector.h"
#include "NUMDictionary.h"
#include "NUM1Parser.h"
#include "NUM1Token.h"
#include "PAGCollector.h"
#include "PAG1Parser.h"
#include "PAG1Token.h"
#include "PAGDictionary.h"
using boost::logic::indeterminate;
using boost::logic::tribool;
using boost::scoped_ptr;
using boost::shared_ptr;
using std::string;
using librevenge::RVNG_SEEK_SET;
namespace libetonyek
{
namespace
{
enum CheckType
{
CHECK_TYPE_NONE = 0,
CHECK_TYPE_KEYNOTE = 1 << 1,
CHECK_TYPE_NUMBERS = 1 << 2,
CHECK_TYPE_PAGES = 1 << 3,
CHECK_TYPE_ANY = CHECK_TYPE_KEYNOTE | CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES
};
struct DetectionInfo
{
DetectionInfo();
RVNGInputStreamPtr_t m_input;
RVNGInputStreamPtr_t m_package;
EtonyekDocument::Confidence m_confidence;
EtonyekDocument::Type m_type;
unsigned m_version;
};
DetectionInfo::DetectionInfo()
: m_input()
, m_package()
, m_confidence(EtonyekDocument::CONFIDENCE_NONE)
, m_type(EtonyekDocument::TYPE_UNKNOWN)
, m_version(0)
{
}
typedef bool (*ProbeXMLFun_t)(const RVNGInputStreamPtr_t &, unsigned &, xmlTextReaderPtr);
std::string queryAttribute(xmlTextReaderPtr reader, const int name, const int ns, const IWORKTokenizer &tokenizer)
{
if (xmlTextReaderHasAttributes(reader))
{
int ret = xmlTextReaderMoveToFirstAttribute(reader);
while (1 == ret)
{
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((ns | name) == id)
return char_cast(xmlTextReaderConstValue(reader));
ret = xmlTextReaderMoveToNextAttribute(reader);
}
}
return "";
}
bool probeKeynote1XML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
// TODO: implement me
(void) input;
(void) version;
(void) reader;
return false;
}
bool probeKeynote2XML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(KEY2Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((KEY2Token::NS_URI_KEY | KEY2Token::presentation) == id)
{
const std::string v = queryAttribute(reader, KEY2Token::version, KEY2Token::NS_URI_KEY, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case KEY2Token::VERSION_STR_2 :
version = 2;
return true;
case KEY2Token::VERSION_STR_3 :
version = 3;
return true;
case KEY2Token::VERSION_STR_4 :
version = 4;
return true;
case KEY2Token::VERSION_STR_5 :
version = 5;
return true;
}
}
return false;
}
bool probeKeynoteXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (probeKeynote2XML(input, version, reader))
return true;
input->seek(0, RVNG_SEEK_SET);
return probeKeynote1XML(input, version, reader);
}
bool probeNumbersXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(NUM1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((NUM1Token::NS_URI_LS | NUM1Token::document) == id)
{
const std::string v = queryAttribute(reader, NUM1Token::version, NUM1Token::NS_URI_LS, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case NUM1Token::VERSION_STR_2 :
version = 2;
break;
}
return true;
}
return false;
}
bool probePagesXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(PAG1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((PAG1Token::NS_URI_SL | PAG1Token::document) == id)
{
const std::string v = queryAttribute(reader, PAG1Token::version, PAG1Token::NS_URI_SL, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case PAG1Token::VERSION_STR_4 :
version = 4;
break;
}
return true;
}
return false;
}
bool probeXMLImpl(const RVNGInputStreamPtr_t &input, const ProbeXMLFun_t probe, const EtonyekDocument::Type type, DetectionInfo &info)
{
const shared_ptr<xmlTextReader> reader(xmlReaderForIO(readFromStream, closeStream, input.get(), "", 0, 0), xmlFreeTextReader);
if (!reader)
return false;
int ret = 0;
do
{
ret = xmlTextReaderRead(reader.get());
}
while ((1 == ret) && (XML_READER_TYPE_ELEMENT != xmlTextReaderNodeType(reader.get())));
if (1 != ret)
return false;
if (probe(input, info.m_version, reader.get()))
{
info.m_type = type;
return true;
}
return false;
}
bool probeXML(const ProbeXMLFun_t probe, const EtonyekDocument::Type type, tribool &isGzipped, DetectionInfo &info)
{
if (isGzipped || indeterminate(isGzipped))
{
try
{
const RVNGInputStreamPtr_t uncompressed(new IWORKZlibStream(info.m_input));
isGzipped = true;
if (probeXMLImpl(uncompressed, probe, type, info))
{
info.m_input = uncompressed;
return true;
}
else
{
return false; // compressed, but invalid format
}
}
catch (...)
{
if (isGzipped) // decompression failed? most probably a broken file...
return false;
isGzipped = false;
}
info.m_input->seek(0, RVNG_SEEK_SET);
}
assert(isGzipped == false);
return probeXMLImpl(info.m_input, probe, type, info);
}
bool detect(const RVNGInputStreamPtr_t &input, unsigned checkTypes, DetectionInfo &info)
{
info.m_confidence = EtonyekDocument::CONFIDENCE_SUPPORTED_PART;
bool isXML = true;
tribool isGzipped = indeterminate;
tribool isKeynote1 = indeterminate;
if (input->isStructured())
{
info.m_package = input;
// check which format it might be
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
if (input->existsSubStream("index.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = false;
info.m_input.reset(input->getSubStreamByName("index.apxl"));
}
else if (input->existsSubStream("index.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = false;
info.m_input.reset(input->getSubStreamByName("index.apxl.gz"));
}
else if (input->existsSubStream("presentation.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = true;
info.m_input.reset(input->getSubStreamByName("presentation.apxl"));
}
else if (input->existsSubStream("presentation.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = true;
info.m_input.reset(input->getSubStreamByName("presentation.apxl.gz"));
}
}
if ((CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES) & checkTypes)
{
if (input->existsSubStream("index.xml"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.m_input.reset(input->getSubStreamByName("index.xml"));
}
else if (input->existsSubStream("index.xml.gz"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.m_input.reset(input->getSubStreamByName("index.xml.gz"));
}
}
if (!info.m_input && (CHECK_TYPE_ANY & checkTypes))
{
if (input->existsSubStream("Index.zip"))
{
isXML = false;
info.m_input.reset(input->getSubStreamByName("Index.zip"));
}
}
if (!info.m_input)
{
// nothing detected
// TODO: this might also be Index.zip...
return EtonyekDocument::CONFIDENCE_NONE;
}
info.m_confidence = EtonyekDocument::CONFIDENCE_EXCELLENT; // this is either a valid package of a false positive
}
else
{
info.m_input = input;
}
assert(bool(info.m_input));
if (isXML)
{
assert(CHECK_TYPE_ANY & checkTypes);
assert(!info.m_input->isStructured());
info.m_input->seek(0, RVNG_SEEK_SET);
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
const ProbeXMLFun_t probe = (isKeynote1 ? probeKeynote1XML : ((!isKeynote1) ? probeKeynote2XML : probeKeynoteXML));
if (probeXML(probe, EtonyekDocument::TYPE_KEYNOTE, isGzipped, info))
return true;
info.m_input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_NUMBERS & checkTypes)
{
if (probeXML(probeNumbersXML, EtonyekDocument::TYPE_NUMBERS, isGzipped, info))
return true;
info.m_input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_PAGES & checkTypes)
{
if (probeXML(probePagesXML, EtonyekDocument::TYPE_PAGES, isGzipped, info))
return true;
}
}
else
{
// TODO: detect type in binary format
}
return EtonyekDocument::CONFIDENCE_NONE;
}
}
namespace
{
shared_ptr<IWORKParser> makeKeynoteParser(const unsigned version, const RVNGInputStreamPtr_t &input, const RVNGInputStreamPtr_t &package, KEYCollector &collector, KEYDictionary &dict)
{
shared_ptr<IWORKParser> parser;
if (1 == version)
parser.reset(new KEY1Parser(input, package, collector));
else if ((2 <= version) && (5 >= version))
parser.reset(new KEY2Parser(input, package, collector, dict));
else
assert(0);
return parser;
}
}
ETONYEKAPI EtonyekDocument::Confidence EtonyekDocument::isSupported(librevenge::RVNGInputStream *const input, EtonyekDocument::Type *type) try
{
if (!input)
return CONFIDENCE_NONE;
if (type)
*type = TYPE_UNKNOWN;
DetectionInfo info;
if (detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_ANY, info))
{
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
if (type)
*type = info.m_type;
return info.m_confidence;
}
return CONFIDENCE_NONE;
}
catch (...)
{
return CONFIDENCE_NONE;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGPresentationInterface *const generator) try
{
if (!input || !generator)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_KEYNOTE, info))
return false;
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
assert(0 != info.m_version);
info.m_input->seek(0, librevenge::RVNG_SEEK_SET);
KEYDictionary dict;
IWORKPresentationRedirector redirector(generator);
KEYCollector collector(&redirector);
const shared_ptr<IWORKParser> parser = makeKeynoteParser(info.m_version, info.m_input, info.m_package, collector, dict);
return parser->parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGSpreadsheetInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_NUMBERS, info))
return false;
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
assert(0 != info.m_version);
info.m_input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKSpreadsheetRedirector redirector(document);
NUMCollector collector(&redirector);
NUMDictionary dict;
NUM1Parser parser(info.m_input, info.m_package, collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGTextInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_PAGES, info))
return false;
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
assert(0 != info.m_version);
info.m_input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKTextRedirector redirector(document);
PAGCollector collector(&redirector);
PAGDictionary dict;
PAG1Parser parser(info.m_input, info.m_package, collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>only detect the format kind<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <libetonyek/libetonyek.h>
#include <cassert>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/logic/tribool.hpp>
#include <libxml/xmlreader.h>
#include "libetonyek_utils.h"
#include "libetonyek_xml.h"
#include "IWORKPresentationRedirector.h"
#include "IWORKSpreadsheetRedirector.h"
#include "IWORKTextRedirector.h"
#include "IWORKTokenizer.h"
#include "IWORKZlibStream.h"
#include "KEY1Parser.h"
#include "KEY2Parser.h"
#include "KEY2Token.h"
#include "KEYCollector.h"
#include "KEYDictionary.h"
#include "NUMCollector.h"
#include "NUMDictionary.h"
#include "NUM1Parser.h"
#include "NUM1Token.h"
#include "PAGCollector.h"
#include "PAG1Parser.h"
#include "PAG1Token.h"
#include "PAGDictionary.h"
using boost::logic::indeterminate;
using boost::logic::tribool;
using boost::scoped_ptr;
using boost::shared_ptr;
using std::string;
using librevenge::RVNG_SEEK_SET;
namespace libetonyek
{
namespace
{
enum CheckType
{
CHECK_TYPE_NONE = 0,
CHECK_TYPE_KEYNOTE = 1 << 1,
CHECK_TYPE_NUMBERS = 1 << 2,
CHECK_TYPE_PAGES = 1 << 3,
CHECK_TYPE_ANY = CHECK_TYPE_KEYNOTE | CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES
};
enum Format
{
FORMAT_UNKNOWN,
FORMAT_XML1,
FORMAT_XML2,
FORMAT_BINARY
};
struct DetectionInfo
{
DetectionInfo();
RVNGInputStreamPtr_t m_input;
RVNGInputStreamPtr_t m_package;
EtonyekDocument::Confidence m_confidence;
EtonyekDocument::Type m_type;
Format m_format;
};
DetectionInfo::DetectionInfo()
: m_input()
, m_package()
, m_confidence(EtonyekDocument::CONFIDENCE_NONE)
, m_type(EtonyekDocument::TYPE_UNKNOWN)
, m_format(FORMAT_UNKNOWN)
{
}
typedef bool (*ProbeXMLFun_t)(const RVNGInputStreamPtr_t &, Format &, xmlTextReaderPtr);
bool probeKeynote1XML(const RVNGInputStreamPtr_t &input, Format &format, xmlTextReaderPtr reader)
{
// TODO: implement me
(void) input;
(void) format;
(void) reader;
return false;
}
bool probeKeynote2XML(const RVNGInputStreamPtr_t &input, Format &format, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(KEY2Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((KEY2Token::NS_URI_KEY | KEY2Token::presentation) == id)
{
format = FORMAT_XML2;
return true;
}
return false;
}
bool probeKeynoteXML(const RVNGInputStreamPtr_t &input, Format &format, xmlTextReaderPtr reader)
{
if (probeKeynote2XML(input, format, reader))
return true;
input->seek(0, RVNG_SEEK_SET);
if (probeKeynote1XML(input, format, reader))
return true;
return false;
}
bool probeNumbersXML(const RVNGInputStreamPtr_t &input, Format &format, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(NUM1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((NUM1Token::NS_URI_LS | NUM1Token::document) == id)
{
format = FORMAT_XML2;
return true;
}
return false;
}
bool probePagesXML(const RVNGInputStreamPtr_t &input, Format &format, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(PAG1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((PAG1Token::NS_URI_SL | PAG1Token::document) == id)
{
format = FORMAT_XML2;
return true;
}
return false;
}
bool probeXMLImpl(const RVNGInputStreamPtr_t &input, const ProbeXMLFun_t probe, const EtonyekDocument::Type type, DetectionInfo &info)
{
const shared_ptr<xmlTextReader> reader(xmlReaderForIO(readFromStream, closeStream, input.get(), "", 0, 0), xmlFreeTextReader);
if (!reader)
return false;
int ret = 0;
do
{
ret = xmlTextReaderRead(reader.get());
}
while ((1 == ret) && (XML_READER_TYPE_ELEMENT != xmlTextReaderNodeType(reader.get())));
if (1 != ret)
return false;
if (probe(input, info.m_format, reader.get()))
{
info.m_type = type;
return true;
}
return false;
}
bool probeXML(const ProbeXMLFun_t probe, const EtonyekDocument::Type type, tribool &isGzipped, DetectionInfo &info)
{
if (isGzipped || indeterminate(isGzipped))
{
try
{
const RVNGInputStreamPtr_t uncompressed(new IWORKZlibStream(info.m_input));
isGzipped = true;
if (probeXMLImpl(uncompressed, probe, type, info))
{
info.m_input = uncompressed;
return true;
}
else
{
return false; // compressed, but invalid format
}
}
catch (...)
{
if (isGzipped) // decompression failed? most probably a broken file...
return false;
isGzipped = false;
}
info.m_input->seek(0, RVNG_SEEK_SET);
}
assert(isGzipped == false);
return probeXMLImpl(info.m_input, probe, type, info);
}
bool detect(const RVNGInputStreamPtr_t &input, unsigned checkTypes, DetectionInfo &info)
{
info.m_confidence = EtonyekDocument::CONFIDENCE_SUPPORTED_PART;
bool isXML = true;
tribool isGzipped = indeterminate;
tribool isKeynote1 = indeterminate;
if (input->isStructured())
{
info.m_package = input;
// check which format it might be
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
if (input->existsSubStream("index.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = false;
info.m_input.reset(input->getSubStreamByName("index.apxl"));
}
else if (input->existsSubStream("index.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = false;
info.m_input.reset(input->getSubStreamByName("index.apxl.gz"));
}
else if (input->existsSubStream("presentation.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = true;
info.m_input.reset(input->getSubStreamByName("presentation.apxl"));
}
else if (input->existsSubStream("presentation.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = true;
info.m_input.reset(input->getSubStreamByName("presentation.apxl.gz"));
}
}
if ((CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES) & checkTypes)
{
if (input->existsSubStream("index.xml"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.m_input.reset(input->getSubStreamByName("index.xml"));
}
else if (input->existsSubStream("index.xml.gz"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.m_input.reset(input->getSubStreamByName("index.xml.gz"));
}
}
if (!info.m_input && (CHECK_TYPE_ANY & checkTypes))
{
if (input->existsSubStream("Index.zip"))
{
isXML = false;
info.m_input.reset(input->getSubStreamByName("Index.zip"));
}
}
if (!info.m_input)
{
// nothing detected
// TODO: this might also be Index.zip...
return EtonyekDocument::CONFIDENCE_NONE;
}
info.m_confidence = EtonyekDocument::CONFIDENCE_EXCELLENT; // this is either a valid package of a false positive
}
else
{
info.m_input = input;
}
assert(bool(info.m_input));
if (isXML)
{
assert(CHECK_TYPE_ANY & checkTypes);
assert(!info.m_input->isStructured());
info.m_input->seek(0, RVNG_SEEK_SET);
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
const ProbeXMLFun_t probe = (isKeynote1 ? probeKeynote1XML : ((!isKeynote1) ? probeKeynote2XML : probeKeynoteXML));
if (probeXML(probe, EtonyekDocument::TYPE_KEYNOTE, isGzipped, info))
return true;
info.m_input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_NUMBERS & checkTypes)
{
if (probeXML(probeNumbersXML, EtonyekDocument::TYPE_NUMBERS, isGzipped, info))
return true;
info.m_input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_PAGES & checkTypes)
{
if (probeXML(probePagesXML, EtonyekDocument::TYPE_PAGES, isGzipped, info))
return true;
}
}
else
{
// TODO: detect type in binary format
}
return EtonyekDocument::CONFIDENCE_NONE;
}
}
namespace
{
shared_ptr<IWORKParser> makeKeynoteParser(const unsigned version, const RVNGInputStreamPtr_t &input, const RVNGInputStreamPtr_t &package, KEYCollector &collector, KEYDictionary &dict)
{
shared_ptr<IWORKParser> parser;
if (1 == version)
parser.reset(new KEY1Parser(input, package, collector));
else if ((2 <= version) && (5 >= version))
parser.reset(new KEY2Parser(input, package, collector, dict));
else
assert(0);
return parser;
}
}
ETONYEKAPI EtonyekDocument::Confidence EtonyekDocument::isSupported(librevenge::RVNGInputStream *const input, EtonyekDocument::Type *type) try
{
if (!input)
return CONFIDENCE_NONE;
if (type)
*type = TYPE_UNKNOWN;
DetectionInfo info;
if (detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_ANY, info))
{
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
if (type)
*type = info.m_type;
return info.m_confidence;
}
return CONFIDENCE_NONE;
}
catch (...)
{
return CONFIDENCE_NONE;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGPresentationInterface *const generator) try
{
if (!input || !generator)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_KEYNOTE, info))
return false;
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
assert(FORMAT_UNKNOWN != info.m_format);
info.m_input->seek(0, librevenge::RVNG_SEEK_SET);
KEYDictionary dict;
IWORKPresentationRedirector redirector(generator);
KEYCollector collector(&redirector);
const shared_ptr<IWORKParser> parser = makeKeynoteParser(info.m_format, info.m_input, info.m_package, collector, dict);
return parser->parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGSpreadsheetInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_NUMBERS, info))
return false;
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
assert(FORMAT_UNKNOWN != info.m_format);
info.m_input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKSpreadsheetRedirector redirector(document);
NUMCollector collector(&redirector);
NUMDictionary dict;
NUM1Parser parser(info.m_input, info.m_package, collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGTextInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_PAGES, info))
return false;
assert(TYPE_UNKNOWN != info.m_type);
assert(CONFIDENCE_NONE != info.m_confidence);
assert(bool(info.m_input));
assert(FORMAT_UNKNOWN != info.m_format);
info.m_input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKTextRedirector redirector(document);
PAGCollector collector(&redirector);
PAGDictionary dict;
PAG1Parser parser(info.m_input, info.m_package, collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <vector>
#include <string>
#if __BIG_ENDIAN
#define RTP_HEADER(port, subclass, ack, sfs) \
(((port & 0x0F) << 4) | ((subclass & 0x03) << 2) | ((ack & 0x01) << 1) | \
(sfs & 0x01))
#else
#define RTP_HEADER(port, subclass, ack, sfs) \
(((sfs & 0x01) << 7) | ((ack & 0x01) << 6) | ((subclass & 0x03) << 4) | \
(port & 0x0F))
#endif
#define BASE_STATION_ADDR (1)
#define LOOPBACK_ADDR (127)
namespace rtp {
///
static const unsigned int MAX_DATA_SZ = 120;
/**
* @brief { port enumerations for different communication protocols }
*/
enum port {
SINK = 0x00,
LINK = 0x01,
CONTROL = 0x02,
SETPOINT = 0x03,
GSTROBE = 0x04,
DISCOVER = 0x05,
LOGGER = 0x06,
TCP = 0x07,
LEGACY = 0x0E
};
namespace {
// type of data field used in all packet classes
// - must be 8 bits, (typedef used for eaiser compiler
// type error debugging)
typedef uint8_t packet_data_t;
}
/**
* @brief [brief description]
* @details [long description]
* @return [description]
*/
class layer_map {
public:
typedef packet_data_t data_t;
protected:
typedef std::vector<data_t> datav_t;
typedef datav_t::iterator datav_it_t;
std::vector<data_t> d;
public:
layer_map(size_t resv) { d.reserve(resv); }
datav_it_t pack() {
// make sure all files are in contiguous memory,
// then return iterator to beginning
return d.begin();
}
data_t* data() { return d.data(); }
void show_data() {
for (auto const& i : d) printf("%02X ", i);
}
const size_t size() const { return static_cast<const int>(d.size()); }
};
/**
* @brief [brief description]
* @details [long description]
*
* @param p [description]
* @return [description]
*/
class header_data : public layer_map {
public:
enum type { control, tuning, ota, misc };
header_data() : layer_map(3), t(control), address(0), port_fields(0){};
datav_it_t pack(size_t payload_size) {
if (d.size()) return d.begin();
// payload size + number of bytes in header is top byte
// since that's required for the cc1101/cc1201 with
// variable packet sizes
d.push_back(payload_size + 2);
d.push_back(address);
d.push_back(port_fields);
return d.begin();
}
type t;
data_t address;
friend class payload_data;
// common header byte - union so it's easier to put into vector
struct {
union {
struct {
data_t port_fields;
} __attribute__((packed));
struct {
#if __BIG_ENDIAN
data_t sfs : 1, ack : 1, subclass : 2, port : 4;
#else
data_t port : 4, subclass : 2, ack : 1, sfs : 1;
#endif
} __attribute__((packed));
};
};
};
/**
* @brief [brief description]
* @details [long description]
*
* @param p [description]
* @return [description]
*/
class payload_data : public layer_map {
public:
payload_data() : layer_map(MAX_DATA_SZ){};
datav_it_t pack() { return d.begin(); }
datav_it_t add_header(const header_data& h) {
d.insert(d.begin(), h.d.begin(), h.d.end());
return d.begin();
}
template <class T>
void fill(const std::vector<T>& v) {
d = v;
}
void fill(const std::string& str) {
for (const char& c : str) d.push_back(c);
d.push_back('\0');
}
};
/**
* @brief { Real-Time packet definition }
*/
class packet {
public:
rtp::header_data header;
rtp::payload_data payload;
bool _packed;
packet(){};
packet(const std::string& s) { payload.fill(s); }
template <class T>
packet(const std::vector<T>& v) {
payload.fill(v);
}
packet_data_t* packed() { return payload.data(); }
size_t size() {
if (_packed == true)
return payload.size();
else
return payload.size() + header.size();
}
const int port() const { return static_cast<const int>(header.port); }
template <class T>
void port(T p) {
header.port = static_cast<unsigned int>(p);
}
int subclass() { return header.subclass; }
template <class T>
void subclass(T c) {
header.subclass = static_cast<unsigned int>(c);
}
bool ack() { return header.ack; }
void ack(bool b) { header.ack = b; }
bool sfs() { return header.sfs; }
void sfs(bool b) { header.sfs = b; }
int address() { return header.address; }
void address(int a) { header.address = static_cast<unsigned int>(a); }
template <class T>
void recv(const std::vector<T>& v) {
payload.fill(v);
// sort out header
}
private:
void pack() {
payload.pack();
header.pack(payload.size());
payload.add_header(header);
_packed = true;
}
};
}
<commit_msg>adding support for selective header attachment to packets<commit_after>#pragma once
#include <cstdint>
#include <vector>
#include <string>
#if __BIG_ENDIAN
#define RTP_HEADER(port, subclass, ack, sfs) \
(((port & 0x0F) << 4) | ((subclass & 0x03) << 2) | ((ack & 0x01) << 1) | \
(sfs & 0x01))
#else
#define RTP_HEADER(port, subclass, ack, sfs) \
(((sfs & 0x01) << 7) | ((ack & 0x01) << 6) | ((subclass & 0x03) << 4) | \
(port & 0x0F))
#endif
#define BASE_STATION_ADDR (1)
#define LOOPBACK_ADDR (127)
namespace rtp {
///
static const unsigned int MAX_DATA_SZ = 120;
/**
* @brief { port enumerations for different communication protocols }
*/
enum port {
SINK = 0x00,
LINK = 0x01,
CONTROL = 0x02,
SETPOINT = 0x03,
GSTROBE = 0x04,
DISCOVER = 0x05,
LOGGER = 0x06,
TCP = 0x07,
LEGACY = 0x0E
};
namespace {
// type of data field used in all packet classes
// - must be 8 bits, (typedef used for eaiser compiler
// type error debugging)
typedef uint8_t packet_data_t;
}
/**
* @brief [brief description]
* @details [long description]
* @return [description]
*/
class layer_map {
public:
typedef packet_data_t data_t;
protected:
typedef std::vector<data_t> datav_t;
typedef datav_t::iterator datav_it_t;
std::vector<data_t> d;
public:
layer_map(size_t resv) { d.reserve(resv); }
datav_it_t pack() {
// make sure all files are in contiguous memory,
// then return iterator to beginning
return d.begin();
}
data_t* data() { return d.data(); }
void show_data() {
for (auto const& i : d) printf("%02X ", i);
}
const size_t size() const { return static_cast<const int>(d.size()); }
};
/**
* @brief [brief description]
* @details [long description]
*
* @param p [description]
* @return [description]
*/
class header_data : public layer_map {
public:
enum type { control, tuning, ota, misc };
header_data() : layer_map(3), t(control), address(0), port_fields(0){};
datav_it_t pack(size_t payload_size, bool headless = false) {
if (d.size()) return d.begin();
// payload size + number of bytes in header is top byte
// since that's required for the cc1101/cc1201 with
// variable packet sizes
d.push_back(payload_size + (headless ? 0 : 2));
if (headless == false) {
d.push_back(address);
d.push_back(port_fields);
}
return d.begin();
}
type t;
data_t address;
friend class payload_data;
// common header byte - union so it's easier to put into vector
struct {
union {
struct {
data_t port_fields;
} __attribute__((packed));
struct {
#if __BIG_ENDIAN
data_t sfs : 1, ack : 1, subclass : 2, port : 4;
#else
data_t port : 4, subclass : 2, ack : 1, sfs : 1;
#endif
} __attribute__((packed));
};
};
};
/**
* @brief [brief description]
* @details [long description]
*
* @param p [description]
* @return [description]
*/
class payload_data : public layer_map {
public:
payload_data() : layer_map(MAX_DATA_SZ){};
datav_it_t pack() { return d.begin(); }
datav_it_t add_header(const header_data& h) {
d.insert(d.begin(), h.d.begin(), h.d.end());
return d.begin();
}
template <class T>
void fill(const std::vector<T>& v) {
d = v;
}
void fill(const std::string& str) {
for (const char& c : str) d.push_back(c);
d.push_back('\0');
}
};
/**
* @brief { Real-Time packet definition }
*/
class packet {
public:
rtp::header_data header;
rtp::payload_data payload;
bool _packed;
packet(){};
packet(const std::string& s) { payload.fill(s); }
template <class T>
packet(const std::vector<T>& v) {
payload.fill(v);
}
packet_data_t* packed() {
if (_packed == false)
pack();
return payload.data();
}
size_t size() {
if (_packed == true)
return payload.size();
else
return payload.size() + header.size();
}
const int port() const { return static_cast<const int>(header.port); }
template <class T>
void port(T p) {
header.port = static_cast<unsigned int>(p);
}
int subclass() { return header.subclass; }
template <class T>
void subclass(T c) {
header.subclass = static_cast<unsigned int>(c);
}
bool ack() { return header.ack; }
void ack(bool b) { header.ack = b; }
bool sfs() { return header.sfs; }
void sfs(bool b) { header.sfs = b; }
int address() { return header.address; }
void address(int a) { header.address = static_cast<unsigned int>(a); }
template <class T>
void recv(const std::vector<T>& v) {
payload.fill(v);
// sort out header
}
private:
void pack() {
payload.pack();
// pack the header, but do a "headless" pack
header.pack(payload.size(), true);
payload.add_header(header);
_packed = true;
}
};
}
<|endoftext|> |
<commit_before>/// @page AutoFilterTutorial00 AutoFilter Tutorial 00
/// This tutorial is intended to teach blah blah blah.
/// @code
// AutoFilterTutorial00.cpp created by Victor Dods on 2015/06/03
// Copyright (C) Leap Motion, Inc. All rights reserved.
/// @endcode
///
/// Testing
///
/// # Markdown test heading 1
/// ## Heading 2
/// ### Heading 3
///
/// List:
/// - item1
/// - item2
/// - item2.1
/// - item2.2
/// - item2.3
/// - item3
///
/// Numbered list:
/// 1. Blah 1
/// 2. Blah 2
/// 3. Blah 3
///
/// @code
int main () {
return 0;
}
/// @endcode
<commit_msg>Implemented AutoFilter tutorial 00. Having trouble with the doxygen indentation of @code blocks (it strips the common indentation).<commit_after>/// @page AutoFilterTutorial00 AutoFilter Tutorial 00
/// This tutorial will introduce the reader to the AutoFilter concept and how to implement a rudimentary
/// AutoFilter network. It is recommended that the reader become familiar with the concept of a context
/// (see XXX TODO context tutorial) before reading this tutorial.
/// @code
// AutoFilterTutorial00.cpp created by Victor Dods on 2015/06/03
// Copyright (C) Leap Motion, Inc. All rights reserved.
/// @endcode
/// A filter network can be thought of as a directed acyclic graph, where the nodes of the graph represent
/// data structures and the collection of arrows pointing at each graph node represent a function which
/// populates the data structure which that node represents. That collection of arrows will be refered to
/// as a filter.
///
/// In Autowiring, a filter is implemented as context members having an AutoFilter method. Its parameters
/// are what define the inputs and outputs. The inputs and outputs of these AutoFilter methods are what
/// define the nodes of the filter network.
///
/// Particular C++ idioms are used to differentiate the input and output parameters for an AutoFilter method,
/// as well as certain usage semantics. These will be fully covered in later tutorials. For now we will
/// deal only with ordinary input and output.
///
/// This tutorial will define and instantiate a simple filter network.
/// @code{.cpp}
#include <autowiring/Autowired.h> // Needed for Autowiring classes.
#include <cmath> // Needed for std::round.
#include <cstdlib> // Needed for std::atof.
#include <iostream> // Needed for std::cout.
/// @endcode
/// We will define several filters connecting several data structures (really they can be any C++ type), rendering
/// a linear sequence of processing.
///
/// This filter takes a std::string as input and produces a double as output. Notice that the input is passed
/// to the AutoFilter method by value (other, more efficient semantics will be introduced later), and that the
/// output is passed by reference. These type semantics are what define what the inputs and outputs of the
/// filter are. Instead of returning a value, the AutoFilter method need only assign to its output parameters.
///
/// In particular, this filter parses the string as a decimal value and stores it in double-precision floating
/// point format in the output parameter.
/// @code
class StringToDouble {
public:
void AutoFilter (std::string input, double &output) {
output = std::atof(input.c_str());
std::cout << "StringToDouble received std::string value \"" << input << "\" and has set its output param to double value " << output << ".\n";
}
};
/// @endcode
/// This filter takes a double as input and produces an int as output. In particular, the output is the rounded
/// value of the input.
/// @code
class DoubleRounder {
public:
void AutoFilter (double input, int &output) {
output = static_cast<int>(std::round(input));
std::cout << "DoubleRounder received double value " << input << " and has set its output param to int value " << output << ".\n";
}
};
/// @endcode
/// This filter takes an int as input and has no output. It simply prints the value of the input.
/// and
/// @code
class IntPrinter {
public:
void AutoFilter (int value) {
std::cout << "IntPrinter received int value " << value << ".\n";
}
};
/// @endcode
/// To demonstrate this filter network, we will perform the necessary initialization and context member injection
/// within the main function.
/// @code
int main () {
/// @endcode
/// A global context is created by default, and is the default current context. We must initialize that context
/// before proceeding.
/// @code
AutoCurrentContext()->Initiate();
/// @endcode
/// Each of the filters must be injected into the context in which they'll operate. In this case, we're only working
/// with the global context. The `AutoRequired` method is what accomplishes that injection.
/// @code
AutoRequired<StringToDouble>();
AutoRequired<DoubleRounder>();
AutoRequired<IntPrinter>();
/// @endcode
/// If a context has any members, then the context automatically includes an AutoPacketFactory type. This
/// can be used to create new packets in the AutoFilter network.
/// @code
Autowired<AutoPacketFactory> factory;
/// @endcode
/// `AutoPacket` is the mechanism which runs filter networks. An instance of AutoPacket corresponds with one execution
/// of the corresponding filter network. The packet can be 'decorated' with a value of a particular type. This means
/// that that type is present during this execution of the filter network as an input parameter to whatever AutoFilter
/// methods are present in the filter network. Only one value of any given type can be present in a packet at a time.
/// The AutoFilter method of a context member will only be called once all of its inputs have been decorated onto the
/// packet.
///
/// Using the factory, create a new AutoPacket so that we may run the filter network.
/// @code
std::shared_ptr<AutoPacket> packet = factory->NewPacket();
/// @endcode
/// Now decorate the packet with an `int`. This will cause the `AutoFilter` methods which only require a single `int`
/// input to be called. We should expect to see "IntPrinter received int value 42." printed to std::cout at this point.
/// @code
packet->Decorate(42);
std::cout << '\n'; // To make the separation between packets' executions clear in the console output.
/// @endcode
/// Create a new packet so that we may run the filter network again. Note that `packet` is a `std::shared_ptr<AutoPacket>`,
/// and so this assignment deletes the old instance. Decorate the packet again, but this time with a `double` value, thereby
/// calling the `DoubleRounder` filter, which in turn outputs an `int`, which calls the `IntPrinter` filter, generating output
/// to std::cout. This demonstrates that a filter network doesn't have a fixed input interface -- inputs can be provided at
/// any point. Of course, an `AutoFilter` method will be called only when all of its inputs are present on a packet.
/// @code
packet = factory->NewPacket();
packet->Decorate(101.1);
std::cout << '\n';
/// @endcode
/// Repeat the process, but decorate the packet with a value whose rounded value is different.
/// @code
packet = factory->NewPacket();
packet->Decorate(101.9);
std::cout << '\n';
/// @endcode
/// Repeat the process, but decorate the packet with a std::string value.
/// @code
packet = factory->NewPacket();
packet->Decorate(std::string("45954.1"));
}
/// @endcode
/// The output of this program is:
///
/// IntPrinter received int value 42.
///
/// DoubleRounder received double value 101.1 and has set its output param to int value 101.
/// IntPrinter received int value 101.
///
/// DoubleRounder received double value 101.9 and has set its output param to int value 102.
/// IntPrinter received int value 102.
///
/// StringToDouble received std::string value "45954.1" and has set its output param to double value 45954.1.
/// DoubleRounder received double value 45954.1 and has set its output param to int value 45954.
/// IntPrinter received int value 45954.
<|endoftext|> |
<commit_before>/* utility.ino */
#include "utility.h"
#include <LiquidTWI2.h>
#include <Ethernet2.h> // https://github.com/adafruit/Ethernet2
#include <EthernetUdp2.h> // https://github.com/adafruit/Ethernet2
void LCD_clearLine(LiquidTWI2 lcdref, int line) {
lcdref.setCursor(0, line);
for (int i=0;i<17;i++)
lcdref.print(" ");
lcdref.setCursor(0, line);
}
// Maintainbe our DHCP Lease
// Based on examples from the Ethernet2 Library
void dhcp_maintain() {
switch (Ethernet.maintain()) {
case DHCP_RENEW_FAIL:
Serial.println("DHCP Renew Failed");
// Turn off NTP Fetching
break;
case DHCP_RENEW_SUCCESS:
Serial.println("DHCP Renew Success");
break;
case DHCP_REBIND_FAIL:
// how is this diff to Renew fail?
Serial.println("DHCP Rebind Failed");
// Assume turn off NTP Fetching
break;
case DHCP_REBIND_SUCCESS:
Serial.println("DHCP Rebind Success");
break;
default:
break;
}
}
<commit_msg>Improved clearLine<commit_after>/* utility.ino */
#include "utility.h"
#include <LiquidTWI2.h>
#include <Ethernet2.h> // https://github.com/adafruit/Ethernet2
#include <EthernetUdp2.h> // https://github.com/adafruit/Ethernet2
void LCD_clearLine(LiquidTWI2 lcdref, int line) {
lcdref.setCursor(0, line);
char row[16];
memset(row, ' ', 16);
lcdref.print(row);
lcdref.setCursor(0, line);
}
// Maintainbe our DHCP Lease
// Based on examples from the Ethernet2 Library
void dhcp_maintain() {
switch (Ethernet.maintain()) {
case DHCP_RENEW_FAIL:
Serial.println("DHCP Renew Failed");
// Turn off NTP Fetching
break;
case DHCP_RENEW_SUCCESS:
Serial.println("DHCP Renew Success");
break;
case DHCP_REBIND_FAIL:
// how is this diff to Renew fail?
Serial.println("DHCP Rebind Failed");
// Assume turn off NTP Fetching
break;
case DHCP_REBIND_SUCCESS:
Serial.println("DHCP Rebind Success");
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// File: DateTime.cpp
//
// Title: DateTime Class
//
// Description: This file contains the class definition for DateTime
//
// Programmer: Paul Bladek & Norton Pengra
//
// Date: 4/24/2017
//
// Version: 1.0
//
// Environment: Hardware: IBM Pentium
// Software: WinXP or later or .NET for execution;
//
// Compiles under Microsoft C++ 2005
//
// class DateTime:
//
// Virtual Non-inline:
// virtual bool operator==(const Comparable &other)const;
// virtual bool operator<(const Comparable &other)const;
// virtual void input(istream& sin);
// virtual void print(ostream& sout)const;
//
// History Log:
// 4/7/08 PB completed version 1.0
// ----------------------------------------------------------------------------
#include "DateTime.h"
using namespace std;
namespace NP_DATETIME {
}<commit_msg>add == comparison<commit_after>//-----------------------------------------------------------------------------
// File: DateTime.cpp
//
// Title: DateTime Class
//
// Description: This file contains the class definition for DateTime
//
// Programmer: Paul Bladek & Norton Pengra
//
// Date: 4/24/2017
//
// Version: 1.0
//
// Environment: Hardware: IBM Pentium
// Software: WinXP or later or .NET for execution;
//
// Compiles under Microsoft C++ 2005
//
// class DateTime:
//
// Virtual Non-inline:
// virtual bool operator==(const Comparable &other)const;
// virtual bool operator<(const Comparable &other)const;
// virtual void input(istream& sin);
// virtual void print(ostream& sout)const;
//
// History Log:
// 4/7/08 PB completed version 1.0
// ----------------------------------------------------------------------------
#include "DateTime.h"
using namespace std;
namespace NP_DATETIME {
bool DateTime::operator==(const Comparable &other) const {
bool returnValue = false;
try
{
bool dateEqual = Date::operator==(other);
bool timeEqual = CTime::operator==(other);
returnValue = dateEqual && timeEqual;
}
catch (bad_cast e)
{
// Should something happen here?
}
return returnValue;
}
}<|endoftext|> |
<commit_before>/* @cpp.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
#include <vector>
#include <gridgain/gridgain.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/timer.hpp>
#include "gridtestcommon.hpp"
#include "gridgain/impl/gridclientpartitionedaffinity.hpp"
/** Global atomic used to calculate statistics. */
TGridAtomicInt gIters;
/** Maximum number of distinct keys. */
const int KEY_COUNT = 1000000;
/** Map of command line arguments */
boost::program_options::variables_map vm;
/** GridGain client interface. */
TGridClientPtr client;
/** Used to stop worker threads. */
TGridAtomicBool gExit;
/** Used to stop only collect status after warmup. */
TGridAtomicBool gWarmupDone;
/** Test types enumerator. */
enum GridClientCacheTestType {
PUT = 0,
GET,
PUT_TX,
GET_TX,
NUM_TEST_TYPES
};
/**
* Threadproc that prints out performance statistics every second.
*
*/
void StatsPrinterThreadProc() {
int LastIters = gIters.load(); // Save global iterations count so while
while (true) {
boost::this_thread::sleep(boost::posix_time::seconds(1));
int CurIters = gIters.load();
std::cout << "Operations for last second: " << CurIters - LastIters << std::endl;
LastIters = CurIters;
}
}
/**
* Converts string int test type enum.
*
* @param typeName String representation of test type.
* @param Enum representation of test type.
*/
GridClientCacheTestType testTypeFromString(std::string typeName) {
if (!strcmp(typeName.c_str(), "PUT"))
return PUT;
else if (!strcmp(typeName.c_str(), "PUT_TX"))
return PUT_TX;
else if (!strcmp(typeName.c_str(), "GET_TX"))
return GET_TX;
else if (!strcmp(typeName.c_str(), "GET"))
return GET;
return NUM_TEST_TYPES;
}
/**
* Returns a random int between 0 and max, thread safe.
*
* @param max A maximum value of a random integer.
* @param seed A seed to use. Modifiable. Needs to be passed each time.
*/
int randomInt(int max, unsigned int* seed) {
return rand_r(seed) % (max + 1);
}
/**
* Class representing one thread working with the client.
*/
class TestThread: private boost::noncopyable {
public:
/**
* Constructs the test thread.
*
* @param iterationCnt How many iterations to perform.
*/
TestThread(GridClientCacheTestType op) {
iters = 1;
seed = time(NULL);
thread = boost::thread(boost::bind(&TestThread::run, this, op));
}
/**
* Thread proc for running specific type of test.
*
* @param opType Type of test to run
*/
void run(GridClientCacheTestType opType) {
try {
TGridClientDataPtr data = client->data(vm["cachename"].as<string>());
switch (opType) {
case PUT: { // block of code to avoid "jump to the case label" compilation error
TGridClientVariantMap theMap;
theMap[randomInt(KEY_COUNT - 1, &seed)] = 42;
while (!gExit) {
data->putAll(theMap);
++gIters;
}
}
break;
case GET:
while (!gExit && ++iters) {
data->get((int16_t) randomInt(KEY_COUNT - 1, &seed));
++gIters;
}
break;
case PUT_TX:
case GET_TX:
std::cerr << "Unsupported test operation.\n";
break;
default:
std::cerr << "Invalid test operation.\n";
break;
}
}
catch (GridClientException& e) {
std::cerr << "GridClientException: " << e.what() << "\n";
}
catch (...) {
std::cerr << "Unknown exception.\n";
}
}
/** Joins the test thread. */
void join() {
thread.join();
}
/** Returns number of iterations completed. */
int getIters() {
return iters;
}
private:
/** Thread implementation. */
boost::thread thread;
/** Number of completed iterations. */
int iters;
/** A random seed used as a state for thread-safe random functions. */
unsigned int seed;
};
typedef std::shared_ptr<TestThread> TestThreadPtr;
int main(int argc, const char** argv) {
gIters = 0;
gExit = false;
gWarmupDone = false;
using namespace std;
using namespace boost::program_options;
// initialize random seed
srand(time(NULL));
// Declare the supported options.
options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("host", value<string>()->required(), "Host to connect to")
("port", value<int>()->required(), "Port to connect to")
("threads", value<int>()->required(), "Number of threads")
("testtype", value<string>()->required(), "Type of operations to run")
("cachename", value<string>()->required(), "Cache name")
("warmupseconds", value<int>()->required(), "Seconds to warm up")
("runseconds", value<int>()->required(), "Seconds to run")
("usetransactions", boost::program_options::value<bool>()->required(), "Use transactions (bool)");
try {
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
} catch (exception &e)
{
cerr << "Error parsing arguments: " << e.what() << endl;
cerr << desc << endl;
return 1;
}
if (vm.count("help"))
{
cout << desc << endl;
return 0;
}
GridClientConfiguration cfg = clientConfig();
std::vector<GridClientSocketAddress> servers;
servers.push_back(GridClientSocketAddress(vm["host"].as<string>(), vm["port"].as<int>()));
cfg.servers(servers);
GridClientDataConfiguration cacheCfg;
// Set remote cache name.
cacheCfg.name(vm["cachename"].as<string>());
std::shared_ptr<GridClientDataAffinity> ptrAffinity(new GridClientPartitionAffinity());
// Set client partitioned affinity for this cache.
cacheCfg.affinity(ptrAffinity);
std::vector<GridClientDataConfiguration> dataConfigurations;
dataConfigurations.push_back(cacheCfg);
cfg.dataConfiguration(dataConfigurations);
client = GridClientFactory::start(cfg);
std::vector<TestThreadPtr> workers;
boost::thread printerThread(StatsPrinterThreadProc);
int numThreads = vm["threads"].as<int>();
for (int i = 0; i < numThreads; i++) {
workers.push_back(TestThreadPtr(new TestThread(testTypeFromString(vm["testtype"].as<string>()))));
}
// let it warm up for requested amount of time and start gathering stats
boost::this_thread::sleep(boost::posix_time::seconds(vm["warmupseconds"].as<int>()));
gWarmupDone = true;
int ItersBefore = gIters.load(); // Save Iterations before final benchmark
// Let tests run for requested amount of time and then signal the exit
boost::this_thread::sleep(boost::posix_time::seconds(vm["runseconds"].as<int>()));
gExit = true;
int ItersAfter = gIters.load(); // Save iterations after final benchmark
//join all threads
for (std::vector<TestThreadPtr>::iterator i = workers.begin(); i != workers.end(); i++) {
(*i)->join();
}
workers.clear();
client.reset();
GridClientFactory::stopAll();
cout << "Average operations/s :" << (ItersAfter - ItersBefore) / vm["runseconds"].as<int>() << endl;
return EXIT_SUCCESS;
}
<commit_msg>gg-7432 Fix coding conventions<commit_after>/* @cpp.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
#include <vector>
#include <gridgain/gridgain.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/timer.hpp>
#include "gridtestcommon.hpp"
#include "gridgain/impl/gridclientpartitionedaffinity.hpp"
/** Global atomic used to calculate statistics. */
TGridAtomicInt gIters;
/** Maximum number of distinct keys. */
const int KEY_COUNT = 1000000;
/** Map of command line arguments */
boost::program_options::variables_map vm;
/** GridGain client interface. */
TGridClientPtr client;
/** Used to stop worker threads. */
TGridAtomicBool gExit;
/** Used to stop only collect status after warmup. */
TGridAtomicBool gWarmupDone;
/** Test types enumerator. */
enum GridClientCacheTestType {
PUT = 0,
GET,
PUT_TX,
GET_TX,
NUM_TEST_TYPES
};
/**
* Threadproc that prints out performance statistics every second.
*
*/
void StatsPrinterThreadProc() {
int LastIters = gIters.load(); // Save global iterations count so while
while (true) {
boost::this_thread::sleep(boost::posix_time::seconds(1));
int CurIters = gIters.load();
std::cout << "Operations for last second: " << CurIters - LastIters << std::endl;
LastIters = CurIters;
}
}
/**
* Converts string int test type enum.
*
* @param typeName String representation of test type.
* @param Enum representation of test type.
*/
GridClientCacheTestType testTypeFromString(std::string typeName) {
if (!strcmp(typeName.c_str(), "PUT"))
return PUT;
else if (!strcmp(typeName.c_str(), "PUT_TX"))
return PUT_TX;
else if (!strcmp(typeName.c_str(), "GET_TX"))
return GET_TX;
else if (!strcmp(typeName.c_str(), "GET"))
return GET;
return NUM_TEST_TYPES;
}
/**
* Returns a random int between 0 and max, thread safe.
*
* @param max A maximum value of a random integer.
* @param seed A seed to use. Modifiable. Needs to be passed each time.
*/
int randomInt(int max, unsigned int* seed) {
return rand_r(seed) % (max + 1);
}
/**
* Class representing one thread working with the client.
*/
class TestThread: private boost::noncopyable {
public:
/**
* Constructs the test thread.
*
* @param iterationCnt How many iterations to perform.
*/
TestThread(GridClientCacheTestType op) {
iters = 1;
seed = time(NULL);
thread = boost::thread(boost::bind(&TestThread::run, this, op));
}
/**
* Thread proc for running specific type of test.
*
* @param opType Type of test to run
*/
void run(GridClientCacheTestType opType) {
try {
TGridClientDataPtr data = client->data(vm["cachename"].as<string>());
switch (opType) {
case PUT: { // block of code to avoid "jump to the case label" compilation error
TGridClientVariantMap theMap;
theMap[randomInt(KEY_COUNT - 1, &seed)] = 42;
while (!gExit) {
data->putAll(theMap);
++gIters;
}
}
break;
case GET:
while (!gExit && ++iters) {
data->get((int16_t) randomInt(KEY_COUNT - 1, &seed));
++gIters;
}
break;
case PUT_TX:
case GET_TX:
std::cerr << "Unsupported test operation.\n";
break;
default:
std::cerr << "Invalid test operation.\n";
break;
}
}
catch (GridClientException& e) {
std::cerr << "GridClientException: " << e.what() << "\n";
}
catch (...) {
std::cerr << "Unknown exception.\n";
}
}
/** Joins the test thread. */
void join() {
thread.join();
}
/** Returns number of iterations completed. */
int getIters() {
return iters;
}
private:
/** Thread implementation. */
boost::thread thread;
/** Number of completed iterations. */
int iters;
/** A random seed used as a state for thread-safe random functions. */
unsigned int seed;
};
typedef std::shared_ptr<TestThread> TestThreadPtr;
int main(int argc, const char** argv) {
gIters = 0;
gExit = false;
gWarmupDone = false;
using namespace std;
using namespace boost::program_options;
// initialize random seed
srand(time(NULL));
// Declare the supported options.
options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("host", value<string>()->required(), "Host to connect to")
("port", value<int>()->required(), "Port to connect to")
("threads", value<int>()->required(), "Number of threads")
("testtype", value<string>()->required(), "Type of operations to run")
("cachename", value<string>()->required(), "Cache name")
("warmupseconds", value<int>()->required(), "Seconds to warm up")
("runseconds", value<int>()->required(), "Seconds to run")
("usetransactions", boost::program_options::value<bool>()->required(), "Use transactions (bool)");
try {
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
} catch (exception &e)
{
cerr << "Error parsing arguments: " << e.what() << endl;
cerr << desc << endl;
return 1;
}
if (vm.count("help"))
{
cout << desc << endl;
return 0;
}
GridClientConfiguration cfg = clientConfig();
std::vector<GridClientSocketAddress> servers;
servers.push_back(GridClientSocketAddress(vm["host"].as<string>(), vm["port"].as<int>()));
cfg.servers(servers);
GridClientDataConfiguration cacheCfg;
// Set remote cache name.
cacheCfg.name(vm["cachename"].as<string>());
std::shared_ptr<GridClientDataAffinity> ptrAffinity(new GridClientPartitionAffinity());
// Set client partitioned affinity for this cache.
cacheCfg.affinity(ptrAffinity);
std::vector<GridClientDataConfiguration> dataConfigurations;
dataConfigurations.push_back(cacheCfg);
cfg.dataConfiguration(dataConfigurations);
client = GridClientFactory::start(cfg);
std::vector<TestThreadPtr> workers;
boost::thread printerThread(StatsPrinterThreadProc);
int numThreads = vm["threads"].as<int>();
for (int i = 0; i < numThreads; i++) {
workers.push_back(TestThreadPtr(new TestThread(testTypeFromString(vm["testtype"].as<string>()))));
}
// let it warm up for requested amount of time and start gathering stats
boost::this_thread::sleep(boost::posix_time::seconds(vm["warmupseconds"].as<int>()));
gWarmupDone = true;
int itersBeforeTest = gIters.load(); // Save Iterations before final benchmark
// Let tests run for requested amount of time and then signal the exit
boost::this_thread::sleep(boost::posix_time::seconds(vm["runseconds"].as<int>()));
gExit = true;
int itersAfterTest = gIters.load(); // Save iterations after final benchmark
//join all threads
for (std::vector<TestThreadPtr>::iterator i = workers.begin(); i != workers.end(); i++) {
(*i)->join();
}
workers.clear();
client.reset();
GridClientFactory::stopAll();
cout << "Average operations/s :" << (itersAfterTest - itersBeforeTest) / vm["runseconds"].as<int>() << endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Oluwatobi Adeyinka
*
* 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 "top_podcasts_panel.h"
#include "discover_item_panel.h"
TopPodcastsPanel::TopPodcastsPanel(wxWindow * parent, DiscoveryPanelManager & panelManager) : wxScrolledWindow(parent) {
mainSizer = new wxBoxSizer(wxVERTICAL);
topPodcasts = panelManager.getTopPodcasts();
setupSectionHeader();
setupFirstRow();
setupSecondRow();
this->SetBackgroundColour(wxColour(wxT("#ffffff")));
this->SetSizer(mainSizer);
// this part makes the scrollbars show up
this->FitInside(); // ask the sizer about the needed size
this->SetScrollRate(5, 5);
}
void TopPodcastsPanel::setupSectionHeader() {
auto * titlePanel = new wxPanel(this);
auto * titlePanelSizer = new wxBoxSizer(wxHORIZONTAL);
auto * sectionTitle = new wxStaticText(titlePanel, wxID_ANY, wxT("Top Podcasts"));
wxFont sectionTitleFont = sectionTitle->GetFont();
sectionTitleFont.SetPointSize(16);
sectionTitle->SetFont(sectionTitleFont);
titlePanel->SetBackgroundColour(wxColour(wxT("#ffffff")));
titlePanelSizer->Add(sectionTitle, 1, wxALL, 5);
titlePanel->SetSizer(titlePanelSizer);
mainSizer->Add(titlePanel, 1, wxEXPAND, 5);
}
void TopPodcastsPanel::setupFirstRow() {
auto * rowPanel = new wxPanel(this);
auto * rowPanelSizer = new wxBoxSizer(wxHORIZONTAL);
for (std::vector<int>::size_type i = 0; i != topPodcasts.size()/2; i++) {
Podcast podcast = topPodcasts[i];
auto * itemPanel = new DiscoverItemPanel(rowPanel, podcast);
rowPanelSizer->Add(itemPanel, wxID_ANY, wxRIGHT | wxEXPAND, 10);
}
rowPanel->SetSizer(rowPanelSizer);
mainSizer->Add(rowPanel, 1, wxALL | wxEXPAND, 5);
}
void TopPodcastsPanel::setupSecondRow() {
auto * rowPanel = new wxPanel(this);
auto * rowPanelSizer = new wxBoxSizer(wxHORIZONTAL);
for (std::vector<int>::size_type i = 24; i != topPodcasts.size(); i++) {
Podcast podcast = topPodcasts[i];
auto * itemPanel = new DiscoverItemPanel(rowPanel, podcast);
rowPanelSizer->Add(itemPanel, wxID_ANY, wxRIGHT | wxEXPAND, 10);
}
rowPanel->SetSizer(rowPanelSizer);
mainSizer->Add(rowPanel, 1, wxALL | wxEXPAND, 5);
}
<commit_msg>dev progress: discovery panel<commit_after>/*
* Copyright 2017 Oluwatobi Adeyinka
*
* 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 "top_podcasts_panel.h"
#include "discover_item_panel.h"
TopPodcastsPanel::TopPodcastsPanel(wxWindow * parent, DiscoveryPanelManager & panelManager) : wxScrolledWindow(parent) {
mainSizer = new wxBoxSizer(wxVERTICAL);
topPodcasts = panelManager.getTopPodcasts();
setupSectionHeader();
setupFirstRow();
setupSecondRow();
this->SetBackgroundColour(wxColour(wxT("#ffffff")));
this->SetSizer(mainSizer);
// this part makes the scrollbars show up
this->FitInside(); // ask the sizer about the needed size
this->SetScrollRate(5, 5);
}
void TopPodcastsPanel::setupSectionHeader() {
auto * titlePanel = new wxPanel(this);
titlePanel->SetBackgroundColour(wxColour(wxT("#ffffff")));
auto * sectionTitle = new wxStaticText(titlePanel, wxID_ANY, wxT("Top Podcasts"));
wxFont sectionTitleFont = sectionTitle->GetFont();
sectionTitleFont.SetPointSize(16);
sectionTitle->SetFont(sectionTitleFont);
mainSizer->Add(titlePanel, 0, wxLEFT | wxBOTTOM, 5);
}
void TopPodcastsPanel::setupFirstRow() {
auto * rowPanel = new wxPanel(this);
auto * rowPanelSizer = new wxBoxSizer(wxHORIZONTAL);
for (std::vector<int>::size_type i = 0; i != topPodcasts.size()/2; i++) {
Podcast podcast = topPodcasts[i];
auto * itemPanel = new DiscoverItemPanel(rowPanel, podcast);
rowPanelSizer->Add(itemPanel, wxID_ANY, wxRIGHT | wxEXPAND, 10);
}
rowPanel->SetSizer(rowPanelSizer);
mainSizer->Add(rowPanel, 1, wxALL | wxEXPAND, 5);
}
void TopPodcastsPanel::setupSecondRow() {
auto * rowPanel = new wxPanel(this);
auto * rowPanelSizer = new wxBoxSizer(wxHORIZONTAL);
for (std::vector<int>::size_type i = 24; i != topPodcasts.size(); i++) {
Podcast podcast = topPodcasts[i];
auto * itemPanel = new DiscoverItemPanel(rowPanel, podcast);
rowPanelSizer->Add(itemPanel, wxID_ANY, wxRIGHT | wxEXPAND, 10);
}
rowPanel->SetSizer(rowPanelSizer);
mainSizer->Add(rowPanel, 1, wxALL | wxEXPAND, 5);
}
<|endoftext|> |
<commit_before>/**
* A command-line calculator that uses a sequental grammar instead of left-recursion.
*/
#include <iostream>
#include <unordered_map>
#include <cmath>
#include <numeric>
#include <lars/parser/generator.h>
int main() {
using namespace std;
using VariableMap = unordered_map<string, float>;
lars::ParserGenerator<float, VariableMap &> calculator;
auto &g = calculator;
g.setSeparator(g["Whitespace"] << "[\t ]");
g["Expression"] << "Set | Sum";
g["Set"] << "Name '=' Sum" >> [](auto e, auto &v){ return v[e[0].string()] = e[1].evaluate(v); };
g["Sum"] << "Product Summand*" >> [=](auto e, auto &v){
return std::accumulate(e.begin(), e.end(), 0, [&](auto a, auto b){ return a+b.evaluate(v); });
};
g["Product"] << "Power Term*" >> [](auto e, auto &v){
return std::accumulate(e.begin(), e.end(), 1, [&](auto a, auto b){ return a*b.evaluate(v); });
};
g["Power"] << "Atomic ('^' Power) | Atomic" >> [](auto e, auto &v){
return e.size() == 2 ? pow(e[0].evaluate(v), e[1].evaluate(v)) : e[0].evaluate(v);
};
g["Atomic" ] << "Number | Brackets | Variable";
shared_ptr<lars::peg::Rule> sumOp = g["SumOp"] << "'+'", subOp = g["SubOp"] << "'-'";
g["Summand"] << "(SumOp | SubOp) Product" >> [=](auto e, auto &v){
return e[0].rule() == subOp ? -e[1].evaluate(v) : e[1].evaluate(v);
};
shared_ptr<lars::peg::Rule> mulOp = g["MulOp"] << "'*'", divOp = g["DivOp"] << "'/'";
g["Term"] << "(MulOp | DivOp) Power" >> [=](auto e, auto &v){
return e[0].rule() == divOp ? 1/e[1].evaluate(v) : e[1].evaluate(v);
};
g["Brackets" ] << "'(' Sum ')'";
g["Variable" ] << "Name" >> [](auto e, auto &v){ return v[e[0].string()]; };
g["Name" ] << "[a-zA-Z] [a-zA-Z0-9]*";
// We can re-use previously defined programs as rules
g.setProgramRule("Number", lars::peg::createFloatProgram());
g.setStart(g["Expression"]);
cout << "Enter an expression to be evaluated.\n";
VariableMap variables;
while (true) {
string str;
cout << "> ";
getline(cin,str);
if(str == "q" || str == "quit"){ break; }
try {
auto result = calculator.run(str, variables);
cout << str << " = " << result << endl;
} catch (lars::SyntaxError error) {
auto syntax = error.syntax;
cout << " ";
cout << string(syntax->begin, ' ');
cout << string(syntax->length(), '~');
cout << "^\n";
cout << " " << "Syntax error while parsing " << syntax->rule->name << endl;
}
}
return 0;
}
<commit_msg>simplify sequental example (#29)<commit_after>/**
* A command-line calculator that uses a sequental grammar instead of left-recursion.
*/
#include <iostream>
#include <unordered_map>
#include <cmath>
#include <numeric>
#include <lars/parser/generator.h>
int main() {
using namespace std;
using VariableMap = unordered_map<string, float>;
lars::ParserGenerator<float, VariableMap &> calculator;
auto &g = calculator;
g.setSeparator(g["Whitespace"] << "[\t ]");
g["Expression"] << "Assign | Sum";
g["Assign"] << "Name '=' Sum" >> [](auto e, auto &v){ return v[e[0].string()] = e[1].evaluate(v); };
g["Sum"] << "Product Summand*" >> [=](auto e, auto &v){
return std::accumulate(e.begin(), e.end(), 0, [&](auto a, auto b){ return a+b.evaluate(v); });
};
g["PositiveSummand"] << "'+' Product" >> [=](auto e, auto &v){ return e[0].evaluate(v); };
g["NegativeSummand"] << "'-' Product" >> [=](auto e, auto &v){ return -e[0].evaluate(v); };
g["Summand"] << "PositiveSummand | NegativeSummand";
g["Product"] << "Power Term*" >> [](auto e, auto &v){
return std::accumulate(e.begin(), e.end(), 1, [&](auto a, auto b){ return a*b.evaluate(v); });
};
g["NormalTerm"] << "'*' Power" >> [=](auto e, auto &v){ return e[0].evaluate(v); };
g["InverseTerm"] << "'/' Power" >> [=](auto e, auto &v){ return 1/e[0].evaluate(v); };
g["Term"] << "NormalTerm | InverseTerm";
g["Power"] << "Atomic ('^' Power) | Atomic" >> [](auto e, auto &v){
return e.size() == 2 ? pow(e[0].evaluate(v), e[1].evaluate(v)) : e[0].evaluate(v);
};
g["Atomic" ] << "Number | Brackets | Variable";
g["Brackets" ] << "'(' Sum ')'";
g["Variable" ] << "Name" >> [](auto e, auto &v){ return v[e[0].string()]; };
g["Name" ] << "[a-zA-Z] [a-zA-Z0-9]*";
// We can also use other programs as rules
g.setProgramRule("Number", lars::peg::createFloatProgram());
g.setStart(g["Expression"]);
cout << "Enter an expression to be evaluated.\n";
VariableMap variables;
while (true) {
string str;
cout << "> ";
getline(cin,str);
if(str == "q" || str == "quit"){ break; }
try {
auto result = calculator.run(str, variables);
cout << str << " = " << result << endl;
} catch (lars::SyntaxError error) {
auto syntax = error.syntax;
cout << " ";
cout << string(syntax->begin, ' ');
cout << string(syntax->length(), '~');
cout << "^\n";
cout << " " << "Syntax error while parsing " << syntax->rule->name << endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
#include "opencv2/opencv_modules.hpp"
#include "cvconfig.h"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/core/cuda.hpp"
#include "opencv2/core/opengl.hpp"
#include "opencv2/core/va_intel.hpp"
#include "opencv2/core/private.hpp"
#include "opencv2/core/private.cuda.hpp"
#ifdef HAVE_OPENCL
#include "opencv2/core/ocl.hpp"
#endif
#include <assert.h>
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <float.h>
#include <cstring>
#include <cassert>
#define USE_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2))
#define USE_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2))
#define USE_AVX (cv::checkHardwareSupport(CV_CPU_AVX))
#define USE_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2))
#include "opencv2/core/hal/hal.hpp"
#include "opencv2/core/hal/intrin.hpp"
#include "opencv2/core/sse_utils.hpp"
#include "opencv2/core/neon_utils.hpp"
#include "opencv2/core/vsx_utils.hpp"
#include "hal_replacement.hpp"
#define GET_OPTIMIZED(func) (func)
namespace cv
{
// -128.f ... 255.f
extern const float g_8x32fTab[];
#define CV_8TO32F(x) cv::g_8x32fTab[(x)+128]
extern const ushort g_8x16uSqrTab[];
#define CV_SQR_8U(x) cv::g_8x16uSqrTab[(x)+255]
extern const uchar g_Saturate8u[];
#define CV_FAST_CAST_8U(t) (assert(-256 <= (t) && (t) <= 512), cv::g_Saturate8u[(t)+256])
#define CV_MIN_8U(a,b) ((a) - CV_FAST_CAST_8U((a) - (b)))
#define CV_MAX_8U(a,b) ((a) + CV_FAST_CAST_8U((b) - (a)))
template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a + b); }
};
template<typename T1, typename T2=T1, typename T3=T1> struct OpSub
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a - b); }
};
template<typename T1, typename T2=T1, typename T3=T1> struct OpRSub
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(b - a); }
};
template<typename T> struct OpMin
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator ()(const T a, const T b) const { return std::min(a, b); }
};
template<typename T> struct OpMax
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator ()(const T a, const T b) const { return std::max(a, b); }
};
template<typename T> struct OpAbsDiff
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()(T a, T b) const { return a > b ? a - b : b - a; }
};
// specializations to prevent "-0" results
template<> struct OpAbsDiff<float>
{
typedef float type1;
typedef float type2;
typedef float rtype;
float operator()(float a, float b) const { return std::abs(a - b); }
};
template<> struct OpAbsDiff<double>
{
typedef double type1;
typedef double type2;
typedef double rtype;
double operator()(double a, double b) const { return std::abs(a - b); }
};
template<typename T> struct OpAnd
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T b ) const { return a & b; }
};
template<typename T> struct OpOr
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T b ) const { return a | b; }
};
template<typename T> struct OpXor
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T b ) const { return a ^ b; }
};
template<typename T> struct OpNot
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T ) const { return ~a; }
};
template<> inline uchar OpAdd<uchar>::operator ()(uchar a, uchar b) const
{ return CV_FAST_CAST_8U(a + b); }
template<> inline uchar OpSub<uchar>::operator ()(uchar a, uchar b) const
{ return CV_FAST_CAST_8U(a - b); }
template<> inline short OpAbsDiff<short>::operator ()(short a, short b) const
{ return saturate_cast<short>(std::abs(a - b)); }
template<> inline schar OpAbsDiff<schar>::operator ()(schar a, schar b) const
{ return saturate_cast<schar>(std::abs(a - b)); }
template<> inline uchar OpMin<uchar>::operator ()(uchar a, uchar b) const { return CV_MIN_8U(a, b); }
template<> inline uchar OpMax<uchar>::operator ()(uchar a, uchar b) const { return CV_MAX_8U(a, b); }
typedef void (*UnaryFunc)(const uchar* src1, size_t step1,
uchar* dst, size_t step, Size sz,
void*);
typedef void (*BinaryFunc)(const uchar* src1, size_t step1,
const uchar* src2, size_t step2,
uchar* dst, size_t step, Size sz,
void*);
typedef void (*BinaryFuncC)(const uchar* src1, size_t step1,
const uchar* src2, size_t step2,
uchar* dst, size_t step, int width, int height,
void*);
BinaryFunc getConvertFunc(int sdepth, int ddepth);
BinaryFunc getConvertScaleFunc(int sdepth, int ddepth);
BinaryFunc getCopyMaskFunc(size_t esz);
/* default memory block for sparse array elements */
#define CV_SPARSE_MAT_BLOCK (1<<12)
/* initial hash table size */
#define CV_SPARSE_HASH_SIZE0 (1<<10)
/* maximal average node_count/hash_size ratio beyond which hash table is resized */
#define CV_SPARSE_HASH_RATIO 3
// There is some mess in code with vectors representation.
// Both vector-column / vector-rows are used with dims=2 (as Mat2D always).
// Reshape matrices if necessary (in case of vectors) and returns size with scaled width.
Size getContinuousSize2D(Mat& m1, int widthScale=1);
Size getContinuousSize2D(Mat& m1, Mat& m2, int widthScale=1);
Size getContinuousSize2D(Mat& m1, Mat& m2, Mat& m3, int widthScale=1);
void setSize( Mat& m, int _dims, const int* _sz, const size_t* _steps, bool autoSteps=false );
void finalizeHdr(Mat& m);
int updateContinuityFlag(int flags, int dims, const int* size, const size_t* step);
struct NoVec
{
size_t operator()(const void*, const void*, void*, size_t) const { return 0; }
};
#define CV_SPLIT_MERGE_MAX_BLOCK_SIZE(cn) ((INT_MAX/4)/(cn)) // HAL implementation accepts 'int' len, so INT_MAX doesn't work here
enum { BLOCK_SIZE = 1024 };
#if defined HAVE_IPP && (IPP_VERSION_X100 >= 700)
#define ARITHM_USE_IPP 1
#else
#define ARITHM_USE_IPP 0
#endif
inline bool checkScalar(const Mat& sc, int atype, _InputArray::KindFlag sckind, _InputArray::KindFlag akind)
{
if( sc.dims > 2 || !sc.isContinuous() )
return false;
Size sz = sc.size();
if(sz.width != 1 && sz.height != 1)
return false;
int cn = CV_MAT_CN(atype);
if( akind == _InputArray::MATX && sckind != _InputArray::MATX )
return false;
return sz == Size(1, 1) || sz == Size(1, cn) || sz == Size(cn, 1) ||
(sz == Size(1, 4) && sc.type() == CV_64F && cn <= 4);
}
inline bool checkScalar(InputArray sc, int atype, _InputArray::KindFlag sckind, _InputArray::KindFlag akind)
{
if( sc.dims() > 2 || !sc.isContinuous() )
return false;
Size sz = sc.size();
if(sz.width != 1 && sz.height != 1)
return false;
int cn = CV_MAT_CN(atype);
if( akind == _InputArray::MATX && sckind != _InputArray::MATX )
return false;
return sz == Size(1, 1) || sz == Size(1, cn) || sz == Size(cn, 1) ||
(sz == Size(1, 4) && sc.type() == CV_64F && cn <= 4);
}
void convertAndUnrollScalar( const Mat& sc, int buftype, uchar* scbuf, size_t blocksize );
#ifdef CV_COLLECT_IMPL_DATA
struct ImplCollector
{
ImplCollector()
{
useCollection = false;
implFlags = 0;
}
bool useCollection; // enable/disable impl data collection
int implFlags;
std::vector<int> implCode;
std::vector<String> implFun;
cv::Mutex mutex;
};
#endif
struct CoreTLSData
{
CoreTLSData() :
//#ifdef HAVE_OPENCL
device(0), useOpenCL(-1),
//#endif
useIPP(-1),
useIPP_NE(-1)
#ifdef HAVE_OPENVX
,useOpenVX(-1)
#endif
{}
RNG rng;
//#ifdef HAVE_OPENCL
int device; // device index of an array of devices in a context, see also Device::getDefault
ocl::Queue oclQueue; // the queue used for running a kernel, see also getQueue, Kernel::run
int useOpenCL; // 1 - use, 0 - do not use, -1 - auto/not initialized
//#endif
int useIPP; // 1 - use, 0 - do not use, -1 - auto/not initialized
int useIPP_NE; // 1 - use, 0 - do not use, -1 - auto/not initialized
#ifdef HAVE_OPENVX
int useOpenVX; // 1 - use, 0 - do not use, -1 - auto/not initialized
#endif
};
CoreTLSData& getCoreTlsData();
#if defined(BUILD_SHARED_LIBS)
#if defined _WIN32 || defined WINCE
#define CL_RUNTIME_EXPORT __declspec(dllexport)
#elif defined __GNUC__ && __GNUC__ >= 4
#define CL_RUNTIME_EXPORT __attribute__ ((visibility ("default")))
#else
#define CL_RUNTIME_EXPORT
#endif
#else
#define CL_RUNTIME_EXPORT
#endif
extern CV_EXPORTS
bool __termination; // skip some cleanups, because process is terminating
// (for example, if ExitProcess() was already called)
cv::Mutex& getInitializationMutex();
// TODO Memory barriers?
#define CV_SINGLETON_LAZY_INIT_(TYPE, INITIALIZER, RET_VALUE) \
static TYPE* volatile instance = NULL; \
if (instance == NULL) \
{ \
cv::AutoLock lock(cv::getInitializationMutex()); \
if (instance == NULL) \
instance = INITIALIZER; \
} \
return RET_VALUE;
#define CV_SINGLETON_LAZY_INIT(TYPE, INITIALIZER) CV_SINGLETON_LAZY_INIT_(TYPE, INITIALIZER, instance)
#define CV_SINGLETON_LAZY_INIT_REF(TYPE, INITIALIZER) CV_SINGLETON_LAZY_INIT_(TYPE, INITIALIZER, *instance)
int cv_snprintf(char* buf, int len, const char* fmt, ...);
int cv_vsnprintf(char* buf, int len, const char* fmt, va_list args);
}
#endif /*_CXCORE_INTERNAL_H_*/
<commit_msg>use C++11 static variables as memory barrier<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
#include "opencv2/opencv_modules.hpp"
#include "cvconfig.h"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/core/cuda.hpp"
#include "opencv2/core/opengl.hpp"
#include "opencv2/core/va_intel.hpp"
#include "opencv2/core/private.hpp"
#include "opencv2/core/private.cuda.hpp"
#ifdef HAVE_OPENCL
#include "opencv2/core/ocl.hpp"
#endif
#include <assert.h>
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <float.h>
#include <cstring>
#include <cassert>
#define USE_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2))
#define USE_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2))
#define USE_AVX (cv::checkHardwareSupport(CV_CPU_AVX))
#define USE_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2))
#include "opencv2/core/hal/hal.hpp"
#include "opencv2/core/hal/intrin.hpp"
#include "opencv2/core/sse_utils.hpp"
#include "opencv2/core/neon_utils.hpp"
#include "opencv2/core/vsx_utils.hpp"
#include "hal_replacement.hpp"
#define GET_OPTIMIZED(func) (func)
namespace cv
{
// -128.f ... 255.f
extern const float g_8x32fTab[];
#define CV_8TO32F(x) cv::g_8x32fTab[(x)+128]
extern const ushort g_8x16uSqrTab[];
#define CV_SQR_8U(x) cv::g_8x16uSqrTab[(x)+255]
extern const uchar g_Saturate8u[];
#define CV_FAST_CAST_8U(t) (assert(-256 <= (t) && (t) <= 512), cv::g_Saturate8u[(t)+256])
#define CV_MIN_8U(a,b) ((a) - CV_FAST_CAST_8U((a) - (b)))
#define CV_MAX_8U(a,b) ((a) + CV_FAST_CAST_8U((b) - (a)))
template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a + b); }
};
template<typename T1, typename T2=T1, typename T3=T1> struct OpSub
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a - b); }
};
template<typename T1, typename T2=T1, typename T3=T1> struct OpRSub
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(b - a); }
};
template<typename T> struct OpMin
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator ()(const T a, const T b) const { return std::min(a, b); }
};
template<typename T> struct OpMax
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator ()(const T a, const T b) const { return std::max(a, b); }
};
template<typename T> struct OpAbsDiff
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()(T a, T b) const { return a > b ? a - b : b - a; }
};
// specializations to prevent "-0" results
template<> struct OpAbsDiff<float>
{
typedef float type1;
typedef float type2;
typedef float rtype;
float operator()(float a, float b) const { return std::abs(a - b); }
};
template<> struct OpAbsDiff<double>
{
typedef double type1;
typedef double type2;
typedef double rtype;
double operator()(double a, double b) const { return std::abs(a - b); }
};
template<typename T> struct OpAnd
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T b ) const { return a & b; }
};
template<typename T> struct OpOr
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T b ) const { return a | b; }
};
template<typename T> struct OpXor
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T b ) const { return a ^ b; }
};
template<typename T> struct OpNot
{
typedef T type1;
typedef T type2;
typedef T rtype;
T operator()( T a, T ) const { return ~a; }
};
template<> inline uchar OpAdd<uchar>::operator ()(uchar a, uchar b) const
{ return CV_FAST_CAST_8U(a + b); }
template<> inline uchar OpSub<uchar>::operator ()(uchar a, uchar b) const
{ return CV_FAST_CAST_8U(a - b); }
template<> inline short OpAbsDiff<short>::operator ()(short a, short b) const
{ return saturate_cast<short>(std::abs(a - b)); }
template<> inline schar OpAbsDiff<schar>::operator ()(schar a, schar b) const
{ return saturate_cast<schar>(std::abs(a - b)); }
template<> inline uchar OpMin<uchar>::operator ()(uchar a, uchar b) const { return CV_MIN_8U(a, b); }
template<> inline uchar OpMax<uchar>::operator ()(uchar a, uchar b) const { return CV_MAX_8U(a, b); }
typedef void (*UnaryFunc)(const uchar* src1, size_t step1,
uchar* dst, size_t step, Size sz,
void*);
typedef void (*BinaryFunc)(const uchar* src1, size_t step1,
const uchar* src2, size_t step2,
uchar* dst, size_t step, Size sz,
void*);
typedef void (*BinaryFuncC)(const uchar* src1, size_t step1,
const uchar* src2, size_t step2,
uchar* dst, size_t step, int width, int height,
void*);
BinaryFunc getConvertFunc(int sdepth, int ddepth);
BinaryFunc getConvertScaleFunc(int sdepth, int ddepth);
BinaryFunc getCopyMaskFunc(size_t esz);
/* default memory block for sparse array elements */
#define CV_SPARSE_MAT_BLOCK (1<<12)
/* initial hash table size */
#define CV_SPARSE_HASH_SIZE0 (1<<10)
/* maximal average node_count/hash_size ratio beyond which hash table is resized */
#define CV_SPARSE_HASH_RATIO 3
// There is some mess in code with vectors representation.
// Both vector-column / vector-rows are used with dims=2 (as Mat2D always).
// Reshape matrices if necessary (in case of vectors) and returns size with scaled width.
Size getContinuousSize2D(Mat& m1, int widthScale=1);
Size getContinuousSize2D(Mat& m1, Mat& m2, int widthScale=1);
Size getContinuousSize2D(Mat& m1, Mat& m2, Mat& m3, int widthScale=1);
void setSize( Mat& m, int _dims, const int* _sz, const size_t* _steps, bool autoSteps=false );
void finalizeHdr(Mat& m);
int updateContinuityFlag(int flags, int dims, const int* size, const size_t* step);
struct NoVec
{
size_t operator()(const void*, const void*, void*, size_t) const { return 0; }
};
#define CV_SPLIT_MERGE_MAX_BLOCK_SIZE(cn) ((INT_MAX/4)/(cn)) // HAL implementation accepts 'int' len, so INT_MAX doesn't work here
enum { BLOCK_SIZE = 1024 };
#if defined HAVE_IPP && (IPP_VERSION_X100 >= 700)
#define ARITHM_USE_IPP 1
#else
#define ARITHM_USE_IPP 0
#endif
inline bool checkScalar(const Mat& sc, int atype, _InputArray::KindFlag sckind, _InputArray::KindFlag akind)
{
if( sc.dims > 2 || !sc.isContinuous() )
return false;
Size sz = sc.size();
if(sz.width != 1 && sz.height != 1)
return false;
int cn = CV_MAT_CN(atype);
if( akind == _InputArray::MATX && sckind != _InputArray::MATX )
return false;
return sz == Size(1, 1) || sz == Size(1, cn) || sz == Size(cn, 1) ||
(sz == Size(1, 4) && sc.type() == CV_64F && cn <= 4);
}
inline bool checkScalar(InputArray sc, int atype, _InputArray::KindFlag sckind, _InputArray::KindFlag akind)
{
if( sc.dims() > 2 || !sc.isContinuous() )
return false;
Size sz = sc.size();
if(sz.width != 1 && sz.height != 1)
return false;
int cn = CV_MAT_CN(atype);
if( akind == _InputArray::MATX && sckind != _InputArray::MATX )
return false;
return sz == Size(1, 1) || sz == Size(1, cn) || sz == Size(cn, 1) ||
(sz == Size(1, 4) && sc.type() == CV_64F && cn <= 4);
}
void convertAndUnrollScalar( const Mat& sc, int buftype, uchar* scbuf, size_t blocksize );
#ifdef CV_COLLECT_IMPL_DATA
struct ImplCollector
{
ImplCollector()
{
useCollection = false;
implFlags = 0;
}
bool useCollection; // enable/disable impl data collection
int implFlags;
std::vector<int> implCode;
std::vector<String> implFun;
cv::Mutex mutex;
};
#endif
struct CoreTLSData
{
CoreTLSData() :
//#ifdef HAVE_OPENCL
device(0), useOpenCL(-1),
//#endif
useIPP(-1),
useIPP_NE(-1)
#ifdef HAVE_OPENVX
,useOpenVX(-1)
#endif
{}
RNG rng;
//#ifdef HAVE_OPENCL
int device; // device index of an array of devices in a context, see also Device::getDefault
ocl::Queue oclQueue; // the queue used for running a kernel, see also getQueue, Kernel::run
int useOpenCL; // 1 - use, 0 - do not use, -1 - auto/not initialized
//#endif
int useIPP; // 1 - use, 0 - do not use, -1 - auto/not initialized
int useIPP_NE; // 1 - use, 0 - do not use, -1 - auto/not initialized
#ifdef HAVE_OPENVX
int useOpenVX; // 1 - use, 0 - do not use, -1 - auto/not initialized
#endif
};
CoreTLSData& getCoreTlsData();
#if defined(BUILD_SHARED_LIBS)
#if defined _WIN32 || defined WINCE
#define CL_RUNTIME_EXPORT __declspec(dllexport)
#elif defined __GNUC__ && __GNUC__ >= 4
#define CL_RUNTIME_EXPORT __attribute__ ((visibility ("default")))
#else
#define CL_RUNTIME_EXPORT
#endif
#else
#define CL_RUNTIME_EXPORT
#endif
extern CV_EXPORTS
bool __termination; // skip some cleanups, because process is terminating
// (for example, if ExitProcess() was already called)
cv::Mutex& getInitializationMutex();
#define CV_SINGLETON_LAZY_INIT_(TYPE, INITIALIZER, RET_VALUE) \
static TYPE* const instance = INITIALIZER; \
return RET_VALUE;
#define CV_SINGLETON_LAZY_INIT(TYPE, INITIALIZER) CV_SINGLETON_LAZY_INIT_(TYPE, INITIALIZER, instance)
#define CV_SINGLETON_LAZY_INIT_REF(TYPE, INITIALIZER) CV_SINGLETON_LAZY_INIT_(TYPE, INITIALIZER, *instance)
int cv_snprintf(char* buf, int len, const char* fmt, ...);
int cv_vsnprintf(char* buf, int len, const char* fmt, va_list args);
}
#endif /*_CXCORE_INTERNAL_H_*/
<|endoftext|> |
<commit_before>
// Locals
#include "dns_server.hpp"
#include <stdlib.h>
// EASTL new/delete
//void* operator new[](size_t size, const char* pName, int flags, unsigned debugFlags, const char* file, int line)
void* operator new[](size_t size, const char*, int, unsigned, const char*, int)
{
//printf("[new:%lu] %s %d %d from %s:%d\n", size, pName, flags, debugFlags, file, line);
return malloc(size);
}
//void* operator new[](size_t size, size_t alignment, size_t alignmentOffset, const char* pName, int flags, unsigned debugFlags, const char* file, int line)
void* operator new[](size_t size, size_t, size_t, const char*, int, unsigned, const char*, int)
{
//printf("[new:%lu] %s %d %d from %s:%d\n", size, pName, flags, debugFlags, file, line);
return malloc(size);
}
void* operator new (size_t size)
{
return malloc(size);
}
void* operator new[] (size_t size)
{
return malloc(size);
}
// placement new/delete
void* operator new (size_t, void* p) { return p; }
void* operator new[](size_t, void* p) { return p; }
extern "C" void __assert_func(int){};
DNS_server myDnsServer;
int main(){
std::cout << "*** Service is up - with OS Included! ***" << std::endl;
std::cout << "Starting DNS prototype\n";
/// www.google.com ///
std::vector<net::IP4::addr> mapping1;
mapping1.push_back( { 213, 155, 151, 187 } );
mapping1.push_back( { 213, 155, 151, 185 } );
mapping1.push_back( { 213, 155, 151, 180 } );
mapping1.push_back( { 213, 155, 151, 183 } );
mapping1.push_back( { 213, 155, 151, 186 } );
mapping1.push_back( { 213, 155, 151, 184 } );
mapping1.push_back( { 213, 155, 151, 181 } );
mapping1.push_back( { 213, 155, 151, 182 } );
myDnsServer.addMapping("www.google.com.", mapping1);
/// ///
//class Inet{} inet*;
net::Inet* inet;
myDnsServer.start(inet);
std::cout << "<DNS SERVER> Listening on UDP port 53" << std::endl;
std::cout << "Service out!" << std::endl;
}
<commit_msg>Linux DNS version<commit_after>
// Locals
#include "dns_server.hpp"
#include <stdlib.h>
// EASTL new/delete
//void* operator new[](size_t size, const char* pName, int flags, unsigned debugFlags, const char* file, int line)
void* operator new[](size_t size, const char*, int, unsigned, const char*, int)
{
//printf("[new:%lu] %s %d %d from %s:%d\n", size, pName, flags, debugFlags, file, line);
return malloc(size);
}
//void* operator new[](size_t size, size_t alignment, size_t alignmentOffset, const char* pName, int flags, unsigned debugFlags, const char* file, int line)
void* operator new[](size_t size, size_t, size_t, const char*, int, unsigned, const char*, int)
{
//printf("[new:%lu] %s %d %d from %s:%d\n", size, pName, flags, debugFlags, file, line);
return malloc(size);
}
void* operator new (size_t size)
{
return malloc(size);
}
void* operator new[] (size_t size)
{
return malloc(size);
}
// placement new/delete
void* operator new (size_t, void* p) { return p; }
void* operator new[](size_t, void* p) { return p; }
extern "C" void __assert_func(int){};
//DNS_server myDnsServer;
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace net;
int main()
{
std::cout << "*** Service is up - with OS Included! ***" << std::endl;
std::cout << "Starting DNS prototype\n";
/// www.google.com ///
std::vector<IP4::addr> mapping1;
mapping1.push_back( { 213, 155, 151, 187 } );
mapping1.push_back( { 213, 155, 151, 185 } );
mapping1.push_back( { 213, 155, 151, 180 } );
mapping1.push_back( { 213, 155, 151, 183 } );
mapping1.push_back( { 213, 155, 151, 186 } );
mapping1.push_back( { 213, 155, 151, 184 } );
mapping1.push_back( { 213, 155, 151, 181 } );
mapping1.push_back( { 213, 155, 151, 182 } );
eastl::map<eastl::string, eastl::vector<IP4::addr>> lookup;
lookup["www.google.com."] = mapping1;
/// ///
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
perror("socket() failed");
return -1;
}
in_addr lan_addr;
inet_pton(AF_INET, "128.39.74.243", &lan_addr);
struct sockaddr_in myaddr;
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = lan_addr.s_addr;
myaddr.sin_port = htons(DNS::DNS_SERVICE_PORT);
if (bind(fd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0)
{
perror("bind failed");
return -1;
}
std::cout << "<DNS SERVER> Listening on UDP port 53" << std::endl;
static const int BUFSIZE = 1500;
char* buffer = new char[BUFSIZE];
struct sockaddr_in remote;
socklen_t addrlen = sizeof(remote);
//int recvfrom(int socket, void *restrict buffer, size_t length, int flags, struct sockaddr *restrict src_addr, socklen_t *restrict *src_len)
int bytes = recvfrom(fd, buffer, BUFSIZE, 0, (sockaddr*) &remote, &addrlen);
if (bytes > 0)
{
printf("Received %d boats.\n", bytes);
int packetlen = DNS::createResponse(*(DNS::header*) buffer,
[&lookup] (const std::string& name) ->
std::vector<net::IP4::addr>*
{
auto it = lookup.find(name);
if (it == lookup.end()) return nullptr;
return &lookup[name];
});
int sent = sendto(fd, buffer, packetlen, 0,
(sockaddr*) &remote, addrlen);
printf("Wrote %d boats.\n", sent);
}
std::cout << "Service out!" << std::endl;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* *
* Copyright 2012 Marco Martin <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#include "bodegastore.h"
#include "kdeclarativeview.h"
#include <QtDeclarative/qdeclarative.h>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QScriptEngine>
#include <QScriptValueIterator>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <kwallet.h>
//Bodega libs
#include <bodega/assetoperations.h>
#include <bodega/bodegamodel.h>
#include <bodega/channelsjob.h>
#include <bodega/historymodel.h>
#include <bodega/networkjob.h>
#include <bodega/participantinfojob.h>
#include <bodega/registerjob.h>
#include <bodega/session.h>
#include <bodega/signonjob.h>
#include <bodega/installjob.h>
#include <bodega/uninstalljob.h>
using namespace Bodega;
QScriptValue qScriptValueFromError(QScriptEngine *engine, const Bodega::Error &error)
{
QScriptValue obj = engine->newObject();
obj.setProperty("type", error.type());
obj.setProperty("errorId", error.errorId());
obj.setProperty("title", error.title());
obj.setProperty("description", error.description());
return obj;
}
void errorFromQScriptValue(const QScriptValue &scriptValue, Bodega::Error &error)
{
Error::Type type = Error::Network;
QString errorId;
QString title;
QString description;
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "type") {
type = (Error::Type)it.value().toInteger();
} else if (it.name() == "errorId") {
errorId = it.value().toString();
} else if (it.name() == "title") {
title = it.value().toString();
} else if (it.name() == "description") {
description = it.value().toString();
}
}
error = Error(type, errorId, title, description);
}
QScriptValue qScriptValueFromChannelInfo(QScriptEngine *engine, const Bodega::ChannelInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("name", info.name);
obj.setProperty("description", info.description);
obj.setProperty("assetCount", info.assetCount);
//obj.setProperty("images", images);
return obj;
}
void channelInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ChannelInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "assetCount") {
info.assetCount = it.value().toInteger();
}
}
}
QScriptValue qScriptValueFromAssetInfo(QScriptEngine *engine, const Bodega::AssetInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("license", info.license);
obj.setProperty("partnerId", info.partnerId);
obj.setProperty("partnerName", info.partnerName);
obj.setProperty("name", info.name);
obj.setProperty("version", info.version);
obj.setProperty("path", info.path.toString());
//obj.setProperty("images", info.images);
obj.setProperty("description", info.description);
obj.setProperty("points", info.points);
QScriptValue imageObj = engine->newObject();
imageObj.setProperty("tiny", info.images[ImageTiny].toString());
imageObj.setProperty("small", info.images[ImageSmall].toString());
imageObj.setProperty("medium", info.images[ImageMedium].toString());
imageObj.setProperty("large", info.images[ImageLarge].toString());
imageObj.setProperty("huge", info.images[ImageHuge].toString());
imageObj.setProperty("previews", info.images[ImagePreviews].toString());
obj.setProperty("images", imageObj);
return obj;
}
void assetInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::AssetInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "license") {
info.license = it.value().toString();
} else if (it.name() == "partnerId") {
info.partnerId = it.value().toString();
} else if (it.name() == "partnerName") {
info.partnerName = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "version") {
info.version = it.value().toString();
} else if (it.name() == "path") {
info.path = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "points") {
info.points = it.value().toInteger();
} else if (it.name() == "images") {
QMap<ImageUrl, QUrl> images;
QScriptValueIterator imageIt(scriptValue);
while (imageIt.hasNext()) {
imageIt.next();
if (imageIt.name() == "tiny") {
images[ImageTiny] = imageIt.value().toString();
} else if (imageIt.name() == "small") {
images[ImageSmall] = imageIt.value().toString();
} else if (imageIt.name() == "medium") {
images[ImageMedium] = imageIt.value().toString();
} else if (imageIt.name() == "large") {
images[ImageLarge] = imageIt.value().toString();
} else if (imageIt.name() == "huge") {
images[ImageHuge] = imageIt.value().toString();
} else if (imageIt.name() == "previews") {
images[ImagePreviews] = imageIt.value().toString();
}
}
info.images = images;
}
}
}
QScriptValue qScriptValueFromTags(QScriptEngine *engine, const Bodega::Tags &tags)
{
QScriptValue obj = engine->newObject();
foreach (const QString &key, tags.keys()) {
QScriptValue list = engine->newArray();
int i = 0;
foreach (const QString &value, tags.values(key)) {
list.setProperty(i, value);
++i;
}
obj.setProperty(key, list);
}
return obj;
}
void tagsFromQScriptValue(const QScriptValue &scriptValue, Bodega::Tags &tags)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
QScriptValueIterator tagIterator(it.value());
while (tagIterator.hasNext()) {
tags.insert(it.name(), tagIterator.value().toString());
}
}
}
QScriptValue qScriptValueFromParticipantInfo(QScriptEngine *engine, const Bodega::ParticipantInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("assetCount", info.assetCount);
obj.setProperty("channelCount", info.channelCount);
obj.setProperty("pointsOwed", info.pointsOwed);
obj.setProperty("organization", info.organization);
obj.setProperty("firstName", info.firstName);
obj.setProperty("lastName", info.lastName);
obj.setProperty("email", info.email);
return obj;
}
void participantInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ParticipantInfo &info)
{
info.assetCount = scriptValue.property("assetCount").toInt32();
info.channelCount = scriptValue.property("channelCount").toInt32();
info.pointsOwed = scriptValue.property("pointsOwed").toInt32();
info.organization = scriptValue.property("organization").toString();
info.firstName = scriptValue.property("firstName").toString();
info.lastName = scriptValue.property("lastName").toString();
info.email = scriptValue.property("email").toString();
}
BodegaStore::BodegaStore()
: KDeclarativeMainWindow(),
m_historyModel(0)
{
declarativeView()->setPackageName("com.coherenttheory.addonsapp");
qmlRegisterType<Bodega::ParticipantInfoJob>();
qmlRegisterType<Bodega::AssetJob>();
qmlRegisterType<Bodega::AssetOperations>();
qmlRegisterType<Bodega::ChannelsJob>();
qmlRegisterType<Bodega::HistoryModel>();
qmlRegisterType<Bodega::Model>();
qmlRegisterType<Bodega::NetworkJob>();
qmlRegisterType<Bodega::RegisterJob>();
qmlRegisterType<Bodega::Session>();
qmlRegisterType<Bodega::SignOnJob>();
qmlRegisterType<Bodega::InstallJob>();
qmlRegisterType<Bodega::UninstallJob>();
qScriptRegisterMetaType<Bodega::Error>(declarativeView()->scriptEngine(), qScriptValueFromError, errorFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ChannelInfo>(declarativeView()->scriptEngine(), qScriptValueFromChannelInfo, channelInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::AssetInfo>(declarativeView()->scriptEngine(), qScriptValueFromAssetInfo, assetInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::Tags>(declarativeView()->scriptEngine(), qScriptValueFromTags, tagsFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ParticipantInfo>(declarativeView()->scriptEngine(), qScriptValueFromParticipantInfo, participantInfoFromQScriptValue, QScriptValue());
m_session = new Session(this);
KConfigGroup config(KGlobal::config(), "AddOns");
m_session->setBaseUrl(config.readEntry("URL", "http://addons.makeplaylive.com:3000"));
m_session->setDeviceId(config.readEntry("Device", "VIVALDI-1"));
m_channelsModel = new Bodega::Model(this);
m_channelsModel->setSession(m_session);
m_searchModel = new Bodega::Model(this);
m_searchModel->setSession(m_session);
declarativeView()->rootContext()->setContextProperty("bodegaClient", this);
}
BodegaStore::~BodegaStore()
{
}
Session* BodegaStore::session() const
{
return m_session;
}
Model* BodegaStore::channelsModel() const
{
return m_channelsModel;
}
Model* BodegaStore::searchModel() const
{
return m_searchModel;
}
HistoryModel *BodegaStore::historyModel()
{
if (!m_historyModel) {
m_historyUsers = 0;
m_historyModel = new HistoryModel(m_session);
m_historyModel->setSession(m_session);
}
return m_historyModel;
}
void BodegaStore::historyInUse(bool used)
{
if (used) {
++m_historyUsers;
} else {
--m_historyUsers;
if (m_historyUsers < 1) {
m_historyUsers = 0;
m_historyModel->deleteLater();
m_historyModel = 0;
}
}
}
void BodegaStore::forgetCredentials() const
{
m_session->setUserName(QString());
m_session->setPassword(QString());
saveCredentials();
}
void BodegaStore::saveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet->isOpen() &&
(wallet->hasFolder("MakePlayLive") ||
wallet->createFolder("MakePlayLive")) &&
wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
map["username"] = m_session->userName();
map["password"] = m_session->password();
if (wallet->writeMap("credentials", map) != 0) {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
}
QVariantHash BodegaStore::retrieveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet->isOpen() && wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
if (wallet->readMap("credentials", map) == 0) {
QVariantHash hash;
hash["username"] = map["username"];
hash["password"] = map["password"];
return hash;
} else {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
return QVariantHash();
}
#include "bodegastore.moc"
<commit_msg>update qml bindings for assetinfo<commit_after>/***************************************************************************
* *
* Copyright 2012 Marco Martin <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#include "bodegastore.h"
#include "kdeclarativeview.h"
#include <QtDeclarative/qdeclarative.h>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QScriptEngine>
#include <QScriptValueIterator>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <kwallet.h>
//Bodega libs
#include <bodega/assetoperations.h>
#include <bodega/bodegamodel.h>
#include <bodega/channelsjob.h>
#include <bodega/historymodel.h>
#include <bodega/networkjob.h>
#include <bodega/participantinfojob.h>
#include <bodega/registerjob.h>
#include <bodega/session.h>
#include <bodega/signonjob.h>
#include <bodega/installjob.h>
#include <bodega/uninstalljob.h>
using namespace Bodega;
QScriptValue qScriptValueFromError(QScriptEngine *engine, const Bodega::Error &error)
{
QScriptValue obj = engine->newObject();
obj.setProperty("type", error.type());
obj.setProperty("errorId", error.errorId());
obj.setProperty("title", error.title());
obj.setProperty("description", error.description());
return obj;
}
void errorFromQScriptValue(const QScriptValue &scriptValue, Bodega::Error &error)
{
Error::Type type = Error::Network;
QString errorId;
QString title;
QString description;
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "type") {
type = (Error::Type)it.value().toInteger();
} else if (it.name() == "errorId") {
errorId = it.value().toString();
} else if (it.name() == "title") {
title = it.value().toString();
} else if (it.name() == "description") {
description = it.value().toString();
}
}
error = Error(type, errorId, title, description);
}
QScriptValue qScriptValueFromChannelInfo(QScriptEngine *engine, const Bodega::ChannelInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("name", info.name);
obj.setProperty("description", info.description);
obj.setProperty("assetCount", info.assetCount);
//obj.setProperty("images", images);
return obj;
}
void channelInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ChannelInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "assetCount") {
info.assetCount = it.value().toInteger();
}
}
}
QScriptValue qScriptValueFromAssetInfo(QScriptEngine *engine, const Bodega::AssetInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("license", info.license);
obj.setProperty("partnerId", info.partnerId);
obj.setProperty("partnerName", info.partnerName);
obj.setProperty("name", info.name);
obj.setProperty("version", info.version);
obj.setProperty("path", info.path.toString());
//obj.setProperty("images", info.images);
obj.setProperty("description", info.description);
obj.setProperty("points", info.points);
obj.setProperty("canDownload", info.canDownload);
QScriptValue imageObj = engine->newObject();
imageObj.setProperty("tiny", info.images[ImageTiny].toString());
imageObj.setProperty("small", info.images[ImageSmall].toString());
imageObj.setProperty("medium", info.images[ImageMedium].toString());
imageObj.setProperty("large", info.images[ImageLarge].toString());
imageObj.setProperty("huge", info.images[ImageHuge].toString());
imageObj.setProperty("previews", info.images[ImagePreviews].toString());
obj.setProperty("images", imageObj);
return obj;
}
void assetInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::AssetInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "license") {
info.license = it.value().toString();
} else if (it.name() == "partnerId") {
info.partnerId = it.value().toString();
} else if (it.name() == "partnerName") {
info.partnerName = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "version") {
info.version = it.value().toString();
} else if (it.name() == "path") {
info.path = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "points") {
info.points = it.value().toInteger();
} else if (it.name() == "canDownload") {
info.canDownload = it.value().toBool();
} else if (it.name() == "images") {
QMap<ImageUrl, QUrl> images;
QScriptValueIterator imageIt(scriptValue);
while (imageIt.hasNext()) {
imageIt.next();
if (imageIt.name() == "tiny") {
images[ImageTiny] = imageIt.value().toString();
} else if (imageIt.name() == "small") {
images[ImageSmall] = imageIt.value().toString();
} else if (imageIt.name() == "medium") {
images[ImageMedium] = imageIt.value().toString();
} else if (imageIt.name() == "large") {
images[ImageLarge] = imageIt.value().toString();
} else if (imageIt.name() == "huge") {
images[ImageHuge] = imageIt.value().toString();
} else if (imageIt.name() == "previews") {
images[ImagePreviews] = imageIt.value().toString();
}
}
info.images = images;
}
}
}
QScriptValue qScriptValueFromTags(QScriptEngine *engine, const Bodega::Tags &tags)
{
QScriptValue obj = engine->newObject();
foreach (const QString &key, tags.keys()) {
QScriptValue list = engine->newArray();
int i = 0;
foreach (const QString &value, tags.values(key)) {
list.setProperty(i, value);
++i;
}
obj.setProperty(key, list);
}
return obj;
}
void tagsFromQScriptValue(const QScriptValue &scriptValue, Bodega::Tags &tags)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
QScriptValueIterator tagIterator(it.value());
while (tagIterator.hasNext()) {
tags.insert(it.name(), tagIterator.value().toString());
}
}
}
QScriptValue qScriptValueFromParticipantInfo(QScriptEngine *engine, const Bodega::ParticipantInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("assetCount", info.assetCount);
obj.setProperty("channelCount", info.channelCount);
obj.setProperty("pointsOwed", info.pointsOwed);
obj.setProperty("organization", info.organization);
obj.setProperty("firstName", info.firstName);
obj.setProperty("lastName", info.lastName);
obj.setProperty("email", info.email);
return obj;
}
void participantInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ParticipantInfo &info)
{
info.assetCount = scriptValue.property("assetCount").toInt32();
info.channelCount = scriptValue.property("channelCount").toInt32();
info.pointsOwed = scriptValue.property("pointsOwed").toInt32();
info.organization = scriptValue.property("organization").toString();
info.firstName = scriptValue.property("firstName").toString();
info.lastName = scriptValue.property("lastName").toString();
info.email = scriptValue.property("email").toString();
}
BodegaStore::BodegaStore()
: KDeclarativeMainWindow(),
m_historyModel(0)
{
declarativeView()->setPackageName("com.coherenttheory.addonsapp");
qmlRegisterType<Bodega::ParticipantInfoJob>();
qmlRegisterType<Bodega::AssetJob>();
qmlRegisterType<Bodega::AssetOperations>();
qmlRegisterType<Bodega::ChannelsJob>();
qmlRegisterType<Bodega::HistoryModel>();
qmlRegisterType<Bodega::Model>();
qmlRegisterType<Bodega::NetworkJob>();
qmlRegisterType<Bodega::RegisterJob>();
qmlRegisterType<Bodega::Session>();
qmlRegisterType<Bodega::SignOnJob>();
qmlRegisterType<Bodega::InstallJob>();
qmlRegisterType<Bodega::UninstallJob>();
qScriptRegisterMetaType<Bodega::Error>(declarativeView()->scriptEngine(), qScriptValueFromError, errorFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ChannelInfo>(declarativeView()->scriptEngine(), qScriptValueFromChannelInfo, channelInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::AssetInfo>(declarativeView()->scriptEngine(), qScriptValueFromAssetInfo, assetInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::Tags>(declarativeView()->scriptEngine(), qScriptValueFromTags, tagsFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ParticipantInfo>(declarativeView()->scriptEngine(), qScriptValueFromParticipantInfo, participantInfoFromQScriptValue, QScriptValue());
m_session = new Session(this);
KConfigGroup config(KGlobal::config(), "AddOns");
m_session->setBaseUrl(config.readEntry("URL", "http://addons.makeplaylive.com:3000"));
m_session->setDeviceId(config.readEntry("Device", "VIVALDI-1"));
m_channelsModel = new Bodega::Model(this);
m_channelsModel->setSession(m_session);
m_searchModel = new Bodega::Model(this);
m_searchModel->setSession(m_session);
declarativeView()->rootContext()->setContextProperty("bodegaClient", this);
}
BodegaStore::~BodegaStore()
{
}
Session* BodegaStore::session() const
{
return m_session;
}
Model* BodegaStore::channelsModel() const
{
return m_channelsModel;
}
Model* BodegaStore::searchModel() const
{
return m_searchModel;
}
HistoryModel *BodegaStore::historyModel()
{
if (!m_historyModel) {
m_historyUsers = 0;
m_historyModel = new HistoryModel(m_session);
m_historyModel->setSession(m_session);
}
return m_historyModel;
}
void BodegaStore::historyInUse(bool used)
{
if (used) {
++m_historyUsers;
} else {
--m_historyUsers;
if (m_historyUsers < 1) {
m_historyUsers = 0;
m_historyModel->deleteLater();
m_historyModel = 0;
}
}
}
void BodegaStore::forgetCredentials() const
{
m_session->setUserName(QString());
m_session->setPassword(QString());
saveCredentials();
}
void BodegaStore::saveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet->isOpen() &&
(wallet->hasFolder("MakePlayLive") ||
wallet->createFolder("MakePlayLive")) &&
wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
map["username"] = m_session->userName();
map["password"] = m_session->password();
if (wallet->writeMap("credentials", map) != 0) {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
}
QVariantHash BodegaStore::retrieveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet->isOpen() && wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
if (wallet->readMap("credentials", map) == 0) {
QVariantHash hash;
hash["username"] = map["username"];
hash["password"] = map["password"];
return hash;
} else {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
return QVariantHash();
}
#include "bodegastore.moc"
<|endoftext|> |
<commit_before>/**
* bucketize_procedure.cc
* Mich, 2015-10-27
* Copyright (c) 2015 Datacratic Inc. All rights reserved.
*
* This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
**/
#include "bucketize_procedure.h"
#include "mldb/server/mldb_server.h"
#include "mldb/sql/sql_expression.h"
#include "mldb/server/dataset_context.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/jml/utils/worker_task.h"
#include "mldb/server/function_contexts.h"
#include "mldb/server/bound_queries.h"
#include "mldb/sql/table_expression_operations.h"
#include "mldb/sql/join_utils.h"
#include "mldb/sql/execution_pipeline.h"
#include "mldb/arch/backtrace.h"
#include "mldb/types/any_impl.h"
#include "mldb/server/per_thread_accumulator.h"
#include "mldb/types/date.h"
#include "mldb/sql/sql_expression.h"
#include <memory>
using namespace std;
namespace Datacratic {
namespace MLDB {
BucketizeProcedureConfig::
BucketizeProcedureConfig()
{
outputDataset.withType("sparse.mutable");
}
DEFINE_STRUCTURE_DESCRIPTION(BucketizeProcedureConfig);
BucketizeProcedureConfigDescription::
BucketizeProcedureConfigDescription()
{
addField("inputData", &BucketizeProcedureConfig::inputData,
"An SQL statement to select the input data. The select expression is required "
"but has no effect. The order by expression is used to rank the rows prior to "
"bucketization.");
addField("outputDataset", &BucketizeProcedureConfig::outputDataset,
"Output dataset configuration. This may refer either to an "
"existing dataset, or a fully specified but non-existing dataset "
"which will be created by the procedure.",
PolyConfigT<Dataset>().withType("sparse.mutable"));
addField("percentileBuckets", &BucketizeProcedureConfig::percentileBuckets,
"Key/ranges of the buckets to create. Buckets ranges can share "
"start and end values but cannot overlap such that a row can "
"belong to multiple buckets. "
"E.g. {\"a\":[0, 50], \"b\": [50, 100]} will give two buckets: "
"\"a\" has rows where 0% < rank/count <= 50% and "
"\"b\" has rows where 50% < rank/count <= 100%, where the 'rank' "
"is based on the orderBy parameter.");
addParent<ProcedureConfig>();
onPostValidate = [&] (BucketizeProcedureConfig * cfg,
JsonParsingContext & context)
{
vector<pair<float, float>> ranges;
for (const auto & range: cfg->percentileBuckets) {
ranges.push_back(range.second);
}
auto sorter = [](pair<float, float> a, pair<float, float> b)
{
return a.first < b.first;
};
sort(ranges.begin(), ranges.end(), sorter);
auto last = make_pair(-1.0, -1.0);
for (const auto & range: ranges) {
if (range.first < 0) {
throw ML::Exception(
"Invalid percentileBucket [%f, %f]: lower bound must be "
"greater or equal to 0", range.first, range.second);
}
if (range.second > 100) {
throw ML::Exception(
"Invalid percentileBucket [%f, %f]: higher bound must be "
"lower or equal to 1", range.first, range.second);
}
if (range.first >= range.second) {
throw ML::Exception(
"Invalid percentileBucket [%f, %f]: higher bound must "
"be greater than lower bound", range.first, range.second);
}
if (range.first < last.second) {
throw ML::Exception(
"Invalid percentileBucket: [%f, %f] is overlapping with "
"[%f, %f]", last.first, last.second, range.first,
range.second);
}
last = range;
}
};
}
BucketizeProcedure::
BucketizeProcedure(MldbServer * owner,
PolyConfig config,
const std::function<bool (const Json::Value &)> & onProgress)
: Procedure(owner)
{
procedureConfig = config.params.convert<BucketizeProcedureConfig>();
}
RunOutput
BucketizeProcedure::
run(const ProcedureRunConfig & run,
const std::function<bool (const Json::Value &)> & onProgress) const
{
SqlExpressionMldbContext context(server);
auto boundDataset = procedureConfig.inputData.stm->from->bind(context);
SelectExpression select(SelectExpression::parse("1"));
vector<shared_ptr<SqlExpression> > calc;
vector<Id> orderedRowNames;
auto getSize = [&] (const MatrixNamedRow & row,
const vector<ExpressionValue> & calc)
{
orderedRowNames.emplace_back(row.rowName);
return true;
};
BoundSelectQuery(select,
*boundDataset.dataset,
boundDataset.asName,
procedureConfig.inputData.stm->when,
procedureConfig.inputData.stm->where,
procedureConfig.inputData.stm->orderBy,
calc)
.execute(getSize,
procedureConfig.inputData.stm->offset,
procedureConfig.inputData.stm->limit,
onProgress);
int64_t rowCount = orderedRowNames.size();
cerr << "Row count: " << rowCount << endl;
std::shared_ptr<Dataset> output;
if (!procedureConfig.outputDataset.type.empty() || !procedureConfig.outputDataset.id.empty()) {
output = createDataset(server, procedureConfig.outputDataset, nullptr, true /*overwrite*/);
}
typedef tuple<ColumnName, CellValue, Date> cell;
PerThreadAccumulator<vector<pair<RowName, vector<cell>>>> accum;
for (const auto & mappedRange: procedureConfig.percentileBuckets) {
string bucketName(mappedRange.first);
auto applyFct = [&] (int64_t index)
{
std::vector<cell> cols;
cols.emplace_back(ColumnName("bucket"),
bucketName,
Date::negativeInfinity());
auto & rows = accum.get();
rows.reserve(1024);
rows.emplace_back(orderedRowNames[index], cols);
if (rows.size() >= 1024) {
output->recordRows(rows);
rows.clear();
}
};
auto range = mappedRange.second;
//Make sure that numerical issues dont let 100 percentile go out of bound
int64_t lowerBound = range.second == 0 ? 0 : int64_t(range.first / 100 * rowCount);
int64_t higherBound = range.second == 100 ? rowCount : int64_t(range.second / 100 * rowCount);
ExcAssert(higherBound <= rowCount);
cerr << "Bucket " << bucketName << " from " << lowerBound
<< " to " << higherBound << endl;
ML::run_in_parallel_blocked(lowerBound, higherBound, applyFct);
}
// record remainder
accum.forEach([&] (vector<pair<RowName, vector<cell>>> * rows)
{
output->recordRows(*rows);
});
output->commit();
return output->getStatus();
}
Any
BucketizeProcedure::
getStatus() const
{
return Any();
}
static RegisterProcedureType<BucketizeProcedure, BucketizeProcedureConfig>
regBucketizeProcedure(
builtinPackage(),
"bucketize",
"Assign buckets based on percentile ranges over a sorted dataset",
"procedures/BucketizeProcedure.md.html");
} // namespace MLDB
} // namespace Datacratic
<commit_msg>Fix no output<commit_after>/**
* bucketize_procedure.cc
* Mich, 2015-10-27
* Copyright (c) 2015 Datacratic Inc. All rights reserved.
*
* This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
**/
#include "bucketize_procedure.h"
#include "mldb/server/mldb_server.h"
#include "mldb/sql/sql_expression.h"
#include "mldb/server/dataset_context.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/jml/utils/worker_task.h"
#include "mldb/server/function_contexts.h"
#include "mldb/server/bound_queries.h"
#include "mldb/sql/table_expression_operations.h"
#include "mldb/sql/join_utils.h"
#include "mldb/sql/execution_pipeline.h"
#include "mldb/arch/backtrace.h"
#include "mldb/types/any_impl.h"
#include "mldb/server/per_thread_accumulator.h"
#include "mldb/types/date.h"
#include "mldb/sql/sql_expression.h"
#include <memory>
using namespace std;
namespace Datacratic {
namespace MLDB {
BucketizeProcedureConfig::
BucketizeProcedureConfig()
{
outputDataset.withType("sparse.mutable");
}
DEFINE_STRUCTURE_DESCRIPTION(BucketizeProcedureConfig);
BucketizeProcedureConfigDescription::
BucketizeProcedureConfigDescription()
{
addField("inputData", &BucketizeProcedureConfig::inputData,
"An SQL statement to select the input data. The select expression is required "
"but has no effect. The order by expression is used to rank the rows prior to "
"bucketization.");
addField("outputDataset", &BucketizeProcedureConfig::outputDataset,
"Output dataset configuration. This may refer either to an "
"existing dataset, or a fully specified but non-existing dataset "
"which will be created by the procedure.",
PolyConfigT<Dataset>().withType("sparse.mutable"));
addField("percentileBuckets", &BucketizeProcedureConfig::percentileBuckets,
"Key/ranges of the buckets to create. Buckets ranges can share "
"start and end values but cannot overlap such that a row can "
"belong to multiple buckets. "
"E.g. {\"a\":[0, 50], \"b\": [50, 100]} will give two buckets: "
"\"a\" has rows where 0% < rank/count <= 50% and "
"\"b\" has rows where 50% < rank/count <= 100%, where the 'rank' "
"is based on the orderBy parameter.");
addParent<ProcedureConfig>();
onPostValidate = [&] (BucketizeProcedureConfig * cfg,
JsonParsingContext & context)
{
vector<pair<float, float>> ranges;
for (const auto & range: cfg->percentileBuckets) {
ranges.push_back(range.second);
}
auto sorter = [](pair<float, float> a, pair<float, float> b)
{
return a.first < b.first;
};
sort(ranges.begin(), ranges.end(), sorter);
auto last = make_pair(-1.0, -1.0);
for (const auto & range: ranges) {
if (range.first < 0) {
throw ML::Exception(
"Invalid percentileBucket [%f, %f]: lower bound must be "
"greater or equal to 0", range.first, range.second);
}
if (range.second > 100) {
throw ML::Exception(
"Invalid percentileBucket [%f, %f]: higher bound must be "
"lower or equal to 1", range.first, range.second);
}
if (range.first >= range.second) {
throw ML::Exception(
"Invalid percentileBucket [%f, %f]: higher bound must "
"be greater than lower bound", range.first, range.second);
}
if (range.first < last.second) {
throw ML::Exception(
"Invalid percentileBucket: [%f, %f] is overlapping with "
"[%f, %f]", last.first, last.second, range.first,
range.second);
}
last = range;
}
};
}
BucketizeProcedure::
BucketizeProcedure(MldbServer * owner,
PolyConfig config,
const std::function<bool (const Json::Value &)> & onProgress)
: Procedure(owner)
{
procedureConfig = config.params.convert<BucketizeProcedureConfig>();
}
RunOutput
BucketizeProcedure::
run(const ProcedureRunConfig & run,
const std::function<bool (const Json::Value &)> & onProgress) const
{
SqlExpressionMldbContext context(server);
auto boundDataset = procedureConfig.inputData.stm->from->bind(context);
SelectExpression select(SelectExpression::parse("1"));
vector<shared_ptr<SqlExpression> > calc;
vector<Id> orderedRowNames;
auto getSize = [&] (const MatrixNamedRow & row,
const vector<ExpressionValue> & calc)
{
orderedRowNames.emplace_back(row.rowName);
return true;
};
BoundSelectQuery(select,
*boundDataset.dataset,
boundDataset.asName,
procedureConfig.inputData.stm->when,
procedureConfig.inputData.stm->where,
procedureConfig.inputData.stm->orderBy,
calc)
.execute(getSize,
procedureConfig.inputData.stm->offset,
procedureConfig.inputData.stm->limit,
onProgress);
int64_t rowCount = orderedRowNames.size();
cerr << "Row count: " << rowCount << endl;
auto output = createDataset(server, procedureConfig.outputDataset,
nullptr, true /*overwrite*/);
typedef tuple<ColumnName, CellValue, Date> cell;
PerThreadAccumulator<vector<pair<RowName, vector<cell>>>> accum;
for (const auto & mappedRange: procedureConfig.percentileBuckets) {
string bucketName(mappedRange.first);
auto applyFct = [&] (int64_t index)
{
std::vector<cell> cols;
cols.emplace_back(ColumnName("bucket"),
bucketName,
Date::negativeInfinity());
auto & rows = accum.get();
rows.reserve(1024);
rows.emplace_back(orderedRowNames[index], cols);
if (rows.size() >= 1024) {
output->recordRows(rows);
rows.clear();
}
};
auto range = mappedRange.second;
//Make sure that numerical issues dont let 100 percentile go out of bound
int64_t lowerBound = range.second == 0 ? 0 : int64_t(range.first / 100 * rowCount);
int64_t higherBound = range.second == 100 ? rowCount : int64_t(range.second / 100 * rowCount);
ExcAssert(higherBound <= rowCount);
cerr << "Bucket " << bucketName << " from " << lowerBound
<< " to " << higherBound << endl;
ML::run_in_parallel_blocked(lowerBound, higherBound, applyFct);
}
// record remainder
accum.forEach([&] (vector<pair<RowName, vector<cell>>> * rows)
{
output->recordRows(*rows);
});
output->commit();
return output->getStatus();
}
Any
BucketizeProcedure::
getStatus() const
{
return Any();
}
static RegisterProcedureType<BucketizeProcedure, BucketizeProcedureConfig>
regBucketizeProcedure(
builtinPackage(),
"bucketize",
"Assign buckets based on percentile ranges over a sorted dataset",
"procedures/BucketizeProcedure.md.html");
} // namespace MLDB
} // namespace Datacratic
<|endoftext|> |
<commit_before>#include <GL/freeglut.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <GL/gl.h>
#include <stdlib.h>
#define PI 3.1415926535898
float w_width=700.0,w_height=700.0;
float x=0.0,y=0.0;
int s;
int r;
float xball=350.0,yball=350.0,a=1.0,b=1.0;
float speed[5]={0.05,0.08,0.1,0.14,0.18};
int level=0;
float xver,yver;
int target[700][700];
int font=0;
int flag=1;
int jz=0;
int score=0;
void init(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(1,700,1,700,-1,1);
}
//::::::::::::::::TEXT FUNCTION:::::::::::::://
void drawBitmapText(const char *string,float x,float y,float z)
{
const char *c;
glRasterPos3f(x,y,z);
for (c=string; *c != '\0'; c++)
{
if(font=0)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
else if(font=1)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
else if(font=2)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
else if(font=3)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
}
}
//::::::::::::::::Display Function::::::::::://
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,1.0);
GLint circle_points=100,i;
GLfloat angle;
glBegin(GL_POLYGON);
for(i=0;i<circle_points;i++) {
angle=2*PI*i/circle_points;
xver=xball+w_width*cos(angle)/35;
yver=yball+w_height*sin(angle)/35;
glVertex2f(xver,yver);
}
glEnd();
//::::::::::::Separator:::::::::::://
glColor3f(0.0,0.0,0.0);
glRectf(50.0,70.0,641.0,73.0);
glRectf(50.0,37.0,641.0,40.0);
//::::::::::External GAME BOUNDARY::::::::::://
glColor3f(0.0,0.0,0.0);
glRectf(10.0,10.0,690.0,12.0);
glRectf(10.0,10.0,12.0,690.0);
glRectf(10.0,690.0,690.0,688.0);
glRectf(690.0,690.0,688.0,10.0);
//:::::::::::INTERNAL GAMING PLATFORM BOUNDARY:::::::::::::::://
glColor3f(0.0,0.0,0.0);
glRectf(50.0,594.0,641.0,591.0);
glRectf(50.0,594.0,47.0,37.0);
glRectf(641.0,594.0,644.0,37.0);
//::::::::::Target Blocks::::::::::://
if(flag==1)
{
for(s=590;s>440;s-=50)
{
for(r=50;r<650;r+=50)
{
target[r][s]=1;
}
}
flag=0;
}
glBegin(GL_QUADS);
{
for(s=590;s>440;s-=50)
{
for(r=50;r<650;r+=50)
{
if(target[r][s]==1)
{
glColor3f(0.0,1.0,0.0);
glVertex3f(r,s,0.0);
glVertex3f(r+40.0,s,0.0);
glVertex3f(r+40.0,s-40.0,0.0);
glVertex3f(r,s-40.0,0.0);
}
}
}
}
glEnd();
//::::::::::::Text:::::::::::://
glColor3f(0.0,0.0,0.0);
font=0;
drawBitmapText("Welcome To Tik-i-noids!!",300,650,0);
glColor3f(1.0,0.0,0.0);
if(jz==1)
{font=1;
drawBitmapText("!!!!GAME OVER!!!!",250,300,0);
}
//:::::::::::::Block:::::::::::::::://
glColor3f(1.0,0.0,1.0);
glBegin(GL_QUADS);
{
glVertex3f(310.0+x,40.0,0.0);
glVertex3f(390.0+x,40.0,0.0);
glVertex3f(390.0+x,70.0,0.0);
glVertex3f(310.0+x,70.0,0.0);
}
glEnd();
glFinish();
glutSwapBuffers();
}
//::::::::::::::Reshape Function:::::::::::::::::://
void reshape(int w, int h)
{
w_height=h;
w_width=w;
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0);
}
void againDisplay()
{
xball=xball+(a*speed[level]);
yball=yball+(b*speed[level]);
for(s=590;s>=490;s-=50)
{
for(r=50;r<650;r+=50)
{
if(target[r][s]==1)
{
if((yball<=s-32)&&(yball>=s-58)&&(xball>=r-2)&&(xball<=r+42)&&(b==1))
{
b=-b;
target[r][s]=0;
score++;
}
}
}
}
if(((xball<=390.0+x)&&(xball>=310.0+x))&&((yball>=75.0)&&(yball<=90.0)))
b=-b ;
if(yball>590.0)
b=-b;
if((xball>=620.0)||(xball<=65.0))
a=-a;
if(yball<=10.0)
jz=1;
if(yball<=-200.0)
glutIdleFunc(NULL);
else
glutPostRedisplay();
}
//::::::::::::::::::::keyboard function:::::::::::::::::://
void keyboard(unsigned char key, int xm, int ym)
{
switch (key)
{
case 'a':x-=10;if(x<-360)x=-360;
break;
case 'd':x+=10; if(x>360)x=360;
break;
case 49:level=0;
break;
case 50:level=1;
break;
case 51:level=2;
break;
case 52:level=3;
break;
case 53:level=4;
break;
case 'p':glutIdleFunc(againDisplay); //Start the game
break;
case 's':glutIdleFunc(NULL); //Pause the game
break;
default:
break;
}
}
int main(int argc,char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(w_width,w_height);
glutInitWindowPosition(270,20);
glutCreateWindow("Tik-i-noids by Jalaz");
init();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
<commit_msg>score calculation<commit_after>#include <GL/freeglut.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <GL/gl.h>
#include <stdlib.h>
#define PI 3.1415926535898
float w_width=700.0,w_height=700.0;
float x=0.0,y=0.0;
int s;
int r;
float xball=350.0,yball=350.0,a=1.0,b=1.0;
float speed[5]={0.1,0.15,0.18,0.22,0.25};
int level=0;
float xver,yver;
int target[700][700];
int font=0;
int flag=1;
int score=0;
int play=1;
char sc[4];
void init(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(1,700,1,700,-1,1);
}
//::::::::::::::::TEXT FUNCTION:::::::::::::://
void drawBitmapText(const char *string,float x,float y,float z)
{
const char *c;
glRasterPos3f(x,y,z);
for (c=string; *c != '\0'; c++)
{
if(font==0)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
else if(font==1)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
else if(font==2)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *c);
else if(font==3)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c);
else if(font==4)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
else if(font==5)
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *c);
else if(font==6)
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, *c);
}
}
//::::::::::::::::Display Function::::::::::://
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
//:::::::::::Ball:::::::::::://
glColor3f(0.0,0.0,1.0);
GLint circle_points=100,i;
GLfloat angle;
glBegin(GL_POLYGON);
for(i=0;i<circle_points;i++)
{
angle=2*PI*i/circle_points;
xver=xball+w_width*cos(angle)/35;
yver=yball+w_height*sin(angle)/35;
glVertex2f(xver,yver);
}
glEnd();
//::::::::::::Separator:::::::::::://
glColor3f(0.0,0.0,0.0);
//glRectf(50.0,70.0,641.0,73.0);
glRectf(50.0,37.0,641.0,40.0);
//::::::::::External Boundary::::::::::://
glColor3f(0.0,0.0,0.0);
glRectf(10.0,10.0,690.0,12.0);
glRectf(10.0,10.0,12.0,690.0);
glRectf(10.0,690.0,690.0,688.0);
glRectf(690.0,690.0,688.0,10.0);
//:::::::::::Internal Gaming Platform Boundary:::::::::::::::://
glColor3f(0.0,0.0,0.0);
glRectf(50.0,594.0,641.0,591.0);
glRectf(50.0,594.0,47.0,37.0);
glRectf(641.0,594.0,644.0,37.0);
//::::::::::Target Blocks::::::::::://
if(flag==1)
{
for(s=590;s>440;s-=50)
{
for(r=50;r<650;r+=50)
{
target[r][s]=1;
}
}
flag=0;
}
glBegin(GL_QUADS);
{
for(s=590;s>440;s-=50)
{
for(r=50;r<650;r+=50)
{
if(target[r][s]==1)
{
glColor3f(0.0,1.0,0.0);
glVertex3f(r,s,0.0);
glVertex3f(r+40.0,s,0.0);
glVertex3f(r+40.0,s-40.0,0.0);
glVertex3f(r,s-40.0,0.0);
}
}
}
}
glEnd();
//::::::::::::Text:::::::::::://
glColor3f(0.0,0.0,0.0);
font=2;
drawBitmapText("Welcome To Tik-i-noids!!",220,650,0);
font=3;
drawBitmapText("Score:",500,650,0);
drawBitmapText(sc,550,650,0);
glColor3f(1.0,0.0,0.0);
if(play==2)
{
font=1;
drawBitmapText("!!!!GAME OVER!!!!",230,350,0);
drawBitmapText("Your Score: ",230,300,0);
drawBitmapText(sc,360,300,0);
font=3;
drawBitmapText("Press R to Restart the game",250,250,0);
}
//:::::::::::::Block:::::::::::::::://
glColor3f(1.0,0.0,1.0);
glBegin(GL_QUADS);
{
glVertex3f(310.0+x,40.0,0.0);
glVertex3f(390.0+x,40.0,0.0);
glVertex3f(390.0+x,70.0,0.0);
glVertex3f(310.0+x,70.0,0.0);
}
glEnd();
glFinish();
glutSwapBuffers();
}
//::::::::::::::Reshape Function:::::::::::::::::://
void reshape(int w, int h)
{
w_height=h;
w_width=w;
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0);
}
void againDisplay()
{
xball=xball+(a*speed[level]);
yball=yball+(b*speed[level]);
for(s=590;s>=490;s-=50)
{
for(r=50;r<650;r+=50)
{
if(target[r][s]==1)
{
if((yball<=s-32)&&(yball>=s-58)&&(xball>=r-2)&&(xball<=r+42)&&(b==1))
{
b=-b;
target[r][s]=0;
score+=10;
}
}
}
}
if(((xball<=400.0+x)&&(xball>=300.0+x))&&((yball>=75.0)&&(yball<=90.0)))
b=-b ;
if(yball>590.0)
b=-b;
if((xball>=620.0)||(xball<=65.0))
a=-a;
int s1,s2,s3,s4;
s1=score/1000;
s2=(score%1000)/100;
s3=(score%100)/10;
s4=score%10;
sc[0]=s1+48;
sc[1]=s2+48;
sc[2]=s3+48;
sc[3]=s4+48;
if(yball<=10.0)
play=2;
if(yball<=-20.0)
glutIdleFunc(NULL);
glutPostRedisplay();
}
//::::::::::::Restart Function::::::::::::::://
void restart(void)
{
play=1;
flag=1;
x=0.0,y=0.0;
xball=350.0,yball=350.0,a=1.0,b=1.0;
score=0;
level=0;
glutPostRedisplay();
}
//::::::::::::::::::::keyboard function:::::::::::::::::://
void keyboard(unsigned char key, int xm, int ym)
{
switch (key)
{
case 'a':x-=15;if(x<-260)x=-260;
break;
case 'd':x+=15; if(x>251)x=251;
break;
case 49:level=0;
break;
case 50:level=1;
break;
case 51:level=2;
break;
case 52:level=3;
break;
case 53:level=4;
break;
case 's':glutIdleFunc(againDisplay); //Start the game
break;
case 'p':glutIdleFunc(NULL); //Pause the game
break;
case 'r':glutIdleFunc(restart);
default:
break;
}
}
int main(int argc,char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(w_width,w_height);
glutInitWindowPosition(270,20);
glutCreateWindow("Tik-i-noids by Jalaz");
init();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2020 Google 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 "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/detection.pb.h"
#include "mediapipe/framework/formats/location_data.pb.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/util/tracking/box_tracker.h"
#include "mediapipe/graphs/instantmotiontracking/calculators/transformations.h"
namespace mediapipe {
constexpr char kSentinelTag[] = "SENTINEL";
constexpr char kAnchorsTag[] = "ANCHORS";
constexpr char kBoxesInputTag[] = "BOXES";
constexpr char kBoxesOutputTag[] = "START_POS";
constexpr char kCancelTag[] = "CANCEL_ID";
// TODO: Find optimal Height/Width (0.1-0.3)
constexpr float kBoxEdgeSize = 0.2f; // Used to establish tracking box dimensions
constexpr float kUsToMs = 1000.0f; // Used to convert from microseconds to millis
// This calculator manages the regions being tracked for each individual sticker
// and adjusts the regions being tracked if a change is detected in a sticker's
// initial anchor placement. Regions being tracked that have no associated sticker
// will be automatically removed upon the next iteration of the graph to optimize
// performance and remove all sticker artifacts
//
// Input:
// SENTINEL - ID of sticker which has an anchor that must be reset (-1 when no
// anchor must be reset) [REQUIRED]
// ANCHORS - Initial anchor data (tracks changes and where to re/position) [REQUIRED]
// BOXES - Used in cycle, boxes being tracked meant to update positions [OPTIONAL
// - provided by subgraph]
// Output:
// START_POS - Positions of boxes being tracked (can be overwritten with ID) [REQUIRED]
// CANCEL_ID - Single integer ID of tracking box to remove from tracker subgraph [OPTIONAL]
// ANCHORS - Updated set of anchors with tracked and normalized X,Y,Z [REQUIRED]
//
// Example config:
// node {
// calculator: "TrackedAnchorManagerCalculator"
// input_stream: "SENTINEL:sticker_sentinel"
// input_stream: "ANCHORS:initial_anchor_data"
// input_stream: "BOXES:boxes"
// input_stream_info: {
// tag_index: 'BOXES'
// back_edge: true
// }
// output_stream: "START_POS:start_pos"
// output_stream: "CANCEL_ID:cancel_object_id"
// output_stream: "ANCHORS:tracked_scaled_anchor_data"
// }
class TrackedAnchorManagerCalculator : public CalculatorBase {
private:
// Previous graph iteration anchor data
std::vector<Anchor> previous_anchor_data;
public:
static ::mediapipe::Status GetContract(CalculatorContract* cc) {
RET_CHECK(cc->Inputs().HasTag(kAnchorsTag)
&& cc->Inputs().HasTag(kSentinelTag));
RET_CHECK(cc->Outputs().HasTag(kAnchorsTag)
&& cc->Outputs().HasTag(kBoxesOutputTag));
cc->Inputs().Tag(kAnchorsTag).Set<std::vector<Anchor>>();
cc->Inputs().Tag(kSentinelTag).Set<int>();
if (cc->Inputs().HasTag(kBoxesInputTag)) {
cc->Inputs().Tag(kBoxesInputTag).Set<TimedBoxProtoList>();
}
cc->Outputs().Tag(kAnchorsTag).Set<std::vector<Anchor>>();
cc->Outputs().Tag(kBoxesOutputTag).Set<TimedBoxProtoList>();
if (cc->Outputs().HasTag(kCancelTag)) {
cc->Outputs().Tag(kCancelTag).Set<int>();
}
return ::mediapipe::OkStatus();
}
::mediapipe::Status Open(CalculatorContext* cc) override {
return ::mediapipe::OkStatus();
}
::mediapipe::Status Process(CalculatorContext* cc) override;
};
REGISTER_CALCULATOR(TrackedAnchorManagerCalculator);
::mediapipe::Status TrackedAnchorManagerCalculator::Process(CalculatorContext* cc) {
mediapipe::Timestamp timestamp = cc->InputTimestamp();
const int sticker_sentinel = cc->Inputs().Tag(kSentinelTag).Get<int>();
std::vector<Anchor> current_anchor_data = cc->Inputs().Tag(kAnchorsTag).Get<std::vector<Anchor>>();
auto pos_boxes = absl::make_unique<TimedBoxProtoList>();
std::vector<Anchor> tracked_scaled_anchor_data;
// Delete any boxes being tracked without an associated anchor
for (const TimedBoxProto& box : cc->Inputs().Tag(kBoxesInputTag)
.Get<TimedBoxProtoList>().box()) {
bool anchor_exists = false;
for (Anchor anchor : current_anchor_data) {
if (box.id() == anchor.sticker_id) {
anchor_exists = true;
break;
}
}
if (!anchor_exists) {
cc->Outputs().Tag(kCancelTag).AddPacket(MakePacket<int>(box.id()).At(timestamp++));
}
}
// Perform tracking or updating for each anchor position
for (Anchor anchor : current_anchor_data) {
// Check if anchor position is being reset by user in this graph iteration
if (sticker_sentinel == anchor.sticker_id) {
// Delete associated tracking box
// TODO: BoxTrackingSubgraph should accept vector to avoid breaking timestamp rules
cc->Outputs().Tag(kCancelTag).AddPacket(MakePacket<int>(anchor.sticker_id).At(timestamp++));
// Add a tracking box
TimedBoxProto* box = pos_boxes->add_box();
box->set_left(anchor.x - kBoxEdgeSize * 0.5f);
box->set_right(anchor.x + kBoxEdgeSize * 0.5f);
box->set_top(anchor.y - kBoxEdgeSize * 0.5f);
box->set_bottom(anchor.y + kBoxEdgeSize * 0.5f);
box->set_id(anchor.sticker_id);
box->set_time_msec((timestamp++).Microseconds() / kUsToMs);
// Default value for normalized z (scale factor)
anchor.z = 1.0;
}
// Anchor position was not reset by user
else {
// Attempt to update anchor position from tracking subgraph (TimedBoxProto)
bool updated_from_tracker = false;
const TimedBoxProtoList box_list = cc->Inputs().Tag(kBoxesInputTag).Get<TimedBoxProtoList>();
for (const auto& box : box_list.box())
{
if (box.id() == anchor.sticker_id) {
// Get center x normalized coordinate [0.0-1.0]
anchor.x = (box.left() + box.right()) * 0.5f;
// Get center y normalized coordinate [0.0-1.0]
anchor.y = (box.top() + box.bottom()) * 0.5f;
// Get center z coordinate [z starts at normalized 1.0 and scales inversely with box-width]
// TODO: Look into issues with uniform scaling on x-axis and y-axis
anchor.z = kBoxEdgeSize / (box.right() - box.left());
updated_from_tracker = true;
break;
}
}
// If anchor position was not updated from tracker, create new tracking box
// at last recorded anchor coordinates. This will allow all current stickers
// to be tracked at approximately last location even if re-acquisitioning
// in the BoxTrackingSubgraph encounters errors
if (!updated_from_tracker) {
for (Anchor prev_anchor : previous_anchor_data) {
if (anchor.sticker_id == prev_anchor.sticker_id) {
anchor = prev_anchor;
TimedBoxProto* box = pos_boxes->add_box();
box->set_left(anchor.x - kBoxEdgeSize * 0.5f);
box->set_right(anchor.x + kBoxEdgeSize * 0.5f);
box->set_top(anchor.y - kBoxEdgeSize * 0.5f);
box->set_bottom(anchor.y + kBoxEdgeSize * 0.5f);
box->set_id(anchor.sticker_id);
box->set_time_msec((timestamp++).Microseconds() / kUsToMs);
// Default value for normalized z (scale factor)
anchor.z = 1.0;
break;
}
}
}
}
tracked_scaled_anchor_data.emplace_back(anchor);
}
// Set anchor data for next iteration
previous_anchor_data = tracked_scaled_anchor_data;
cc->Outputs().Tag(kAnchorsTag).AddPacket(MakePacket<std::vector<Anchor>>(tracked_scaled_anchor_data).At(cc->InputTimestamp()));
cc->Outputs().Tag(kBoxesOutputTag).Add(pos_boxes.release(), cc->InputTimestamp());
return ::mediapipe::OkStatus();
}
}
<commit_msg>Update tracked_anchor_manager_calculator.cc<commit_after>// Copyright 2020 Google 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 "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/detection.pb.h"
#include "mediapipe/framework/formats/location_data.pb.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/util/tracking/box_tracker.h"
#include "mediapipe/graphs/instantmotiontracking/calculators/transformations.h"
namespace mediapipe {
constexpr char kSentinelTag[] = "SENTINEL";
constexpr char kAnchorsTag[] = "ANCHORS";
constexpr char kBoxesInputTag[] = "BOXES";
constexpr char kBoxesOutputTag[] = "START_POS";
constexpr char kCancelTag[] = "CANCEL_ID";
// TODO: Find optimal Height/Width (0.1-0.3)
constexpr float kBoxEdgeSize = 0.2f; // Used to establish tracking box dimensions
constexpr float kUsToMs = 1000.0f; // Used to convert from microseconds to millis
// This calculator manages the regions being tracked for each individual sticker
// and adjusts the regions being tracked if a change is detected in a sticker's
// initial anchor placement. Regions being tracked that have no associated sticker
// will be automatically removed upon the next iteration of the graph to optimize
// performance and remove all sticker artifacts
//
// Input:
// SENTINEL - ID of sticker which has an anchor that must be reset (-1 when no
// anchor must be reset) [REQUIRED]
// ANCHORS - Initial anchor data (tracks changes and where to re/position) [REQUIRED]
// BOXES - Used in cycle, boxes being tracked meant to update positions [OPTIONAL
// - provided by subgraph]
// Output:
// START_POS - Positions of boxes being tracked (can be overwritten with ID) [REQUIRED]
// CANCEL_ID - Single integer ID of tracking box to remove from tracker subgraph [OPTIONAL]
// ANCHORS - Updated set of anchors with tracked and normalized X,Y,Z [REQUIRED]
//
// Example config:
// node {
// calculator: "TrackedAnchorManagerCalculator"
// input_stream: "SENTINEL:sticker_sentinel"
// input_stream: "ANCHORS:initial_anchor_data"
// input_stream: "BOXES:boxes"
// input_stream_info: {
// tag_index: 'BOXES'
// back_edge: true
// }
// output_stream: "START_POS:start_pos"
// output_stream: "CANCEL_ID:cancel_object_id"
// output_stream: "ANCHORS:tracked_scaled_anchor_data"
// }
class TrackedAnchorManagerCalculator : public CalculatorBase {
private:
// Previous graph iteration anchor data
std::vector<Anchor> previous_anchor_data;
public:
static ::mediapipe::Status GetContract(CalculatorContract* cc) {
RET_CHECK(cc->Inputs().HasTag(kAnchorsTag)
&& cc->Inputs().HasTag(kSentinelTag));
RET_CHECK(cc->Outputs().HasTag(kAnchorsTag)
&& cc->Outputs().HasTag(kBoxesOutputTag));
cc->Inputs().Tag(kAnchorsTag).Set<std::vector<Anchor>>();
cc->Inputs().Tag(kSentinelTag).Set<int>();
if (cc->Inputs().HasTag(kBoxesInputTag)) {
cc->Inputs().Tag(kBoxesInputTag).Set<TimedBoxProtoList>();
}
cc->Outputs().Tag(kAnchorsTag).Set<std::vector<Anchor>>();
cc->Outputs().Tag(kBoxesOutputTag).Set<TimedBoxProtoList>();
if (cc->Outputs().HasTag(kCancelTag)) {
cc->Outputs().Tag(kCancelTag).Set<int>();
}
return ::mediapipe::OkStatus();
}
::mediapipe::Status Open(CalculatorContext* cc) override {
return ::mediapipe::OkStatus();
}
::mediapipe::Status Process(CalculatorContext* cc) override;
};
REGISTER_CALCULATOR(TrackedAnchorManagerCalculator);
::mediapipe::Status TrackedAnchorManagerCalculator::Process(CalculatorContext* cc) {
mediapipe::Timestamp timestamp = cc->InputTimestamp();
const int sticker_sentinel = cc->Inputs().Tag(kSentinelTag).Get<int>();
std::vector<Anchor> current_anchor_data = cc->Inputs().Tag(kAnchorsTag).Get<std::vector<Anchor>>();
auto pos_boxes = absl::make_unique<TimedBoxProtoList>();
std::vector<Anchor> tracked_scaled_anchor_data;
// Delete any boxes being tracked without an associated anchor
for (const TimedBoxProto& box : cc->Inputs().Tag(kBoxesInputTag)
.Get<TimedBoxProtoList>().box()) {
bool anchor_exists = false;
for (Anchor anchor : current_anchor_data) {
if (box.id() == anchor.sticker_id) {
anchor_exists = true;
break;
}
}
if (!anchor_exists) {
cc->Outputs().Tag(kCancelTag).AddPacket(MakePacket<int>(box.id()).At(timestamp++));
}
}
// Perform tracking or updating for each anchor position
for (Anchor anchor : current_anchor_data) {
// Check if anchor position is being reset by user in this graph iteration
if (sticker_sentinel == anchor.sticker_id) {
// Delete associated tracking box
// TODO: BoxTrackingSubgraph should accept vector to avoid breaking timestamp rules
cc->Outputs().Tag(kCancelTag).AddPacket(MakePacket<int>(anchor.sticker_id).At(timestamp++));
// Add a tracking box
TimedBoxProto* box = pos_boxes->add_box();
box->set_left(anchor.x - kBoxEdgeSize * 0.5f);
box->set_right(anchor.x + kBoxEdgeSize * 0.5f);
box->set_top(anchor.y - kBoxEdgeSize * 0.5f);
box->set_bottom(anchor.y + kBoxEdgeSize * 0.5f);
box->set_id(anchor.sticker_id);
box->set_time_msec((timestamp++).Microseconds() / kUsToMs);
// Default value for normalized z (scale factor)
anchor.z = 1.0;
}
// Anchor position was not reset by user
else {
// Attempt to update anchor position from tracking subgraph (TimedBoxProto)
bool updated_from_tracker = false;
const TimedBoxProtoList box_list = cc->Inputs().Tag(kBoxesInputTag).Get<TimedBoxProtoList>();
for (const auto& box : box_list.box())
{
if (box.id() == anchor.sticker_id) {
// Get center x normalized coordinate [0.0-1.0]
anchor.x = (box.left() + box.right()) * 0.5f;
// Get center y normalized coordinate [0.0-1.0]
anchor.y = (box.top() + box.bottom()) * 0.5f;
// Get center z coordinate [z starts at normalized 1.0 and scales
// inversely with box-width]
// TODO: Look into issues with uniform scaling on x-axis and y-axis
anchor.z = kBoxEdgeSize / (box.right() - box.left());
updated_from_tracker = true;
break;
}
}
// If anchor position was not updated from tracker, create new tracking box
// at last recorded anchor coordinates. This will allow all current stickers
// to be tracked at approximately last location even if re-acquisitioning
// in the BoxTrackingSubgraph encounters errors
if (!updated_from_tracker) {
for (Anchor prev_anchor : previous_anchor_data) {
if (anchor.sticker_id == prev_anchor.sticker_id) {
anchor = prev_anchor;
TimedBoxProto* box = pos_boxes->add_box();
box->set_left(anchor.x - kBoxEdgeSize * 0.5f);
box->set_right(anchor.x + kBoxEdgeSize * 0.5f);
box->set_top(anchor.y - kBoxEdgeSize * 0.5f);
box->set_bottom(anchor.y + kBoxEdgeSize * 0.5f);
box->set_id(anchor.sticker_id);
box->set_time_msec((timestamp++).Microseconds() / kUsToMs);
// Default value for normalized z (scale factor)
anchor.z = 1.0;
break;
}
}
}
}
tracked_scaled_anchor_data.emplace_back(anchor);
}
// Set anchor data for next iteration
previous_anchor_data = tracked_scaled_anchor_data;
cc->Outputs().Tag(kAnchorsTag).AddPacket(MakePacket<std::vector<Anchor>>(tracked_scaled_anchor_data).At(cc->InputTimestamp()));
cc->Outputs().Tag(kBoxesOutputTag).Add(pos_boxes.release(), cc->InputTimestamp());
return ::mediapipe::OkStatus();
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix adaption to SAL_INFO<commit_after><|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Jin Ma, [email protected]
// Xiaopeng Fu, [email protected]
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders 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 Intel Corporation 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.
//
//M*/
#include "perf_precomp.hpp"
using namespace perf;
using namespace std;
using namespace cv::ocl;
using namespace cv;
using std::tr1::tuple;
using std::tr1::get;
////////////////////////////////// K-NEAREST NEIGHBOR ////////////////////////////////////
static void genData(Mat& trainData, Size size, Mat& trainLabel = Mat().setTo(Scalar::all(0)), int nClasses = 0)
{
trainData.create(size, CV_32FC1);
randu(trainData, 1.0, 100.0);
if(nClasses != 0)
{
trainLabel.create(size.height, 1, CV_8UC1);
randu(trainLabel, 0, nClasses - 1);
trainLabel.convertTo(trainLabel, CV_32FC1);
}
}
typedef tuple<int> KNNParamType;
typedef TestBaseWithParam<KNNParamType> KNNFixture;
PERF_TEST_P(KNNFixture, KNN,
testing::Values(1000, 2000, 4000))
{
KNNParamType params = GetParam();
const int rows = get<0>(params);
int columns = 100;
int k = rows/250;
Mat trainData, trainLabels;
Size size(columns, rows);
genData(trainData, size, trainLabels, 3);
Mat testData;
genData(testData, size);
Mat best_label;
if(RUN_PLAIN_IMPL)
{
TEST_CYCLE()
{
CvKNearest knn_cpu;
knn_cpu.train(trainData, trainLabels);
knn_cpu.find_nearest(testData, k, &best_label);
}
}else if(RUN_OCL_IMPL)
{
cv::ocl::oclMat best_label_ocl;
cv::ocl::oclMat testdata;
testdata.upload(testData);
OCL_TEST_CYCLE()
{
cv::ocl::KNearestNeighbour knn_ocl;
knn_ocl.train(trainData, trainLabels);
knn_ocl.find_nearest(testdata, k, best_label_ocl);
}
best_label_ocl.download(best_label);
}else
OCL_PERF_ELSE
SANITY_CHECK(best_label);
}<commit_msg>ocl: added SVM perf test<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Jin Ma, [email protected]
// Xiaopeng Fu, [email protected]
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders 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 Intel Corporation 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.
//
//M*/
#include "perf_precomp.hpp"
using namespace perf;
using namespace std;
using namespace cv::ocl;
using namespace cv;
using std::tr1::tuple;
using std::tr1::get;
////////////////////////////////// K-NEAREST NEIGHBOR ////////////////////////////////////
static void genData(Mat& trainData, Size size, Mat& trainLabel = Mat().setTo(Scalar::all(0)), int nClasses = 0)
{
trainData.create(size, CV_32FC1);
randu(trainData, 1.0, 100.0);
if(nClasses != 0)
{
trainLabel.create(size.height, 1, CV_8UC1);
randu(trainLabel, 0, nClasses - 1);
trainLabel.convertTo(trainLabel, CV_32FC1);
}
}
typedef tuple<int> KNNParamType;
typedef TestBaseWithParam<KNNParamType> KNNFixture;
PERF_TEST_P(KNNFixture, KNN,
testing::Values(1000, 2000, 4000))
{
KNNParamType params = GetParam();
const int rows = get<0>(params);
int columns = 100;
int k = rows/250;
Mat trainData, trainLabels;
Size size(columns, rows);
genData(trainData, size, trainLabels, 3);
Mat testData;
genData(testData, size);
Mat best_label;
if(RUN_PLAIN_IMPL)
{
TEST_CYCLE()
{
CvKNearest knn_cpu;
knn_cpu.train(trainData, trainLabels);
knn_cpu.find_nearest(testData, k, &best_label);
}
}else if(RUN_OCL_IMPL)
{
cv::ocl::oclMat best_label_ocl;
cv::ocl::oclMat testdata;
testdata.upload(testData);
OCL_TEST_CYCLE()
{
cv::ocl::KNearestNeighbour knn_ocl;
knn_ocl.train(trainData, trainLabels);
knn_ocl.find_nearest(testdata, k, best_label_ocl);
}
best_label_ocl.download(best_label);
}else
OCL_PERF_ELSE
SANITY_CHECK(best_label);
}
typedef TestBaseWithParam<tuple<int> > SVMFixture;
// code is based on: samples\cpp\tutorial_code\ml\non_linear_svms\non_linear_svms.cpp
PERF_TEST_P(SVMFixture, DISABLED_SVM,
testing::Values(50, 100))
{
const int NTRAINING_SAMPLES = get<0>(GetParam()); // Number of training samples per class
#define FRAC_LINEAR_SEP 0.9f // Fraction of samples which compose the linear separable part
const int WIDTH = 512, HEIGHT = 512;
Mat trainData(2*NTRAINING_SAMPLES, 2, CV_32FC1);
Mat labels (2*NTRAINING_SAMPLES, 1, CV_32FC1);
RNG rng(100); // Random value generation class
// Set up the linearly separable part of the training data
int nLinearSamples = (int) (FRAC_LINEAR_SEP * NTRAINING_SAMPLES);
// Generate random points for the class 1
Mat trainClass = trainData.rowRange(0, nLinearSamples);
// The x coordinate of the points is in [0, 0.4)
Mat c = trainClass.colRange(0, 1);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(0.4 * WIDTH));
// The y coordinate of the points is in [0, 1)
c = trainClass.colRange(1,2);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));
// Generate random points for the class 2
trainClass = trainData.rowRange(2*NTRAINING_SAMPLES-nLinearSamples, 2*NTRAINING_SAMPLES);
// The x coordinate of the points is in [0.6, 1]
c = trainClass.colRange(0 , 1);
rng.fill(c, RNG::UNIFORM, Scalar(0.6*WIDTH), Scalar(WIDTH));
// The y coordinate of the points is in [0, 1)
c = trainClass.colRange(1,2);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));
//------------------ Set up the non-linearly separable part of the training data ---------------
// Generate random points for the classes 1 and 2
trainClass = trainData.rowRange( nLinearSamples, 2*NTRAINING_SAMPLES-nLinearSamples);
// The x coordinate of the points is in [0.4, 0.6)
c = trainClass.colRange(0,1);
rng.fill(c, RNG::UNIFORM, Scalar(0.4*WIDTH), Scalar(0.6*WIDTH));
// The y coordinate of the points is in [0, 1)
c = trainClass.colRange(1,2);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));
//------------------------- Set up the labels for the classes ---------------------------------
labels.rowRange( 0, NTRAINING_SAMPLES).setTo(1); // Class 1
labels.rowRange(NTRAINING_SAMPLES, 2*NTRAINING_SAMPLES).setTo(2); // Class 2
//------------------------ Set up the support vector machines parameters --------------------
CvSVMParams params;
params.svm_type = SVM::C_SVC;
params.C = 0.1;
params.kernel_type = SVM::LINEAR;
params.term_crit = TermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6);
Mat dst = Mat::zeros(HEIGHT, WIDTH, CV_8UC1);
Mat samples(WIDTH*HEIGHT, 2, CV_32FC1);
int k = 0;
for (int i = 0; i < HEIGHT; ++i)
{
for (int j = 0; j < WIDTH; ++j)
{
samples.at<float>(k, 0) = (float)i;
samples.at<float>(k, 0) = (float)j;
k++;
}
}
Mat results(WIDTH*HEIGHT, 1, CV_32FC1);
CvMat samples_ = samples;
CvMat results_ = results;
if(RUN_PLAIN_IMPL)
{
CvSVM svm;
svm.train(trainData, labels, Mat(), Mat(), params);
TEST_CYCLE()
{
svm.predict(&samples_, &results_);
}
}
else if(RUN_OCL_IMPL)
{
CvSVM_OCL svm;
svm.train(trainData, labels, Mat(), Mat(), params);
OCL_TEST_CYCLE()
{
svm.predict(&samples_, &results_);
}
}
else
OCL_PERF_ELSE
SANITY_CHECK_NOTHING();
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Jin Ma, [email protected]
// Xiaopeng Fu, [email protected]
// Erping Pang, [email protected]
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#ifdef HAVE_OPENCL
using namespace cv;
using namespace cv::ocl;
using namespace cvtest;
using namespace testing;
///////K-NEAREST NEIGHBOR//////////////////////////
static void genTrainData(cv::RNG& rng, Mat& trainData, int trainDataRow, int trainDataCol,
Mat& trainLabel = Mat().setTo(Scalar::all(0)), int nClasses = 0)
{
cv::Size size(trainDataCol, trainDataRow);
trainData = randomMat(rng, size, CV_32FC1, 1.0, 1000.0, false);
if(nClasses != 0)
{
cv::Size size1(trainDataRow, 1);
trainLabel = randomMat(rng, size1, CV_8UC1, 0, nClasses - 1, false);
trainLabel.convertTo(trainLabel, CV_32FC1);
}
}
PARAM_TEST_CASE(KNN, int, Size, int, bool)
{
int k;
int trainDataCol;
int testDataRow;
int nClass;
bool regression;
virtual void SetUp()
{
k = GET_PARAM(0);
nClass = GET_PARAM(2);
trainDataCol = GET_PARAM(1).width;
testDataRow = GET_PARAM(1).height;
regression = GET_PARAM(3);
}
};
OCL_TEST_P(KNN, Accuracy)
{
Mat trainData, trainLabels;
const int trainDataRow = 500;
genTrainData(rng, trainData, trainDataRow, trainDataCol, trainLabels, nClass);
Mat testData, testLabels;
genTrainData(rng, testData, testDataRow, trainDataCol);
KNearestNeighbour knn_ocl;
CvKNearest knn_cpu;
Mat best_label_cpu;
oclMat best_label_ocl;
/*ocl k-Nearest_Neighbor start*/
oclMat trainData_ocl;
trainData_ocl.upload(trainData);
Mat simpleIdx;
knn_ocl.train(trainData, trainLabels, simpleIdx, regression);
oclMat testdata;
testdata.upload(testData);
knn_ocl.find_nearest(testdata, k, best_label_ocl);
/*ocl k-Nearest_Neighbor end*/
/*cpu k-Nearest_Neighbor start*/
knn_cpu.train(trainData, trainLabels, simpleIdx, regression);
knn_cpu.find_nearest(testData, k, &best_label_cpu);
/*cpu k-Nearest_Neighbor end*/
if(regression)
{
EXPECT_MAT_SIMILAR(Mat(best_label_ocl), best_label_cpu, 1e-5);
}
else
{
EXPECT_MAT_NEAR(Mat(best_label_ocl), best_label_cpu, 0.0);
}
}
INSTANTIATE_TEST_CASE_P(OCL_ML, KNN, Combine(Values(6, 5), Values(Size(200, 400), Size(300, 600)),
Values(4, 3), Values(false, true)));
#ifndef HAVE_CLAMDBLAS // TODO does not work non-blas version of SVM
////////////////////////////////SVM/////////////////////////////////////////////////
PARAM_TEST_CASE(SVM_OCL, int, int, int)
{
cv::Size size;
int kernel_type;
int svm_type;
Mat src, labels, samples, labels_predict;
int K;
virtual void SetUp()
{
kernel_type = GET_PARAM(0);
svm_type = GET_PARAM(1);
K = GET_PARAM(2);
cv::Size size = cv::Size(MWIDTH, MHEIGHT);
src.create(size, CV_32FC1);
labels.create(1, size.height, CV_32SC1);
int row_idx = 0;
const int max_number = size.height / K - 1;
CV_Assert(K <= size.height);
for(int i = 0; i < K; i++ )
{
Mat center_row_header = src.row(row_idx);
center_row_header.setTo(0);
int nchannel = center_row_header.channels();
for(int j = 0; j < nchannel; j++)
{
center_row_header.at<float>(0, i * nchannel + j) = 500.0;
}
labels.at<int>(0, row_idx) = i;
for(int j = 0; (j < max_number) ||
(i == K - 1 && j < max_number + size.height % K); j ++)
{
Mat cur_row_header = src.row(row_idx + 1 + j);
center_row_header.copyTo(cur_row_header);
Mat tmpmat = randomMat(cur_row_header.size(), cur_row_header.type(), 1, 100, false);
cur_row_header += tmpmat;
labels.at<int>(0, row_idx + 1 + j) = i;
}
row_idx += 1 + max_number;
}
labels.convertTo(labels, CV_32FC1);
cv::Size test_size = cv::Size(MWIDTH, 100);
samples.create(test_size, CV_32FC1);
labels_predict.create(1, test_size.height, CV_32SC1);
const int max_number_test = test_size.height / K - 1;
row_idx = 0;
for(int i = 0; i < K; i++ )
{
Mat center_row_header = samples.row(row_idx);
center_row_header.setTo(0);
int nchannel = center_row_header.channels();
for(int j = 0; j < nchannel; j++)
{
center_row_header.at<float>(0, i * nchannel + j) = 500.0;
}
labels_predict.at<int>(0, row_idx) = i;
for(int j = 0; (j < max_number_test) ||
(i == K - 1 && j < max_number_test + test_size.height % K); j ++)
{
Mat cur_row_header = samples.row(row_idx + 1 + j);
center_row_header.copyTo(cur_row_header);
Mat tmpmat = randomMat(cur_row_header.size(), cur_row_header.type(), 1, 100, false);
cur_row_header += tmpmat;
labels_predict.at<int>(0, row_idx + 1 + j) = i;
}
row_idx += 1 + max_number_test;
}
labels_predict.convertTo(labels_predict, CV_32FC1);
}
};
OCL_TEST_P(SVM_OCL, Accuracy)
{
CvSVMParams params;
params.degree = 0.4;
params.gamma = 1;
params.coef0 = 1;
params.C = 1;
params.nu = 0.5;
params.p = 1;
params.svm_type = svm_type;
params.kernel_type = kernel_type;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 1000, 0.001);
CvSVM SVM;
SVM.train(src, labels, Mat(), Mat(), params);
cv::ocl::CvSVM_OCL SVM_OCL;
SVM_OCL.train(src, labels, Mat(), Mat(), params);
int c = SVM.get_support_vector_count();
int c1 = SVM_OCL.get_support_vector_count();
Mat sv(c, MHEIGHT, CV_32FC1);
Mat sv_ocl(c1, MHEIGHT, CV_32FC1);
for(int i = 0; i < c; i++)
{
const float* v = SVM.get_support_vector(i);
for(int j = 0; j < MHEIGHT; j++)
{
sv.at<float>(i, j) = v[j];
}
}
for(int i = 0; i < c1; i++)
{
const float* v_ocl = SVM_OCL.get_support_vector(i);
for(int j = 0; j < MHEIGHT; j++)
{
sv_ocl.at<float>(i, j) = v_ocl[j];
}
}
cv::BFMatcher matcher(cv::NORM_L2);
std::vector<cv::DMatch> matches;
matcher.match(sv, sv_ocl, matches);
int count = 0;
for(std::vector<cv::DMatch>::iterator itr = matches.begin(); itr != matches.end(); itr++)
{
if((*itr).distance < 0.1)
{
count ++;
}
}
if(c != 0)
{
float matchedRatio = (float)count / c;
EXPECT_GT(matchedRatio, 0.95);
}
if(c != 0)
{
CvMat *result = cvCreateMat(1, samples.rows, CV_32FC1);
CvMat test_samples = samples;
CvMat *result_ocl = cvCreateMat(1, samples.rows, CV_32FC1);
SVM.predict(&test_samples, result);
SVM_OCL.predict(&test_samples, result_ocl);
int true_resp = 0, true_resp_ocl = 0;
for (int i = 0; i < samples.rows; i++)
{
if (result->data.fl[i] == labels_predict.at<float>(0, i))
{
true_resp++;
}
}
float matchedRatio = (float)true_resp / samples.rows;
for (int i = 0; i < samples.rows; i++)
{
if (result_ocl->data.fl[i] == labels_predict.at<float>(0, i))
{
true_resp_ocl++;
}
}
float matchedRatio_ocl = (float)true_resp_ocl / samples.rows;
if(matchedRatio != 0 && true_resp_ocl < true_resp)
{
EXPECT_NEAR(matchedRatio_ocl, matchedRatio, 0.03);
}
}
}
// TODO FIXIT: CvSVM::EPS_SVR case is crashed inside CPU implementation
// Anonymous enums are not supported well so cast them to 'int'
INSTANTIATE_TEST_CASE_P(OCL_ML, SVM_OCL, testing::Combine(
Values((int)CvSVM::LINEAR, (int)CvSVM::POLY, (int)CvSVM::RBF, (int)CvSVM::SIGMOID),
Values((int)CvSVM::C_SVC, (int)CvSVM::NU_SVC, (int)CvSVM::ONE_CLASS, (int)CvSVM::NU_SVR),
Values(2, 3, 4)
));
#endif // HAVE_CLAMDBLAS
#endif // HAVE_OPENCL
<commit_msg>misprint in disabling ocl::svm<commit_after>///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Jin Ma, [email protected]
// Xiaopeng Fu, [email protected]
// Erping Pang, [email protected]
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#ifdef HAVE_OPENCL
using namespace cv;
using namespace cv::ocl;
using namespace cvtest;
using namespace testing;
///////K-NEAREST NEIGHBOR//////////////////////////
static void genTrainData(cv::RNG& rng, Mat& trainData, int trainDataRow, int trainDataCol,
Mat& trainLabel = Mat().setTo(Scalar::all(0)), int nClasses = 0)
{
cv::Size size(trainDataCol, trainDataRow);
trainData = randomMat(rng, size, CV_32FC1, 1.0, 1000.0, false);
if(nClasses != 0)
{
cv::Size size1(trainDataRow, 1);
trainLabel = randomMat(rng, size1, CV_8UC1, 0, nClasses - 1, false);
trainLabel.convertTo(trainLabel, CV_32FC1);
}
}
PARAM_TEST_CASE(KNN, int, Size, int, bool)
{
int k;
int trainDataCol;
int testDataRow;
int nClass;
bool regression;
virtual void SetUp()
{
k = GET_PARAM(0);
nClass = GET_PARAM(2);
trainDataCol = GET_PARAM(1).width;
testDataRow = GET_PARAM(1).height;
regression = GET_PARAM(3);
}
};
OCL_TEST_P(KNN, Accuracy)
{
Mat trainData, trainLabels;
const int trainDataRow = 500;
genTrainData(rng, trainData, trainDataRow, trainDataCol, trainLabels, nClass);
Mat testData, testLabels;
genTrainData(rng, testData, testDataRow, trainDataCol);
KNearestNeighbour knn_ocl;
CvKNearest knn_cpu;
Mat best_label_cpu;
oclMat best_label_ocl;
/*ocl k-Nearest_Neighbor start*/
oclMat trainData_ocl;
trainData_ocl.upload(trainData);
Mat simpleIdx;
knn_ocl.train(trainData, trainLabels, simpleIdx, regression);
oclMat testdata;
testdata.upload(testData);
knn_ocl.find_nearest(testdata, k, best_label_ocl);
/*ocl k-Nearest_Neighbor end*/
/*cpu k-Nearest_Neighbor start*/
knn_cpu.train(trainData, trainLabels, simpleIdx, regression);
knn_cpu.find_nearest(testData, k, &best_label_cpu);
/*cpu k-Nearest_Neighbor end*/
if(regression)
{
EXPECT_MAT_SIMILAR(Mat(best_label_ocl), best_label_cpu, 1e-5);
}
else
{
EXPECT_MAT_NEAR(Mat(best_label_ocl), best_label_cpu, 0.0);
}
}
INSTANTIATE_TEST_CASE_P(OCL_ML, KNN, Combine(Values(6, 5), Values(Size(200, 400), Size(300, 600)),
Values(4, 3), Values(false, true)));
#ifdef HAVE_CLAMDBLAS // TODO does not work non-blas version of SVM
////////////////////////////////SVM/////////////////////////////////////////////////
PARAM_TEST_CASE(SVM_OCL, int, int, int)
{
cv::Size size;
int kernel_type;
int svm_type;
Mat src, labels, samples, labels_predict;
int K;
virtual void SetUp()
{
kernel_type = GET_PARAM(0);
svm_type = GET_PARAM(1);
K = GET_PARAM(2);
cv::Size size = cv::Size(MWIDTH, MHEIGHT);
src.create(size, CV_32FC1);
labels.create(1, size.height, CV_32SC1);
int row_idx = 0;
const int max_number = size.height / K - 1;
CV_Assert(K <= size.height);
for(int i = 0; i < K; i++ )
{
Mat center_row_header = src.row(row_idx);
center_row_header.setTo(0);
int nchannel = center_row_header.channels();
for(int j = 0; j < nchannel; j++)
{
center_row_header.at<float>(0, i * nchannel + j) = 500.0;
}
labels.at<int>(0, row_idx) = i;
for(int j = 0; (j < max_number) ||
(i == K - 1 && j < max_number + size.height % K); j ++)
{
Mat cur_row_header = src.row(row_idx + 1 + j);
center_row_header.copyTo(cur_row_header);
Mat tmpmat = randomMat(cur_row_header.size(), cur_row_header.type(), 1, 100, false);
cur_row_header += tmpmat;
labels.at<int>(0, row_idx + 1 + j) = i;
}
row_idx += 1 + max_number;
}
labels.convertTo(labels, CV_32FC1);
cv::Size test_size = cv::Size(MWIDTH, 100);
samples.create(test_size, CV_32FC1);
labels_predict.create(1, test_size.height, CV_32SC1);
const int max_number_test = test_size.height / K - 1;
row_idx = 0;
for(int i = 0; i < K; i++ )
{
Mat center_row_header = samples.row(row_idx);
center_row_header.setTo(0);
int nchannel = center_row_header.channels();
for(int j = 0; j < nchannel; j++)
{
center_row_header.at<float>(0, i * nchannel + j) = 500.0;
}
labels_predict.at<int>(0, row_idx) = i;
for(int j = 0; (j < max_number_test) ||
(i == K - 1 && j < max_number_test + test_size.height % K); j ++)
{
Mat cur_row_header = samples.row(row_idx + 1 + j);
center_row_header.copyTo(cur_row_header);
Mat tmpmat = randomMat(cur_row_header.size(), cur_row_header.type(), 1, 100, false);
cur_row_header += tmpmat;
labels_predict.at<int>(0, row_idx + 1 + j) = i;
}
row_idx += 1 + max_number_test;
}
labels_predict.convertTo(labels_predict, CV_32FC1);
}
};
OCL_TEST_P(SVM_OCL, Accuracy)
{
CvSVMParams params;
params.degree = 0.4;
params.gamma = 1;
params.coef0 = 1;
params.C = 1;
params.nu = 0.5;
params.p = 1;
params.svm_type = svm_type;
params.kernel_type = kernel_type;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 1000, 0.001);
CvSVM SVM;
SVM.train(src, labels, Mat(), Mat(), params);
cv::ocl::CvSVM_OCL SVM_OCL;
SVM_OCL.train(src, labels, Mat(), Mat(), params);
int c = SVM.get_support_vector_count();
int c1 = SVM_OCL.get_support_vector_count();
Mat sv(c, MHEIGHT, CV_32FC1);
Mat sv_ocl(c1, MHEIGHT, CV_32FC1);
for(int i = 0; i < c; i++)
{
const float* v = SVM.get_support_vector(i);
for(int j = 0; j < MHEIGHT; j++)
{
sv.at<float>(i, j) = v[j];
}
}
for(int i = 0; i < c1; i++)
{
const float* v_ocl = SVM_OCL.get_support_vector(i);
for(int j = 0; j < MHEIGHT; j++)
{
sv_ocl.at<float>(i, j) = v_ocl[j];
}
}
cv::BFMatcher matcher(cv::NORM_L2);
std::vector<cv::DMatch> matches;
matcher.match(sv, sv_ocl, matches);
int count = 0;
for(std::vector<cv::DMatch>::iterator itr = matches.begin(); itr != matches.end(); itr++)
{
if((*itr).distance < 0.1)
{
count ++;
}
}
if(c != 0)
{
float matchedRatio = (float)count / c;
EXPECT_GT(matchedRatio, 0.95);
}
if(c != 0)
{
CvMat *result = cvCreateMat(1, samples.rows, CV_32FC1);
CvMat test_samples = samples;
CvMat *result_ocl = cvCreateMat(1, samples.rows, CV_32FC1);
SVM.predict(&test_samples, result);
SVM_OCL.predict(&test_samples, result_ocl);
int true_resp = 0, true_resp_ocl = 0;
for (int i = 0; i < samples.rows; i++)
{
if (result->data.fl[i] == labels_predict.at<float>(0, i))
{
true_resp++;
}
}
float matchedRatio = (float)true_resp / samples.rows;
for (int i = 0; i < samples.rows; i++)
{
if (result_ocl->data.fl[i] == labels_predict.at<float>(0, i))
{
true_resp_ocl++;
}
}
float matchedRatio_ocl = (float)true_resp_ocl / samples.rows;
if(matchedRatio != 0 && true_resp_ocl < true_resp)
{
EXPECT_NEAR(matchedRatio_ocl, matchedRatio, 0.03);
}
}
}
// TODO FIXIT: CvSVM::EPS_SVR case is crashed inside CPU implementation
// Anonymous enums are not supported well so cast them to 'int'
INSTANTIATE_TEST_CASE_P(OCL_ML, SVM_OCL, testing::Combine(
Values((int)CvSVM::LINEAR, (int)CvSVM::POLY, (int)CvSVM::RBF, (int)CvSVM::SIGMOID),
Values((int)CvSVM::C_SVC, (int)CvSVM::NU_SVC, (int)CvSVM::ONE_CLASS, (int)CvSVM::NU_SVR),
Values(2, 3, 4)
));
#endif // HAVE_CLAMDBLAS
#endif // HAVE_OPENCL
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "transport.h"
#include "transport_thread.h"
#include "iocomponent.h"
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/rendezvous.h>
#include <vespa/vespalib/util/backtrace.h>
#include <xxhash.h>
#include <vespa/log/log.h>
LOG_SETUP(".fnet.transport");
namespace {
struct HashState {
using clock = std::chrono::high_resolution_clock;
const void *self;
clock::time_point now;
uint64_t key_hash;
HashState(const void *key, size_t key_len)
: self(this),
now(clock::now()),
key_hash(XXH64(key, key_len, 0)) {}
};
VESPA_THREAD_STACK_TAG(fnet_work_pool);
struct DefaultTimeTools : fnet::TimeTools {
vespalib::duration event_timeout() const override {
return FNET_Scheduler::tick_ms;
}
vespalib::steady_time current_time() const override {
return vespalib::steady_clock::now();
}
};
struct DebugTimeTools : fnet::TimeTools {
vespalib::duration my_event_timeout;
std::function<vespalib::steady_time()> my_current_time;
DebugTimeTools(vespalib::duration d, std::function<vespalib::steady_time()> f) noexcept
: my_event_timeout(d), my_current_time(std::move(f)) {}
vespalib::duration event_timeout() const override {
return my_event_timeout;
}
vespalib::steady_time current_time() const override {
return my_current_time();
}
};
struct CaptureMeet : vespalib::Rendezvous<int,bool> {
using SP = std::shared_ptr<CaptureMeet>;
vespalib::SyncableThreadExecutor &work_pool;
vespalib::AsyncResolver &async_resolver;
std::function<bool()> capture_hook;
CaptureMeet(size_t N,
vespalib::SyncableThreadExecutor &work_pool_in,
vespalib::AsyncResolver &resolver_in,
std::function<bool()> capture_hook_in)
: vespalib::Rendezvous<int,bool>(N),
work_pool(work_pool_in),
async_resolver(resolver_in),
capture_hook(std::move(capture_hook_in)) {}
void mingle() override {
work_pool.sync();
async_resolver.wait_for_pending_resolves();
bool result = capture_hook();
for (size_t i = 0; i < size(); ++i) {
out(i) = result;
}
}
};
struct CaptureTask : FNET_Task {
CaptureMeet::SP meet;
CaptureTask(FNET_Scheduler *scheduler, CaptureMeet::SP meet_in)
: FNET_Task(scheduler), meet(std::move(meet_in)) {}
void PerformTask() override {
int dummy_value = 0; // rendezvous must have input value
if (meet->rendezvous(dummy_value)) {
ScheduleNow();
} else {
delete this;
}
};
};
} // namespace <unnamed>
namespace fnet {
TimeTools::SP
TimeTools::make_debug(vespalib::duration event_timeout,
std::function<vespalib::steady_time()> current_time)
{
return std::make_shared<DebugTimeTools>(event_timeout, std::move(current_time));
}
TransportConfig::TransportConfig(int num_threads)
: _config(),
_resolver(),
_crypto(),
_time_tools(),
_num_threads(num_threads)
{}
TransportConfig::~TransportConfig() = default;
vespalib::AsyncResolver::SP
TransportConfig::resolver() const {
return _resolver ? _resolver : vespalib::AsyncResolver::get_shared();
}
vespalib::CryptoEngine::SP
TransportConfig::crypto() const {
return _crypto ? _crypto : vespalib::CryptoEngine::get_default();
}
fnet::TimeTools::SP
TransportConfig::time_tools() const {
return _time_tools ? _time_tools : std::make_shared<DefaultTimeTools>();
}
} // fnet
void
FNET_Transport::wait_for_pending_resolves() {
_async_resolver->wait_for_pending_resolves();
}
FNET_Transport::FNET_Transport(const fnet::TransportConfig &cfg)
: _async_resolver(cfg.resolver()),
_crypto_engine(cfg.crypto()),
_time_tools(cfg.time_tools()),
_work_pool(std::make_unique<vespalib::ThreadStackExecutor>(1, 128_Ki, fnet_work_pool, 1024)),
_threads(),
_config(cfg.config())
{
// TODO Temporary logging to track down overspend
LOG(debug, "FNET_Transport threads=%d from :%s", cfg.num_threads(), vespalib::getStackTrace(0).c_str());
assert(cfg.num_threads() >= 1);
for (size_t i = 0; i < cfg.num_threads(); ++i) {
_threads.emplace_back(std::make_unique<FNET_TransportThread>(*this));
}
}
FNET_Transport::~FNET_Transport() = default;
void
FNET_Transport::post_or_perform(vespalib::Executor::Task::UP task)
{
if (auto rejected = _work_pool->execute(std::move(task))) {
rejected->run();
}
}
void
FNET_Transport::resolve_async(const vespalib::string &spec,
vespalib::AsyncResolver::ResultHandler::WP result_handler)
{
_async_resolver->resolve_async(spec, std::move(result_handler));
}
vespalib::CryptoSocket::UP
FNET_Transport::create_client_crypto_socket(vespalib::SocketHandle socket, const vespalib::SocketSpec &spec)
{
return _crypto_engine->create_client_crypto_socket(std::move(socket), spec);
}
vespalib::CryptoSocket::UP
FNET_Transport::create_server_crypto_socket(vespalib::SocketHandle socket)
{
return _crypto_engine->create_server_crypto_socket(std::move(socket));
}
FNET_TransportThread *
FNET_Transport::select_thread(const void *key, size_t key_len) const
{
HashState hash_state(key, key_len);
size_t hash_value = XXH64(&hash_state, sizeof(hash_state), 0);
size_t thread_id = (hash_value % _threads.size());
return _threads[thread_id].get();
}
FNET_Connector *
FNET_Transport::Listen(const char *spec, FNET_IPacketStreamer *streamer,
FNET_IServerAdapter *serverAdapter)
{
return select_thread(spec, strlen(spec))->Listen(spec, streamer, serverAdapter);
}
FNET_Connection *
FNET_Transport::Connect(const char *spec, FNET_IPacketStreamer *streamer,
FNET_IServerAdapter *serverAdapter,
FNET_Context connContext)
{
return select_thread(spec, strlen(spec))->Connect(spec, streamer, serverAdapter, connContext);
}
uint32_t
FNET_Transport::GetNumIOComponents()
{
uint32_t result = 0;
for (const auto &thread: _threads) {
result += thread->GetNumIOComponents();
}
return result;
}
void
FNET_Transport::sync()
{
for (const auto &thread: _threads) {
thread->sync();
}
}
void
FNET_Transport::detach(FNET_IServerAdapter *server_adapter)
{
for (const auto &thread: _threads) {
thread->init_detach(server_adapter);
}
wait_for_pending_resolves();
for (const auto &thread: _threads) {
thread->fini_detach(server_adapter);
}
sync();
}
FNET_Scheduler *
FNET_Transport::GetScheduler()
{
return select_thread(nullptr, 0)->GetScheduler();
}
bool
FNET_Transport::execute(FNET_IExecutable *exe)
{
return select_thread(nullptr, 0)->execute(exe);
}
void
FNET_Transport::ShutDown(bool waitFinished)
{
for (const auto &thread: _threads) {
thread->ShutDown(waitFinished);
}
if (waitFinished) {
wait_for_pending_resolves();
_work_pool->shutdown().sync();
}
}
void
FNET_Transport::WaitFinished()
{
for (const auto &thread: _threads) {
thread->WaitFinished();
}
wait_for_pending_resolves();
_work_pool->shutdown().sync();
}
bool
FNET_Transport::Start(FastOS_ThreadPool *pool)
{
bool result = true;
for (const auto &thread: _threads) {
result &= thread->Start(pool);
}
return result;
}
void
FNET_Transport::attach_capture_hook(std::function<bool()> capture_hook)
{
auto meet = std::make_shared<CaptureMeet>(_threads.size(), *_work_pool, *_async_resolver, std::move(capture_hook));
for (auto &thread: _threads) {
// tasks will be deleted when the capture_hook returns false
auto *task = new CaptureTask(thread->GetScheduler(), meet);
task->ScheduleNow();
}
}
void
FNET_Transport::Add(FNET_IOComponent *comp, bool needRef) {
comp->Owner()->Add(comp, needRef);
}
void
FNET_Transport::Close(FNET_IOComponent *comp, bool needRef) {
comp->Owner()->Close(comp, needRef);
}
void
FNET_Transport::Main() {
assert(_threads.size() == 1);
_threads[0]->Main();
}
<commit_msg>extra sync needed<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "transport.h"
#include "transport_thread.h"
#include "iocomponent.h"
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/rendezvous.h>
#include <vespa/vespalib/util/backtrace.h>
#include <xxhash.h>
#include <vespa/log/log.h>
LOG_SETUP(".fnet.transport");
namespace {
struct HashState {
using clock = std::chrono::high_resolution_clock;
const void *self;
clock::time_point now;
uint64_t key_hash;
HashState(const void *key, size_t key_len)
: self(this),
now(clock::now()),
key_hash(XXH64(key, key_len, 0)) {}
};
VESPA_THREAD_STACK_TAG(fnet_work_pool);
struct DefaultTimeTools : fnet::TimeTools {
vespalib::duration event_timeout() const override {
return FNET_Scheduler::tick_ms;
}
vespalib::steady_time current_time() const override {
return vespalib::steady_clock::now();
}
};
struct DebugTimeTools : fnet::TimeTools {
vespalib::duration my_event_timeout;
std::function<vespalib::steady_time()> my_current_time;
DebugTimeTools(vespalib::duration d, std::function<vespalib::steady_time()> f) noexcept
: my_event_timeout(d), my_current_time(std::move(f)) {}
vespalib::duration event_timeout() const override {
return my_event_timeout;
}
vespalib::steady_time current_time() const override {
return my_current_time();
}
};
struct CaptureMeet : vespalib::Rendezvous<int,bool> {
using SP = std::shared_ptr<CaptureMeet>;
vespalib::SyncableThreadExecutor &work_pool;
vespalib::AsyncResolver &async_resolver;
std::function<bool()> capture_hook;
CaptureMeet(size_t N,
vespalib::SyncableThreadExecutor &work_pool_in,
vespalib::AsyncResolver &resolver_in,
std::function<bool()> capture_hook_in)
: vespalib::Rendezvous<int,bool>(N),
work_pool(work_pool_in),
async_resolver(resolver_in),
capture_hook(std::move(capture_hook_in)) {}
void mingle() override {
work_pool.sync();
async_resolver.wait_for_pending_resolves();
bool result = capture_hook();
for (size_t i = 0; i < size(); ++i) {
out(i) = result;
}
}
};
struct CaptureTask : FNET_Task {
CaptureMeet::SP meet;
CaptureTask(FNET_Scheduler *scheduler, CaptureMeet::SP meet_in)
: FNET_Task(scheduler), meet(std::move(meet_in)) {}
void PerformTask() override {
int dummy_value = 0; // rendezvous must have input value
if (meet->rendezvous(dummy_value)) {
ScheduleNow();
} else {
delete this;
}
};
};
} // namespace <unnamed>
namespace fnet {
TimeTools::SP
TimeTools::make_debug(vespalib::duration event_timeout,
std::function<vespalib::steady_time()> current_time)
{
return std::make_shared<DebugTimeTools>(event_timeout, std::move(current_time));
}
TransportConfig::TransportConfig(int num_threads)
: _config(),
_resolver(),
_crypto(),
_time_tools(),
_num_threads(num_threads)
{}
TransportConfig::~TransportConfig() = default;
vespalib::AsyncResolver::SP
TransportConfig::resolver() const {
return _resolver ? _resolver : vespalib::AsyncResolver::get_shared();
}
vespalib::CryptoEngine::SP
TransportConfig::crypto() const {
return _crypto ? _crypto : vespalib::CryptoEngine::get_default();
}
fnet::TimeTools::SP
TransportConfig::time_tools() const {
return _time_tools ? _time_tools : std::make_shared<DefaultTimeTools>();
}
} // fnet
void
FNET_Transport::wait_for_pending_resolves() {
_async_resolver->wait_for_pending_resolves();
}
FNET_Transport::FNET_Transport(const fnet::TransportConfig &cfg)
: _async_resolver(cfg.resolver()),
_crypto_engine(cfg.crypto()),
_time_tools(cfg.time_tools()),
_work_pool(std::make_unique<vespalib::ThreadStackExecutor>(1, 128_Ki, fnet_work_pool, 1024)),
_threads(),
_config(cfg.config())
{
// TODO Temporary logging to track down overspend
LOG(debug, "FNET_Transport threads=%d from :%s", cfg.num_threads(), vespalib::getStackTrace(0).c_str());
assert(cfg.num_threads() >= 1);
for (size_t i = 0; i < cfg.num_threads(); ++i) {
_threads.emplace_back(std::make_unique<FNET_TransportThread>(*this));
}
}
FNET_Transport::~FNET_Transport() = default;
void
FNET_Transport::post_or_perform(vespalib::Executor::Task::UP task)
{
if (auto rejected = _work_pool->execute(std::move(task))) {
rejected->run();
}
}
void
FNET_Transport::resolve_async(const vespalib::string &spec,
vespalib::AsyncResolver::ResultHandler::WP result_handler)
{
_async_resolver->resolve_async(spec, std::move(result_handler));
}
vespalib::CryptoSocket::UP
FNET_Transport::create_client_crypto_socket(vespalib::SocketHandle socket, const vespalib::SocketSpec &spec)
{
return _crypto_engine->create_client_crypto_socket(std::move(socket), spec);
}
vespalib::CryptoSocket::UP
FNET_Transport::create_server_crypto_socket(vespalib::SocketHandle socket)
{
return _crypto_engine->create_server_crypto_socket(std::move(socket));
}
FNET_TransportThread *
FNET_Transport::select_thread(const void *key, size_t key_len) const
{
HashState hash_state(key, key_len);
size_t hash_value = XXH64(&hash_state, sizeof(hash_state), 0);
size_t thread_id = (hash_value % _threads.size());
return _threads[thread_id].get();
}
FNET_Connector *
FNET_Transport::Listen(const char *spec, FNET_IPacketStreamer *streamer,
FNET_IServerAdapter *serverAdapter)
{
return select_thread(spec, strlen(spec))->Listen(spec, streamer, serverAdapter);
}
FNET_Connection *
FNET_Transport::Connect(const char *spec, FNET_IPacketStreamer *streamer,
FNET_IServerAdapter *serverAdapter,
FNET_Context connContext)
{
return select_thread(spec, strlen(spec))->Connect(spec, streamer, serverAdapter, connContext);
}
uint32_t
FNET_Transport::GetNumIOComponents()
{
uint32_t result = 0;
for (const auto &thread: _threads) {
result += thread->GetNumIOComponents();
}
return result;
}
void
FNET_Transport::sync()
{
for (const auto &thread: _threads) {
thread->sync();
}
}
void
FNET_Transport::detach(FNET_IServerAdapter *server_adapter)
{
for (const auto &thread: _threads) {
thread->init_detach(server_adapter);
}
wait_for_pending_resolves();
sync();
for (const auto &thread: _threads) {
thread->fini_detach(server_adapter);
}
sync();
}
FNET_Scheduler *
FNET_Transport::GetScheduler()
{
return select_thread(nullptr, 0)->GetScheduler();
}
bool
FNET_Transport::execute(FNET_IExecutable *exe)
{
return select_thread(nullptr, 0)->execute(exe);
}
void
FNET_Transport::ShutDown(bool waitFinished)
{
for (const auto &thread: _threads) {
thread->ShutDown(waitFinished);
}
if (waitFinished) {
wait_for_pending_resolves();
_work_pool->shutdown().sync();
}
}
void
FNET_Transport::WaitFinished()
{
for (const auto &thread: _threads) {
thread->WaitFinished();
}
wait_for_pending_resolves();
_work_pool->shutdown().sync();
}
bool
FNET_Transport::Start(FastOS_ThreadPool *pool)
{
bool result = true;
for (const auto &thread: _threads) {
result &= thread->Start(pool);
}
return result;
}
void
FNET_Transport::attach_capture_hook(std::function<bool()> capture_hook)
{
auto meet = std::make_shared<CaptureMeet>(_threads.size(), *_work_pool, *_async_resolver, std::move(capture_hook));
for (auto &thread: _threads) {
// tasks will be deleted when the capture_hook returns false
auto *task = new CaptureTask(thread->GetScheduler(), meet);
task->ScheduleNow();
}
}
void
FNET_Transport::Add(FNET_IOComponent *comp, bool needRef) {
comp->Owner()->Add(comp, needRef);
}
void
FNET_Transport::Close(FNET_IOComponent *comp, bool needRef) {
comp->Owner()->Close(comp, needRef);
}
void
FNET_Transport::Main() {
assert(_threads.size() == 1);
_threads[0]->Main();
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_uid.h"
#include "internet.h"
#include "network_adapter.linux.h"
#if HAVE_NET_IF_H
# include <net/if.h>
#endif
#if HAVE_LINUX_SOCKIOS_H
# include <linux/sockios.h>
#endif
#if HAVE_LINUX_TYPES_H
# include <linux/types.h>
#endif
#if HAVE_OS_TYPES_H
# include <os_types.h>
#endif
#if HAVE_LINUX_ETHTOOL_H
# include <linux/ethtool.h>
#endif
// For now, the only wake-on-lan type we use is UDP magic
#if defined(HAVE_LINUX_ETHTOOL_H)
# define WAKE_MASK ( 0 | (WAKE_MAGIC) )
#endif
// Possible values for the above (OR them together) :
// WAKE_PHY
// WAKE_UCAST
// WAKE_MCAST
// WAKE_BCAST
// WAKE_ARP
// WAKE_MAGIC
// WAKE_MAGICSECURE
/***************************************************************
* LinuxNetworkAdapter class
***************************************************************/
/// Constructor
LinuxNetworkAdapter::LinuxNetworkAdapter ( const char */*ip_string*/,
unsigned int ip_addr ) throw ()
: UnixNetworkAdapter( ip_addr )
{
m_wol_support_mask = 0;
m_wol_enable_mask = 0;
}
LinuxNetworkAdapter::LinuxNetworkAdapter ( const char *name ) throw()
: UnixNetworkAdapter( name )
{
m_wol_support_mask = 0;
m_wol_enable_mask = 0;
}
/// Destructor
LinuxNetworkAdapter::~LinuxNetworkAdapter ( void ) throw()
{
}
bool
LinuxNetworkAdapter::findAdapter( unsigned int ip_addr )
{
bool found = false;
# if (HAVE_STRUCT_IFCONF) && (HAVE_STRUCT_IFREQ) && (HAVE_DECL_SIOCGIFCONF)
struct ifconf ifc;
int sock;
int num_req = 3; // Should be enough for a machine
// with lo, eth0, eth1
// Get a 'control socket' for the operations
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
derror( "Cannot get control socket for WOL detection" );
return false;
}
// Loop 'til we've read in all the interfaces, keep increasing
// the number that we try to read each time
struct sockaddr_in in_addr;
ifc.ifc_buf = NULL;
while( !found ) {
int size = num_req * sizeof(struct ifreq);
ifc.ifc_buf = (char *) calloc( num_req, sizeof(struct ifreq) );
ifc.ifc_len = size;
int status = ioctl( sock, SIOCGIFCONF, &ifc );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFCONF)" );
break;
}
// Did we find it in the ifc?
int num = ifc.ifc_len / sizeof(struct ifreq);
struct ifreq *ifr = ifc.ifc_req;
for ( int i = 0; i < num; i++, ifr++ ) {
struct sockaddr_in *in = (struct sockaddr_in*)&(ifr->ifr_addr);
MemCopy( &in_addr, in, sizeof(struct sockaddr_in) );
if ( in->sin_addr.s_addr == ip_addr ) {
setIpAddr( *ifr );
setName( *ifr );
found = true;
break;
}
}
// If the length returned by ioctl() is the same as the size
// we started with, it probably overflowed.... try again
if ( (!found) && (ifc.ifc_len == size) ) {
num_req += 2;
free( ifc.ifc_buf );
ifc.ifc_buf = NULL;
}
else {
break;
}
}
// Make sure we free up the buffer memory
if ( ifc.ifc_buf ) {
free( ifc.ifc_buf );
}
if ( found ) {
dprintf( D_FULLDEBUG,
"Found interface %s that matches %s\n",
interfaceName( ),
sin_to_string( &in_addr )
);
}
else
{
m_if_name = NULL;
dprintf( D_FULLDEBUG,
"No interface for address %s\n",
sin_to_string( &in_addr )
);
}
// Don't forget to close the socket!
close( sock );
#endif
return found;
}
bool
LinuxNetworkAdapter::findAdapter( const char *name )
{
bool found = false;
# if (HAVE_STRUCT_IFCONF) && (HAVE_STRUCT_IFREQ) && (HAVE_DECL_SIOCGIFCONF)
struct ifreq ifr;
int sock;
// Get a 'control socket' for the operations
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
derror( "Cannot get control socket for WOL detection" );
return false;
}
// Loop 'til we've read in all the interfaces, keep increasing
// the number that we try to read each time
getName( ifr, name );
int status = ioctl( sock, SIOCGIFADDR, &ifr );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFADDR)" );
}
else {
found = true;
setIpAddr( ifr );
}
if ( found ) {
dprintf( D_FULLDEBUG,
"Found interface %s with ip %s\n",
name,
inet_ntoa( m_in_addr )
);
}
else
{
m_if_name = NULL;
dprintf( D_FULLDEBUG, "No interface for name %s\n", name );
}
// Don't forget to close the socket!
close( sock );
#endif
return found;
}
bool
LinuxNetworkAdapter::getAdapterInfo( void )
{
bool ok = true;
# if (HAVE_STRUCT_IFCONF) && (HAVE_STRUCT_IFREQ) && (HAVE_DECL_SIOCGIFCONF)
struct ifreq ifr;
int sock;
int status;
// Get a 'control socket' for the operations
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
derror( "Cannot get control socket for WOL detection" );
return false;
}
// Get the hardware address
getName( ifr );
status = ioctl( sock, SIOCGIFHWADDR, &ifr );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFHWADDR)" );
}
else {
setHwAddr( ifr );
}
// Get the net mask
getName( ifr );
ifr.ifr_addr.sa_family = AF_INET;
status = ioctl( sock, SIOCGIFNETMASK, &ifr );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFNETMASK)" );
}
else {
setNetMask( ifr );
}
// And, we're done
# endif
return ok;
}
bool
LinuxNetworkAdapter::detectWOL ( void )
{
bool ok = false;
#if (HAVE_DECL_SIOCETHTOOL) && (HAVE_STRUCT_IFREQ) && (HAVE_LINUX_ETHTOOL_H)
int err;
struct ethtool_wolinfo wolinfo;
struct ifreq ifr;
// Open control socket.
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
dprintf( D_ALWAYS, "Cannot get control socket for WOL detection\n" );
return false;
}
// Fill in the WOL request and the ioctl request
wolinfo.cmd = ETHTOOL_GWOL;
getName( ifr );
ifr.ifr_data = (caddr_t)(& wolinfo);
priv_state saved_priv = set_priv( PRIV_ROOT );
err = ioctl(sock, SIOCETHTOOL, &ifr);
set_priv( saved_priv );
if ( err < 0 ) {
derror( "ioctl(SIOCETHTOOL/GWOL)" );
m_wol_support_mask = 0;
m_wol_enable_mask = 0;
}
else {
m_wol_support_mask = wolinfo.supported;
m_wol_enable_mask = wolinfo.wolopts;
ok = true;
}
// For now, all we support is the "magic" packet
setWolBits( NetworkAdapterBase::WOL_HW_SUPPORT, m_wol_support_mask );
setWolBits( NetworkAdapterBase::WOL_HW_ENABLED, m_wol_enable_mask );
dprintf( D_FULLDEBUG, "%s supports Wake-on: %s (raw: 0x%02x)\n",
m_if_name, isWakeSupported() ? "yes" : "no", m_wol_support_mask );
dprintf( D_FULLDEBUG, "%s enabled Wake-on: %s (raw: 0x%02x)\n",
m_if_name, isWakeEnabled() ? "yes" : "no", m_wol_enable_mask );
close( sock );
# endif
return ok;
}
struct WolTable
{
unsigned bit_mask;
NetworkAdapterBase::WOL_BITS wol_bits;
};
static WolTable wol_table [] =
{
# if (HAVE_LINUX_ETHTOOL_H)
{ WAKE_PHY, NetworkAdapterBase::WOL_PHYSICAL },
{ WAKE_UCAST, NetworkAdapterBase::WOL_UCAST },
{ WAKE_MCAST, NetworkAdapterBase::WOL_MCAST },
{ WAKE_BCAST, NetworkAdapterBase::WOL_BCAST },
{ WAKE_ARP, NetworkAdapterBase::WOL_ARP },
{ WAKE_MAGIC, NetworkAdapterBase::WOL_MAGIC },
{ WAKE_MAGICSECURE, NetworkAdapterBase::WOL_MAGICSECURE },
# endif
{ 0, NetworkAdapterBase::WOL_NONE }
};
void
LinuxNetworkAdapter::setWolBits ( WOL_TYPE type, unsigned bits )
{
if ( type == WOL_HW_SUPPORT ) {
wolResetSupportBits( );
}
else {
wolResetEnableBits( );
}
for( unsigned bit = 0; wol_table[bit].bit_mask; bit++ ) {
if ( wol_table[bit].bit_mask & bits ) {
wolSetBit( type, wol_table[bit].wol_bits );
}
}
}
<commit_msg>Added a simple message along with the error generated when the ioctl for detecting Wake-On-LAN fails -- that the error can be ignored unless you're using hibernation. (#231)<commit_after>/***************************************************************
*
* Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_uid.h"
#include "internet.h"
#include "network_adapter.linux.h"
#if HAVE_NET_IF_H
# include <net/if.h>
#endif
#if HAVE_LINUX_SOCKIOS_H
# include <linux/sockios.h>
#endif
#if HAVE_LINUX_TYPES_H
# include <linux/types.h>
#endif
#if HAVE_OS_TYPES_H
# include <os_types.h>
#endif
#if HAVE_LINUX_ETHTOOL_H
# include <linux/ethtool.h>
#endif
// For now, the only wake-on-lan type we use is UDP magic
#if defined(HAVE_LINUX_ETHTOOL_H)
# define WAKE_MASK ( 0 | (WAKE_MAGIC) )
#endif
// Possible values for the above (OR them together) :
// WAKE_PHY
// WAKE_UCAST
// WAKE_MCAST
// WAKE_BCAST
// WAKE_ARP
// WAKE_MAGIC
// WAKE_MAGICSECURE
/***************************************************************
* LinuxNetworkAdapter class
***************************************************************/
/// Constructor
LinuxNetworkAdapter::LinuxNetworkAdapter ( const char */*ip_string*/,
unsigned int ip_addr ) throw ()
: UnixNetworkAdapter( ip_addr )
{
m_wol_support_mask = 0;
m_wol_enable_mask = 0;
}
LinuxNetworkAdapter::LinuxNetworkAdapter ( const char *name ) throw()
: UnixNetworkAdapter( name )
{
m_wol_support_mask = 0;
m_wol_enable_mask = 0;
}
/// Destructor
LinuxNetworkAdapter::~LinuxNetworkAdapter ( void ) throw()
{
}
bool
LinuxNetworkAdapter::findAdapter( unsigned int ip_addr )
{
bool found = false;
# if (HAVE_STRUCT_IFCONF) && (HAVE_STRUCT_IFREQ) && (HAVE_DECL_SIOCGIFCONF)
struct ifconf ifc;
int sock;
int num_req = 3; // Should be enough for a machine
// with lo, eth0, eth1
// Get a 'control socket' for the operations
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
derror( "Cannot get control socket for WOL detection" );
return false;
}
// Loop 'til we've read in all the interfaces, keep increasing
// the number that we try to read each time
struct sockaddr_in in_addr;
ifc.ifc_buf = NULL;
while( !found ) {
int size = num_req * sizeof(struct ifreq);
ifc.ifc_buf = (char *) calloc( num_req, sizeof(struct ifreq) );
ifc.ifc_len = size;
int status = ioctl( sock, SIOCGIFCONF, &ifc );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFCONF)" );
break;
}
// Did we find it in the ifc?
int num = ifc.ifc_len / sizeof(struct ifreq);
struct ifreq *ifr = ifc.ifc_req;
for ( int i = 0; i < num; i++, ifr++ ) {
struct sockaddr_in *in = (struct sockaddr_in*)&(ifr->ifr_addr);
MemCopy( &in_addr, in, sizeof(struct sockaddr_in) );
if ( in->sin_addr.s_addr == ip_addr ) {
setIpAddr( *ifr );
setName( *ifr );
found = true;
break;
}
}
// If the length returned by ioctl() is the same as the size
// we started with, it probably overflowed.... try again
if ( (!found) && (ifc.ifc_len == size) ) {
num_req += 2;
free( ifc.ifc_buf );
ifc.ifc_buf = NULL;
}
else {
break;
}
}
// Make sure we free up the buffer memory
if ( ifc.ifc_buf ) {
free( ifc.ifc_buf );
}
if ( found ) {
dprintf( D_FULLDEBUG,
"Found interface %s that matches %s\n",
interfaceName( ),
sin_to_string( &in_addr )
);
}
else
{
m_if_name = NULL;
dprintf( D_FULLDEBUG,
"No interface for address %s\n",
sin_to_string( &in_addr )
);
}
// Don't forget to close the socket!
close( sock );
#endif
return found;
}
bool
LinuxNetworkAdapter::findAdapter( const char *name )
{
bool found = false;
# if (HAVE_STRUCT_IFCONF) && (HAVE_STRUCT_IFREQ) && (HAVE_DECL_SIOCGIFCONF)
struct ifreq ifr;
int sock;
// Get a 'control socket' for the operations
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
derror( "Cannot get control socket for WOL detection" );
return false;
}
// Loop 'til we've read in all the interfaces, keep increasing
// the number that we try to read each time
getName( ifr, name );
int status = ioctl( sock, SIOCGIFADDR, &ifr );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFADDR)" );
}
else {
found = true;
setIpAddr( ifr );
}
if ( found ) {
dprintf( D_FULLDEBUG,
"Found interface %s with ip %s\n",
name,
inet_ntoa( m_in_addr )
);
}
else
{
m_if_name = NULL;
dprintf( D_FULLDEBUG, "No interface for name %s\n", name );
}
// Don't forget to close the socket!
close( sock );
#endif
return found;
}
bool
LinuxNetworkAdapter::getAdapterInfo( void )
{
bool ok = true;
# if (HAVE_STRUCT_IFCONF) && (HAVE_STRUCT_IFREQ) && (HAVE_DECL_SIOCGIFCONF)
struct ifreq ifr;
int sock;
int status;
// Get a 'control socket' for the operations
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
derror( "Cannot get control socket for WOL detection" );
return false;
}
// Get the hardware address
getName( ifr );
status = ioctl( sock, SIOCGIFHWADDR, &ifr );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFHWADDR)" );
}
else {
setHwAddr( ifr );
}
// Get the net mask
getName( ifr );
ifr.ifr_addr.sa_family = AF_INET;
status = ioctl( sock, SIOCGIFNETMASK, &ifr );
if ( status < 0 ) {
derror( "ioctl(SIOCGIFNETMASK)" );
}
else {
setNetMask( ifr );
}
// And, we're done
# endif
return ok;
}
bool
LinuxNetworkAdapter::detectWOL ( void )
{
bool ok = false;
#if (HAVE_DECL_SIOCETHTOOL) && (HAVE_STRUCT_IFREQ) && (HAVE_LINUX_ETHTOOL_H)
int err;
struct ethtool_wolinfo wolinfo;
struct ifreq ifr;
// Open control socket.
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
dprintf( D_ALWAYS, "Cannot get control socket for WOL detection\n" );
return false;
}
// Fill in the WOL request and the ioctl request
wolinfo.cmd = ETHTOOL_GWOL;
getName( ifr );
ifr.ifr_data = (caddr_t)(& wolinfo);
priv_state saved_priv = set_priv( PRIV_ROOT );
err = ioctl(sock, SIOCETHTOOL, &ifr);
set_priv( saved_priv );
if ( err < 0 ) {
derror( "ioctl(SIOCETHTOOL/GWOL)" );
dprintf( D_ALWAYS,
"You can safely ignore the above error if you're not"
" using hibernation\n" );
m_wol_support_mask = 0;
m_wol_enable_mask = 0;
}
else {
m_wol_support_mask = wolinfo.supported;
m_wol_enable_mask = wolinfo.wolopts;
ok = true;
}
// For now, all we support is the "magic" packet
setWolBits( NetworkAdapterBase::WOL_HW_SUPPORT, m_wol_support_mask );
setWolBits( NetworkAdapterBase::WOL_HW_ENABLED, m_wol_enable_mask );
dprintf( D_FULLDEBUG, "%s supports Wake-on: %s (raw: 0x%02x)\n",
m_if_name, isWakeSupported() ? "yes" : "no", m_wol_support_mask );
dprintf( D_FULLDEBUG, "%s enabled Wake-on: %s (raw: 0x%02x)\n",
m_if_name, isWakeEnabled() ? "yes" : "no", m_wol_enable_mask );
close( sock );
# endif
return ok;
}
struct WolTable
{
unsigned bit_mask;
NetworkAdapterBase::WOL_BITS wol_bits;
};
static WolTable wol_table [] =
{
# if (HAVE_LINUX_ETHTOOL_H)
{ WAKE_PHY, NetworkAdapterBase::WOL_PHYSICAL },
{ WAKE_UCAST, NetworkAdapterBase::WOL_UCAST },
{ WAKE_MCAST, NetworkAdapterBase::WOL_MCAST },
{ WAKE_BCAST, NetworkAdapterBase::WOL_BCAST },
{ WAKE_ARP, NetworkAdapterBase::WOL_ARP },
{ WAKE_MAGIC, NetworkAdapterBase::WOL_MAGIC },
{ WAKE_MAGICSECURE, NetworkAdapterBase::WOL_MAGICSECURE },
# endif
{ 0, NetworkAdapterBase::WOL_NONE }
};
void
LinuxNetworkAdapter::setWolBits ( WOL_TYPE type, unsigned bits )
{
if ( type == WOL_HW_SUPPORT ) {
wolResetSupportBits( );
}
else {
wolResetEnableBits( );
}
for( unsigned bit = 0; wol_table[bit].bit_mask; bit++ ) {
if ( wol_table[bit].bit_mask & bits ) {
wolSetBit( type, wol_table[bit].wol_bits );
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Muhammad Tayyab Akram
*
* 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.
*/
extern "C" {
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_BITMAP_H
#include FT_IMAGE_H
#include FT_OUTLINE_H
#include FT_SIZES_H
#include FT_STROKER_H
#include FT_TYPES_H
}
#include <jni.h>
#include "FreeType.h"
#include "JavaBridge.h"
#include "Miscellaneous.h"
#include "GlyphRasterizer.h"
using namespace Tehreer;
GlyphRasterizer::GlyphRasterizer(Typeface &typeface, FT_F26Dot6 pixelWidth, FT_F26Dot6 pixelHeight, FT_Matrix transform)
: m_typeface(typeface)
, m_size(nullptr)
, m_transform(transform)
{
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
FT_New_Size(baseFace, &m_size);
FT_Activate_Size(m_size);
FT_Set_Char_Size(baseFace, pixelWidth, pixelHeight, 0, 0);
m_typeface.unlock();
}
GlyphRasterizer::~GlyphRasterizer()
{
if (m_size) {
/*
* NOTE:
* FreeType face must be locked before releasing the size because it changes an
* internal list of the face containing all the sizes.
*/
m_typeface.lock();
FT_Done_Size(m_size);
m_typeface.unlock();
}
}
void GlyphRasterizer::unsafeActivate(FT_Face ftFace)
{
FT_Activate_Size(m_size);
FT_Set_Transform(ftFace, &m_transform, nullptr);
}
jobject GlyphRasterizer::unsafeCreateBitmap(const JavaBridge &bridge, const FT_Bitmap *bitmap)
{
char pixelMode = bitmap->pixel_mode;
jobject glyphBitmap = nullptr;
size_t bitmapLength = 0;
switch (pixelMode) {
case FT_PIXEL_MODE_GRAY:
bitmapLength = bitmap->width * bitmap->rows;
if (bitmapLength > 0) {
glyphBitmap = bridge.Bitmap_create(bitmap->width, bitmap->rows, JavaBridge::BitmapConfig::Alpha8);
bridge.Bitmap_setPixels(glyphBitmap, bitmap->buffer, bitmapLength);
}
break;
default:
LOGW("Unsupported pixel mode of freetype bitmap");
break;
}
return glyphBitmap;
}
void GlyphRasterizer::loadBitmap(const JavaBridge &bridge, jobject glyph)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
jobject glyphBitmap = nullptr;
jint leftSideBearing = 0;
jint topSideBearing = 0;
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
unsafeActivate(baseFace);
FT_Error error = FT_Load_Glyph(baseFace, glyphID, FT_LOAD_RENDER);
if (error == FT_Err_Ok) {
FT_GlyphSlot glyphSlot = baseFace->glyph;
glyphBitmap = unsafeCreateBitmap(bridge, &glyphSlot->bitmap);
if (glyphBitmap) {
leftSideBearing = glyphSlot->bitmap_left;
topSideBearing = glyphSlot->bitmap_top;
}
}
m_typeface.unlock();
bridge.Glyph_ownBitmap(glyph, glyphBitmap, leftSideBearing, topSideBearing);
}
void GlyphRasterizer::loadOutline(const JavaBridge &bridge, jobject glyph)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
unsafeActivate(baseFace);
FT_Glyph outline = nullptr;
FT_Error error = FT_Load_Glyph(baseFace, glyphID, FT_LOAD_NO_BITMAP);
if (error == FT_Err_Ok) {
FT_Get_Glyph(baseFace->glyph, &outline);
}
m_typeface.unlock();
bridge.Glyph_ownOutline(glyph, outline ? reinterpret_cast<jlong>(outline) : 0);
}
void GlyphRasterizer::loadPath(const JavaBridge &bridge, jobject glyph)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
unsafeActivate(baseFace);
jobject glyphPath = m_typeface.getGlyphPathNoLock(bridge, glyphID);
m_typeface.unlock();
bridge.Glyph_ownPath(glyph, glyphPath);
}
jobject GlyphRasterizer::strokeGlyph(const JavaBridge &bridge, jobject glyph, FT_Fixed lineRadius,
FT_Stroker_LineCap lineCap, FT_Stroker_LineJoin lineJoin, FT_Fixed miterLimit)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
FT_Glyph baseGlyph = reinterpret_cast<FT_Glyph>(bridge.Glyph_getNativeOutline(glyph));
if (baseGlyph) {
m_typeface.lock();
FT_Stroker stroker = m_typeface.ftStroker();
FT_Stroker_Set(stroker, lineRadius, lineCap, lineJoin, miterLimit);
FT_Error error = FT_Glyph_Stroke(&baseGlyph, stroker, 0);
m_typeface.unlock();
if (error == FT_Err_Ok) {
FT_Glyph_To_Bitmap(&baseGlyph, FT_RENDER_MODE_NORMAL, nullptr, 1);
FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(baseGlyph);
jobject strokeBitmap = nullptr;
jint leftSideBearing = 0;
jint topSideBearing = 0;
strokeBitmap = unsafeCreateBitmap(bridge, &bitmapGlyph->bitmap);
if (strokeBitmap) {
leftSideBearing = bitmapGlyph->left;
topSideBearing = bitmapGlyph->top;
}
jobject result = bridge.Glyph_construct(glyphID);
bridge.Glyph_ownBitmap(result, strokeBitmap, leftSideBearing, topSideBearing);
/* Dispose the stroked / bitmap glyph. */
FT_Done_Glyph(baseGlyph);
return result;
}
}
return nullptr;
}
static jlong create(JNIEnv *env, jobject obj, jlong typefaceHandle, jint pixelWidth, jint pixelHeight,
jint transformXX, jint transformXY, jint transformYX, jint transformYY)
{
Typeface *typeface = reinterpret_cast<Typeface *>(typefaceHandle);
FT_Matrix transform = {
transformXX, transformXY,
transformYX, transformYY
};
GlyphRasterizer *glyphRasterizer = new GlyphRasterizer(*typeface, pixelWidth, pixelHeight, transform);
return reinterpret_cast<jlong>(glyphRasterizer);
}
static void dispose(JNIEnv *env, jobject obj, jlong rasterizerHandle)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
delete glyphRasterizer;
}
static void loadBitmap(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
glyphRasterizer->loadBitmap(JavaBridge(env), glyph);
}
static void loadOutline(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
glyphRasterizer->loadOutline(JavaBridge(env), glyph);
}
static void loadPath(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
glyphRasterizer->loadPath(JavaBridge(env), glyph);
}
static jobject strokeGlyph(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph,
jint lineRadius, jint lineCap, jint lineJoin, jint miterLimit)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
FT_Fixed strokeRadius = static_cast<FT_Fixed >(lineRadius);
FT_Stroker_LineCap strokeCap = static_cast<FT_Stroker_LineCap>(lineCap);
FT_Stroker_LineJoin strokeJoin = static_cast<FT_Stroker_LineJoin>(lineJoin);
FT_Fixed strokeMiter = static_cast<FT_Fixed>(miterLimit);
return glyphRasterizer->strokeGlyph(JavaBridge(env), glyph, strokeRadius,
strokeCap, strokeJoin, strokeMiter);
}
static JNINativeMethod JNI_METHODS[] = {
{ "nativeCreate", "(JIIIIII)J", (void *)create },
{ "nativeDispose", "(J)V", (void *)dispose },
{ "nativeLoadBitmap", "(JLcom/mta/tehreer/graphics/Glyph;)V", (void *)loadBitmap },
{ "nativeLoadOutline", "(JLcom/mta/tehreer/graphics/Glyph;)V", (void *)loadOutline },
{ "nativeLoadPath", "(JLcom/mta/tehreer/graphics/Glyph;)V", (void *)loadPath },
{ "nativeStrokeGlyph", "(JLcom/mta/tehreer/graphics/Glyph;IIII)Lcom/mta/tehreer/graphics/Glyph;", (void *)strokeGlyph },
};
jint register_com_mta_tehreer_graphics_GlyphRasterizer(JNIEnv *env)
{
return JavaBridge::registerClass(env, "com/mta/tehreer/graphics/GlyphRasterizer", JNI_METHODS, sizeof(JNI_METHODS) / sizeof(JNI_METHODS[0]));
}
<commit_msg>[jni] Matched native method signatures in glyph rasterizer<commit_after>/*
* Copyright (C) 2016-2018 Muhammad Tayyab Akram
*
* 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.
*/
extern "C" {
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_BITMAP_H
#include FT_IMAGE_H
#include FT_OUTLINE_H
#include FT_SIZES_H
#include FT_STROKER_H
#include FT_TYPES_H
}
#include <jni.h>
#include "FreeType.h"
#include "JavaBridge.h"
#include "Miscellaneous.h"
#include "GlyphRasterizer.h"
using namespace Tehreer;
GlyphRasterizer::GlyphRasterizer(Typeface &typeface, FT_F26Dot6 pixelWidth, FT_F26Dot6 pixelHeight, FT_Matrix transform)
: m_typeface(typeface)
, m_size(nullptr)
, m_transform(transform)
{
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
FT_New_Size(baseFace, &m_size);
FT_Activate_Size(m_size);
FT_Set_Char_Size(baseFace, pixelWidth, pixelHeight, 0, 0);
m_typeface.unlock();
}
GlyphRasterizer::~GlyphRasterizer()
{
if (m_size) {
/*
* NOTE:
* FreeType face must be locked before releasing the size because it changes an
* internal list of the face containing all the sizes.
*/
m_typeface.lock();
FT_Done_Size(m_size);
m_typeface.unlock();
}
}
void GlyphRasterizer::unsafeActivate(FT_Face ftFace)
{
FT_Activate_Size(m_size);
FT_Set_Transform(ftFace, &m_transform, nullptr);
}
jobject GlyphRasterizer::unsafeCreateBitmap(const JavaBridge &bridge, const FT_Bitmap *bitmap)
{
char pixelMode = bitmap->pixel_mode;
jobject glyphBitmap = nullptr;
size_t bitmapLength = 0;
switch (pixelMode) {
case FT_PIXEL_MODE_GRAY:
bitmapLength = bitmap->width * bitmap->rows;
if (bitmapLength > 0) {
glyphBitmap = bridge.Bitmap_create(bitmap->width, bitmap->rows, JavaBridge::BitmapConfig::Alpha8);
bridge.Bitmap_setPixels(glyphBitmap, bitmap->buffer, bitmapLength);
}
break;
default:
LOGW("Unsupported pixel mode of freetype bitmap");
break;
}
return glyphBitmap;
}
void GlyphRasterizer::loadBitmap(const JavaBridge &bridge, jobject glyph)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
jobject glyphBitmap = nullptr;
jint leftSideBearing = 0;
jint topSideBearing = 0;
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
unsafeActivate(baseFace);
FT_Error error = FT_Load_Glyph(baseFace, glyphID, FT_LOAD_RENDER);
if (error == FT_Err_Ok) {
FT_GlyphSlot glyphSlot = baseFace->glyph;
glyphBitmap = unsafeCreateBitmap(bridge, &glyphSlot->bitmap);
if (glyphBitmap) {
leftSideBearing = glyphSlot->bitmap_left;
topSideBearing = glyphSlot->bitmap_top;
}
}
m_typeface.unlock();
bridge.Glyph_ownBitmap(glyph, glyphBitmap, leftSideBearing, topSideBearing);
}
void GlyphRasterizer::loadOutline(const JavaBridge &bridge, jobject glyph)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
unsafeActivate(baseFace);
FT_Glyph outline = nullptr;
FT_Error error = FT_Load_Glyph(baseFace, glyphID, FT_LOAD_NO_BITMAP);
if (error == FT_Err_Ok) {
FT_Get_Glyph(baseFace->glyph, &outline);
}
m_typeface.unlock();
bridge.Glyph_ownOutline(glyph, outline ? reinterpret_cast<jlong>(outline) : 0);
}
void GlyphRasterizer::loadPath(const JavaBridge &bridge, jobject glyph)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
m_typeface.lock();
FT_Face baseFace = m_typeface.ftFace();
unsafeActivate(baseFace);
jobject glyphPath = m_typeface.getGlyphPathNoLock(bridge, glyphID);
m_typeface.unlock();
bridge.Glyph_ownPath(glyph, glyphPath);
}
jobject GlyphRasterizer::strokeGlyph(const JavaBridge &bridge, jobject glyph, FT_Fixed lineRadius,
FT_Stroker_LineCap lineCap, FT_Stroker_LineJoin lineJoin, FT_Fixed miterLimit)
{
FT_UInt glyphID = static_cast<FT_UInt>(bridge.Glyph_getGlyphID(glyph));
FT_Glyph baseGlyph = reinterpret_cast<FT_Glyph>(bridge.Glyph_getNativeOutline(glyph));
if (baseGlyph) {
m_typeface.lock();
FT_Stroker stroker = m_typeface.ftStroker();
FT_Stroker_Set(stroker, lineRadius, lineCap, lineJoin, miterLimit);
FT_Error error = FT_Glyph_Stroke(&baseGlyph, stroker, 0);
m_typeface.unlock();
if (error == FT_Err_Ok) {
FT_Glyph_To_Bitmap(&baseGlyph, FT_RENDER_MODE_NORMAL, nullptr, 1);
FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(baseGlyph);
jobject strokeBitmap = nullptr;
jint leftSideBearing = 0;
jint topSideBearing = 0;
strokeBitmap = unsafeCreateBitmap(bridge, &bitmapGlyph->bitmap);
if (strokeBitmap) {
leftSideBearing = bitmapGlyph->left;
topSideBearing = bitmapGlyph->top;
}
jobject result = bridge.Glyph_construct(glyphID);
bridge.Glyph_ownBitmap(result, strokeBitmap, leftSideBearing, topSideBearing);
/* Dispose the stroked / bitmap glyph. */
FT_Done_Glyph(baseGlyph);
return result;
}
}
return nullptr;
}
static jlong create(JNIEnv *env, jobject obj, jlong typefaceHandle, jint pixelWidth, jint pixelHeight,
jint transformXX, jint transformXY, jint transformYX, jint transformYY)
{
Typeface *typeface = reinterpret_cast<Typeface *>(typefaceHandle);
FT_Matrix transform = {
transformXX, transformXY,
transformYX, transformYY
};
GlyphRasterizer *glyphRasterizer = new GlyphRasterizer(*typeface, pixelWidth, pixelHeight, transform);
return reinterpret_cast<jlong>(glyphRasterizer);
}
static void dispose(JNIEnv *env, jobject obj, jlong rasterizerHandle)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
delete glyphRasterizer;
}
static void loadBitmap(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
glyphRasterizer->loadBitmap(JavaBridge(env), glyph);
}
static void loadOutline(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
glyphRasterizer->loadOutline(JavaBridge(env), glyph);
}
static void loadPath(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
glyphRasterizer->loadPath(JavaBridge(env), glyph);
}
static jobject strokeGlyph(JNIEnv *env, jobject obj, jlong rasterizerHandle, jobject glyph,
jint lineRadius, jint lineCap, jint lineJoin, jint miterLimit)
{
GlyphRasterizer *glyphRasterizer = reinterpret_cast<GlyphRasterizer *>(rasterizerHandle);
FT_Fixed strokeRadius = static_cast<FT_Fixed >(lineRadius);
FT_Stroker_LineCap strokeCap = static_cast<FT_Stroker_LineCap>(lineCap);
FT_Stroker_LineJoin strokeJoin = static_cast<FT_Stroker_LineJoin>(lineJoin);
FT_Fixed strokeMiter = static_cast<FT_Fixed>(miterLimit);
return glyphRasterizer->strokeGlyph(JavaBridge(env), glyph, strokeRadius,
strokeCap, strokeJoin, strokeMiter);
}
static JNINativeMethod JNI_METHODS[] = {
{ "nCreate", "(JIIIIII)J", (void *)create },
{ "nDispose", "(J)V", (void *)dispose },
{ "nLoadBitmap", "(JLcom/mta/tehreer/graphics/Glyph;)V", (void *)loadBitmap },
{ "nLoadOutline", "(JLcom/mta/tehreer/graphics/Glyph;)V", (void *)loadOutline },
{ "nLoadPath", "(JLcom/mta/tehreer/graphics/Glyph;)V", (void *)loadPath },
{ "nStrokeGlyph", "(JLcom/mta/tehreer/graphics/Glyph;IIII)Lcom/mta/tehreer/graphics/Glyph;", (void *)strokeGlyph },
};
jint register_com_mta_tehreer_graphics_GlyphRasterizer(JNIEnv *env)
{
return JavaBridge::registerClass(env, "com/mta/tehreer/graphics/GlyphRasterizer", JNI_METHODS, sizeof(JNI_METHODS) / sizeof(JNI_METHODS[0]));
}
<|endoftext|> |
<commit_before>/*
* SessionCodeSearch.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionCodeSearch.hpp"
#include <iostream>
#include <vector>
#include <set>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/SafeConvert.hpp>
#include <core/r_util/RSourceIndex.hpp>
#include <core/system/FileChangeEvent.hpp>
#include <core/system/FileMonitor.hpp>
#include <R_ext/rlocale.h>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
#include "SessionSource.hpp"
// TODO: introduce a boolean to control indexing behavior
// TODO: use updateEntry with insert which recovers from duplicate
// by removing the returned iterator
// TODO: faster search for removed items
using namespace core ;
namespace session {
namespace modules {
namespace code_search {
namespace {
class SourceFileIndex : boost::noncopyable
{
public:
SourceFileIndex()
{
}
virtual ~SourceFileIndex()
{
}
// COPYING: prohibited
template <typename ForwardIterator>
void enqueFiles(ForwardIterator begin, ForwardIterator end)
{
// note whether we had anything in the queue before we start
// (if we don't then we'll schedule indexing after the add)
bool schedule = indexingQueue_.empty();
// enque change events (but don't schedule indexing)
using namespace core::system;
for ( ; begin != end; ++begin)
enqueFileChange(FileChangeEvent(FileChangeEvent::FileAdded, *begin), false);
// schedule indexing if necessary
if (schedule)
scheduleIndexing();
}
void enqueFileChange(const core::system::FileChangeEvent& event, bool schedule)
{
// screen out files which aren't R source files
FilePath filePath(event.fileInfo().absolutePath());
if (filePath.isDirectory() || filePath.extensionLowerCase() != ".r")
return;
// note whether we need to schedule after we are done
schedule = schedule && indexingQueue_.empty();
// add to the queue
indexingQueue_.push(event);
// schedule indexing if necessary
if (schedule)
scheduleIndexing();
}
void searchSource(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
const std::set<std::string>& excludeContexts,
std::vector<r_util::RSourceItem>* pItems)
{
BOOST_FOREACH(const Entry& entry, entries_)
{
// bail if this is an exluded context
if (excludeContexts.find(entry.pIndex->context()) != excludeContexts.end())
continue;
// scan the next index
entry.pIndex->search(term,
prefixOnly,
false,
std::back_inserter(*pItems));
// return if we are past maxResults
if (pItems->size() >= maxResults)
{
pItems->resize(maxResults);
return;
}
}
}
void searchFiles(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
json::Array* pNames,
json::Array* pPaths,
bool* pMoreAvailable)
{
// default to no more available
*pMoreAvailable = false;
// create wildcard pattern if the search has a '*'
bool hasWildcard = term.find('*') != std::string::npos;
boost::regex pattern;
if (hasWildcard)
pattern = regex_utils::wildcardPatternToRegex(term);
// iterate over the files
FilePath projectRoot = projects::projectContext().directory();
BOOST_FOREACH(const Entry& entry, entries_)
{
// get the next file
FilePath filePath(entry.fileInfo.absolutePath());
// get name for comparison
std::string name = filePath.filename();
// compare for match (wildcard or standard)
bool matches = false;
if (hasWildcard)
{
matches = regex_utils::textMatches(name,
pattern,
prefixOnly,
false);
}
else
{
if (prefixOnly)
matches = boost::algorithm::istarts_with(name, term);
else
matches = boost::algorithm::icontains(name, term);
}
// add the file if we found a match
if (matches)
{
// name and project relative directory
pNames->push_back(filePath.filename());
pPaths->push_back(filePath.relativePath(projectRoot));
// return if we are past max results
if (pNames->size() > maxResults)
{
*pMoreAvailable = true;
pNames->resize(maxResults);
pPaths->resize(maxResults);
return;
}
}
}
}
private:
// index entries we are managing
struct Entry
{
Entry(const FileInfo& fileInfo,
boost::shared_ptr<core::r_util::RSourceIndex> pIndex)
: fileInfo(fileInfo), pIndex(pIndex)
{
}
FileInfo fileInfo;
boost::shared_ptr<core::r_util::RSourceIndex> pIndex;
bool operator < (const Entry& other) const
{
return core::fileInfoPathLessThan(fileInfo, other.fileInfo);
}
};
private:
void scheduleIndexing()
{
// schedule indexing -- perform up to 300ms of work immediately and then continue
// in periodic 100ms chunks until we are completed. note also that we accept the
// default behavior of only indexing during idle time so as not to interfere
// with running computations
module_context::scheduleIncrementalWork(
boost::posix_time::milliseconds(300),
boost::posix_time::milliseconds(100),
boost::bind(&SourceFileIndex::dequeAndIndex, this));
}
bool dequeAndIndex()
{
using namespace core::system;
// remove the event from the queue
FileChangeEvent event = indexingQueue_.front();
indexingQueue_.pop();
// process the change
const FileInfo& fileInfo = event.fileInfo();
switch(event.type())
{
case FileChangeEvent::FileAdded:
{
addIndexEntry(fileInfo);
break;
}
case FileChangeEvent::FileModified:
{
removeIndexEntry(fileInfo);
addIndexEntry(fileInfo);
break;
}
case FileChangeEvent::FileRemoved:
{
removeIndexEntry(fileInfo);
break;
}
case FileChangeEvent::None:
break;
}
// return status
return !indexingQueue_.empty();
}
void addIndexEntry(const FileInfo& fileInfo)
{
// read the file
FilePath filePath(fileInfo.absolutePath());
std::string code;
Error error = module_context::readAndDecodeFile(
filePath,
projects::projectContext().defaultEncoding(),
true,
&code);
if (error)
{
error.addProperty("src-file", filePath.absolutePath());
LOG_ERROR(error);
return;
}
// compute project relative directory (used for context)
std::string context = filePath.relativePath(projects::projectContext().directory());
// index the source
boost::shared_ptr<r_util::RSourceIndex> pIndex(
new r_util::RSourceIndex(context, code));
// add the entry
entries_.insert(Entry(fileInfo, pIndex));
}
void removeIndexEntry(const FileInfo& fileInfo)
{
for (std::set<Entry>::iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (core::fileInfoPathCompare(it->fileInfo, fileInfo) == 0)
{
entries_.erase(it);
break;
}
}
}
private:
// index entries
std::set<Entry> entries_;
// indexing queue
std::queue<core::system::FileChangeEvent> indexingQueue_;
};
// global source file index
SourceFileIndex s_projectIndex;
void searchSourceDatabase(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
std::vector<r_util::RSourceItem>* pItems,
std::set<std::string>* pContextsSearched)
{
// get all of the source indexes
std::vector<boost::shared_ptr<r_util::RSourceIndex> > rIndexes =
modules::source::rIndexes();
BOOST_FOREACH(boost::shared_ptr<r_util::RSourceIndex>& pIndex, rIndexes)
{
// get file path
FilePath docPath = module_context::resolveAliasedPath(pIndex->context());
// bail if the file isn't in the project
std::string projRelativePath =
docPath.relativePath(projects::projectContext().directory());
if (projRelativePath.empty())
continue;
// record that we searched this path
pContextsSearched->insert(projRelativePath);
// scan the source index
pIndex->search(term,
projRelativePath,
prefixOnly,
false,
std::back_inserter(*pItems));
// return if we are past maxResults
if (pItems->size() >= maxResults)
{
pItems->resize(maxResults);
return;
}
}
}
void searchSource(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
std::vector<r_util::RSourceItem>* pItems,
bool* pMoreAvailable)
{
// default to no more available
*pMoreAvailable = false;
// first search the source database
std::set<std::string> srcDBContexts;
searchSourceDatabase(term, maxResults, prefixOnly, pItems, &srcDBContexts);
// we are done if we had >= maxResults
if (pItems->size() > maxResults)
{
*pMoreAvailable = true;
pItems->resize(maxResults);
return;
}
// compute project max results based on existing results
std::size_t maxProjResults = maxResults - pItems->size();
// now search the project (excluding contexts already searched in the source db)
std::vector<r_util::RSourceItem> projItems;
s_projectIndex.searchSource(term,
maxProjResults,
prefixOnly,
srcDBContexts,
&projItems);
// add project items to the list
BOOST_FOREACH(const r_util::RSourceItem& sourceItem, projItems)
{
// add the item
pItems->push_back(sourceItem);
// bail if we've hit the max
if (pItems->size() > maxResults)
{
*pMoreAvailable = true;
pItems->resize(maxResults);
break;
}
}
}
template <typename TValue, typename TFunc>
json::Array toJsonArray(
const std::vector<r_util::RSourceItem> &items,
TFunc memberFunc)
{
json::Array col;
std::transform(items.begin(),
items.end(),
std::back_inserter(col),
boost::bind(json::toJsonValue<TValue>,
boost::bind(memberFunc, _1)));
return col;
}
bool compareItems(const r_util::RSourceItem& i1, const r_util::RSourceItem& i2)
{
return i1.name() < i2.name();
}
Error searchCode(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get params
std::string term;
int maxResultsInt;
Error error = json::readParams(request.params, &term, &maxResultsInt);
if (error)
return error;
std::size_t maxResults = safe_convert::numberTo<std::size_t>(maxResultsInt,
20);
// object to return
json::Object result;
// search files
json::Array names;
json::Array paths;
bool moreFilesAvailable = false;
s_projectIndex.searchFiles(term,
maxResults,
true,
&names,
&paths,
&moreFilesAvailable);
json::Object files;
files["filename"] = names;
files["path"] = paths;
result["file_items"] = files;
// search source (sort results by name)
std::vector<r_util::RSourceItem> items;
bool moreSourceItemsAvailable = false;
searchSource(term, maxResults, true, &items, &moreSourceItemsAvailable);
std::sort(items.begin(), items.end(), compareItems);
// see if we need to do src truncation
bool truncated = false;
if ( (names.size() + items.size()) > maxResults )
{
// truncate source items
std::size_t srcItems = maxResults - names.size();
items.resize(srcItems);
truncated = true;
}
// return rpc array list (wire efficiency)
json::Object src;
src["type"] = toJsonArray<int>(items, &r_util::RSourceItem::type);
src["name"] = toJsonArray<std::string>(items, &r_util::RSourceItem::name);
src["context"] = toJsonArray<std::string>(items, &r_util::RSourceItem::context);
src["line"] = toJsonArray<int>(items, &r_util::RSourceItem::line);
src["column"] = toJsonArray<int>(items, &r_util::RSourceItem::column);
result["source_items"] = src;
// set more available bit
result["more_available"] =
moreFilesAvailable || moreSourceItemsAvailable || truncated;
pResponse->setResult(result);
return Success();
}
void onFileMonitorRegistered(const tree<core::FileInfo>& files)
{
s_projectIndex.enqueFiles(files.begin_leaf(), files.end_leaf());
}
void onFileMonitorRegistrationError(const core::Error& error)
{
// TODO: disable code searching
}
void onFileMonitorUnregistered()
{
// TODO: disable code searching
}
void onFilesChanged(const std::vector<core::system::FileChangeEvent>& events)
{
// index all of the changes
std::for_each(
events.begin(),
events.end(),
boost::bind(&SourceFileIndex::enqueFileChange, &s_projectIndex, _1, true));
}
} // anonymous namespace
bool enabled()
{
return projects::projectContext().hasProject();
}
Error initialize()
{
// subscribe to project context file monitoring state changes
core::system::file_monitor::Callbacks cb;
cb.onRegistered = boost::bind(onFileMonitorRegistered, _2);
cb.onRegistrationError = onFileMonitorRegistrationError;
cb.onUnregistered = boost::bind(onFileMonitorUnregistered);
cb.onFilesChanged = onFilesChanged;
projects::projectContext().registerFileMonitorCallbacks(cb);
using boost::bind;
using namespace module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "search_code", searchCode));
;
return initBlock.execute();
}
} // namespace agreement
} // namespace modules
} // namespace session
<commit_msg>more code search todos<commit_after>/*
* SessionCodeSearch.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionCodeSearch.hpp"
#include <iostream>
#include <vector>
#include <set>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/SafeConvert.hpp>
#include <core/r_util/RSourceIndex.hpp>
#include <core/system/FileChangeEvent.hpp>
#include <core/system/FileMonitor.hpp>
#include <R_ext/rlocale.h>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
#include "SessionSource.hpp"
// TODO: introduce a boolean to control indexing behavior
// TODO: use updateEntry with insert which recovers from duplicate
// by removing the returned iterator
// TODO: faster search for removed items
// TODO: some kind of scanning progress ui
// TODO: enable/disable of code searching / file-mon in project prefs
// TODO: some type of integration with editor (detect change, etc.)
using namespace core ;
namespace session {
namespace modules {
namespace code_search {
namespace {
class SourceFileIndex : boost::noncopyable
{
public:
SourceFileIndex()
{
}
virtual ~SourceFileIndex()
{
}
// COPYING: prohibited
template <typename ForwardIterator>
void enqueFiles(ForwardIterator begin, ForwardIterator end)
{
// note whether we had anything in the queue before we start
// (if we don't then we'll schedule indexing after the add)
bool schedule = indexingQueue_.empty();
// enque change events (but don't schedule indexing)
using namespace core::system;
for ( ; begin != end; ++begin)
enqueFileChange(FileChangeEvent(FileChangeEvent::FileAdded, *begin), false);
// schedule indexing if necessary
if (schedule)
scheduleIndexing();
}
void enqueFileChange(const core::system::FileChangeEvent& event, bool schedule)
{
// screen out files which aren't R source files
FilePath filePath(event.fileInfo().absolutePath());
if (filePath.isDirectory() || filePath.extensionLowerCase() != ".r")
return;
// note whether we need to schedule after we are done
schedule = schedule && indexingQueue_.empty();
// add to the queue
indexingQueue_.push(event);
// schedule indexing if necessary
if (schedule)
scheduleIndexing();
}
void searchSource(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
const std::set<std::string>& excludeContexts,
std::vector<r_util::RSourceItem>* pItems)
{
BOOST_FOREACH(const Entry& entry, entries_)
{
// bail if this is an exluded context
if (excludeContexts.find(entry.pIndex->context()) != excludeContexts.end())
continue;
// scan the next index
entry.pIndex->search(term,
prefixOnly,
false,
std::back_inserter(*pItems));
// return if we are past maxResults
if (pItems->size() >= maxResults)
{
pItems->resize(maxResults);
return;
}
}
}
void searchFiles(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
json::Array* pNames,
json::Array* pPaths,
bool* pMoreAvailable)
{
// default to no more available
*pMoreAvailable = false;
// create wildcard pattern if the search has a '*'
bool hasWildcard = term.find('*') != std::string::npos;
boost::regex pattern;
if (hasWildcard)
pattern = regex_utils::wildcardPatternToRegex(term);
// iterate over the files
FilePath projectRoot = projects::projectContext().directory();
BOOST_FOREACH(const Entry& entry, entries_)
{
// get the next file
FilePath filePath(entry.fileInfo.absolutePath());
// get name for comparison
std::string name = filePath.filename();
// compare for match (wildcard or standard)
bool matches = false;
if (hasWildcard)
{
matches = regex_utils::textMatches(name,
pattern,
prefixOnly,
false);
}
else
{
if (prefixOnly)
matches = boost::algorithm::istarts_with(name, term);
else
matches = boost::algorithm::icontains(name, term);
}
// add the file if we found a match
if (matches)
{
// name and project relative directory
pNames->push_back(filePath.filename());
pPaths->push_back(filePath.relativePath(projectRoot));
// return if we are past max results
if (pNames->size() > maxResults)
{
*pMoreAvailable = true;
pNames->resize(maxResults);
pPaths->resize(maxResults);
return;
}
}
}
}
private:
// index entries we are managing
struct Entry
{
Entry(const FileInfo& fileInfo,
boost::shared_ptr<core::r_util::RSourceIndex> pIndex)
: fileInfo(fileInfo), pIndex(pIndex)
{
}
FileInfo fileInfo;
boost::shared_ptr<core::r_util::RSourceIndex> pIndex;
bool operator < (const Entry& other) const
{
return core::fileInfoPathLessThan(fileInfo, other.fileInfo);
}
};
private:
void scheduleIndexing()
{
// schedule indexing -- perform up to 300ms of work immediately and then continue
// in periodic 100ms chunks until we are completed. note also that we accept the
// default behavior of only indexing during idle time so as not to interfere
// with running computations
module_context::scheduleIncrementalWork(
boost::posix_time::milliseconds(300),
boost::posix_time::milliseconds(100),
boost::bind(&SourceFileIndex::dequeAndIndex, this));
}
bool dequeAndIndex()
{
using namespace core::system;
// remove the event from the queue
FileChangeEvent event = indexingQueue_.front();
indexingQueue_.pop();
// process the change
const FileInfo& fileInfo = event.fileInfo();
switch(event.type())
{
case FileChangeEvent::FileAdded:
{
addIndexEntry(fileInfo);
break;
}
case FileChangeEvent::FileModified:
{
removeIndexEntry(fileInfo);
addIndexEntry(fileInfo);
break;
}
case FileChangeEvent::FileRemoved:
{
removeIndexEntry(fileInfo);
break;
}
case FileChangeEvent::None:
break;
}
// return status
return !indexingQueue_.empty();
}
void addIndexEntry(const FileInfo& fileInfo)
{
// read the file
FilePath filePath(fileInfo.absolutePath());
std::string code;
Error error = module_context::readAndDecodeFile(
filePath,
projects::projectContext().defaultEncoding(),
true,
&code);
if (error)
{
error.addProperty("src-file", filePath.absolutePath());
LOG_ERROR(error);
return;
}
// compute project relative directory (used for context)
std::string context = filePath.relativePath(projects::projectContext().directory());
// index the source
boost::shared_ptr<r_util::RSourceIndex> pIndex(
new r_util::RSourceIndex(context, code));
// add the entry
entries_.insert(Entry(fileInfo, pIndex));
}
void removeIndexEntry(const FileInfo& fileInfo)
{
for (std::set<Entry>::iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (core::fileInfoPathCompare(it->fileInfo, fileInfo) == 0)
{
entries_.erase(it);
break;
}
}
}
private:
// index entries
std::set<Entry> entries_;
// indexing queue
std::queue<core::system::FileChangeEvent> indexingQueue_;
};
// global source file index
SourceFileIndex s_projectIndex;
void searchSourceDatabase(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
std::vector<r_util::RSourceItem>* pItems,
std::set<std::string>* pContextsSearched)
{
// get all of the source indexes
std::vector<boost::shared_ptr<r_util::RSourceIndex> > rIndexes =
modules::source::rIndexes();
BOOST_FOREACH(boost::shared_ptr<r_util::RSourceIndex>& pIndex, rIndexes)
{
// get file path
FilePath docPath = module_context::resolveAliasedPath(pIndex->context());
// bail if the file isn't in the project
std::string projRelativePath =
docPath.relativePath(projects::projectContext().directory());
if (projRelativePath.empty())
continue;
// record that we searched this path
pContextsSearched->insert(projRelativePath);
// scan the source index
pIndex->search(term,
projRelativePath,
prefixOnly,
false,
std::back_inserter(*pItems));
// return if we are past maxResults
if (pItems->size() >= maxResults)
{
pItems->resize(maxResults);
return;
}
}
}
void searchSource(const std::string& term,
std::size_t maxResults,
bool prefixOnly,
std::vector<r_util::RSourceItem>* pItems,
bool* pMoreAvailable)
{
// default to no more available
*pMoreAvailable = false;
// first search the source database
std::set<std::string> srcDBContexts;
searchSourceDatabase(term, maxResults, prefixOnly, pItems, &srcDBContexts);
// we are done if we had >= maxResults
if (pItems->size() > maxResults)
{
*pMoreAvailable = true;
pItems->resize(maxResults);
return;
}
// compute project max results based on existing results
std::size_t maxProjResults = maxResults - pItems->size();
// now search the project (excluding contexts already searched in the source db)
std::vector<r_util::RSourceItem> projItems;
s_projectIndex.searchSource(term,
maxProjResults,
prefixOnly,
srcDBContexts,
&projItems);
// add project items to the list
BOOST_FOREACH(const r_util::RSourceItem& sourceItem, projItems)
{
// add the item
pItems->push_back(sourceItem);
// bail if we've hit the max
if (pItems->size() > maxResults)
{
*pMoreAvailable = true;
pItems->resize(maxResults);
break;
}
}
}
template <typename TValue, typename TFunc>
json::Array toJsonArray(
const std::vector<r_util::RSourceItem> &items,
TFunc memberFunc)
{
json::Array col;
std::transform(items.begin(),
items.end(),
std::back_inserter(col),
boost::bind(json::toJsonValue<TValue>,
boost::bind(memberFunc, _1)));
return col;
}
bool compareItems(const r_util::RSourceItem& i1, const r_util::RSourceItem& i2)
{
return i1.name() < i2.name();
}
Error searchCode(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get params
std::string term;
int maxResultsInt;
Error error = json::readParams(request.params, &term, &maxResultsInt);
if (error)
return error;
std::size_t maxResults = safe_convert::numberTo<std::size_t>(maxResultsInt,
20);
// object to return
json::Object result;
// search files
json::Array names;
json::Array paths;
bool moreFilesAvailable = false;
s_projectIndex.searchFiles(term,
maxResults,
true,
&names,
&paths,
&moreFilesAvailable);
json::Object files;
files["filename"] = names;
files["path"] = paths;
result["file_items"] = files;
// search source (sort results by name)
std::vector<r_util::RSourceItem> items;
bool moreSourceItemsAvailable = false;
searchSource(term, maxResults, true, &items, &moreSourceItemsAvailable);
std::sort(items.begin(), items.end(), compareItems);
// see if we need to do src truncation
bool truncated = false;
if ( (names.size() + items.size()) > maxResults )
{
// truncate source items
std::size_t srcItems = maxResults - names.size();
items.resize(srcItems);
truncated = true;
}
// return rpc array list (wire efficiency)
json::Object src;
src["type"] = toJsonArray<int>(items, &r_util::RSourceItem::type);
src["name"] = toJsonArray<std::string>(items, &r_util::RSourceItem::name);
src["context"] = toJsonArray<std::string>(items, &r_util::RSourceItem::context);
src["line"] = toJsonArray<int>(items, &r_util::RSourceItem::line);
src["column"] = toJsonArray<int>(items, &r_util::RSourceItem::column);
result["source_items"] = src;
// set more available bit
result["more_available"] =
moreFilesAvailable || moreSourceItemsAvailable || truncated;
pResponse->setResult(result);
return Success();
}
void onFileMonitorRegistered(const tree<core::FileInfo>& files)
{
s_projectIndex.enqueFiles(files.begin_leaf(), files.end_leaf());
}
void onFileMonitorRegistrationError(const core::Error& error)
{
// TODO: disable code searching
}
void onFileMonitorUnregistered()
{
// TODO: disable code searching
}
void onFilesChanged(const std::vector<core::system::FileChangeEvent>& events)
{
// index all of the changes
std::for_each(
events.begin(),
events.end(),
boost::bind(&SourceFileIndex::enqueFileChange, &s_projectIndex, _1, true));
}
} // anonymous namespace
bool enabled()
{
return projects::projectContext().hasProject();
}
Error initialize()
{
// subscribe to project context file monitoring state changes
core::system::file_monitor::Callbacks cb;
cb.onRegistered = boost::bind(onFileMonitorRegistered, _2);
cb.onRegistrationError = onFileMonitorRegistrationError;
cb.onUnregistered = boost::bind(onFileMonitorUnregistered);
cb.onFilesChanged = onFilesChanged;
projects::projectContext().registerFileMonitorCallbacks(cb);
using boost::bind;
using namespace module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "search_code", searchCode));
;
return initBlock.execute();
}
} // namespace agreement
} // namespace modules
} // namespace session
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 utilities.
*//*--------------------------------------------------------------------*/
#include "tcuX11.hpp"
#include "gluRenderConfig.hpp"
#include "deMemory.h"
#include <X11/Xutil.h>
namespace tcu
{
namespace x11
{
enum
{
DEFAULT_WINDOW_WIDTH = 400,
DEFAULT_WINDOW_HEIGHT = 300
};
EventState::EventState (void)
: m_quit(false)
{
}
EventState::~EventState (void)
{
}
void EventState::setQuitFlag (bool quit)
{
de::ScopedLock lock(m_mutex);
m_quit = quit;
}
bool EventState::getQuitFlag (void)
{
de::ScopedLock lock(m_mutex);
return m_quit;
}
Display::Display (EventState& eventState, const char* name)
: m_eventState (eventState)
, m_display (DE_NULL)
, m_deleteAtom (DE_NULL)
{
m_display = XOpenDisplay((char*)name); // Won't modify argument string.
if (!m_display)
throw ResourceError("Failed to open display", name, __FILE__, __LINE__);
m_deleteAtom = XInternAtom(m_display, "WM_DELETE_WINDOW", False);
}
Display::~Display (void)
{
XCloseDisplay(m_display);
}
void Display::processEvents (void)
{
XEvent event;
while (XPending(m_display))
{
XNextEvent(m_display, &event);
// \todo [2010-10-27 pyry] Handle ConfigureNotify?
if (event.type == ClientMessage && (unsigned)event.xclient.data.l[0] == m_deleteAtom)
m_eventState.setQuitFlag(true);
}
}
bool Display::getVisualInfo (VisualID visualID, XVisualInfo& dst)
{
XVisualInfo query;
query.visualid = visualID;
int numVisuals = 0;
XVisualInfo* response = XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals);
bool succ = false;
if (response != DE_NULL)
{
if (numVisuals > 0) // should be 1, but you never know...
{
dst = response[0];
succ = true;
}
XFree(response);
}
return succ;
}
::Visual* Display::getVisual (VisualID visualID)
{
XVisualInfo info;
if (getVisualInfo(visualID, info))
return info.visual;
return DE_NULL;
}
Window::Window (Display& display, int width, int height, ::Visual* visual)
: m_display (display)
, m_colormap (None)
, m_window (None)
, m_visible (false)
{
XSetWindowAttributes swa;
::Display* const dpy = m_display.getXDisplay();
::Window root = DefaultRootWindow(dpy);
unsigned long mask = CWBorderPixel | CWEventMask;
// If redirect is enabled, window size can't be guaranteed and it is up to
// the window manager to decide whether to honor sizing requests. However,
// overriding that causes window to appear as an overlay, which causes
// other issues, so this is disabled by default.
const bool overrideRedirect = false;
if (overrideRedirect)
{
mask |= CWOverrideRedirect;
swa.override_redirect = true;
}
if (visual == DE_NULL)
visual = CopyFromParent;
else
{
XVisualInfo info = XVisualInfo();
bool succ = display.getVisualInfo(XVisualIDFromVisual(visual), info);
TCU_CHECK_INTERNAL(succ);
root = RootWindow(dpy, info.screen);
m_colormap = XCreateColormap(dpy, root, visual, AllocNone);
swa.colormap = m_colormap;
mask |= CWColormap;
}
swa.border_pixel = 0;
swa.event_mask = ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask;
if (width == glu::RenderConfig::DONT_CARE)
width = DEFAULT_WINDOW_WIDTH;
if (height == glu::RenderConfig::DONT_CARE)
height = DEFAULT_WINDOW_HEIGHT;
m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0,
CopyFromParent, InputOutput, visual, mask, &swa);
TCU_CHECK(m_window);
Atom deleteAtom = m_display.getDeleteAtom();
XSetWMProtocols(dpy, m_window, &deleteAtom, 1);
}
void Window::setVisibility (bool visible)
{
::Display* dpy = m_display.getXDisplay();
int eventType = None;
XEvent event;
if (visible == m_visible)
return;
if (visible)
{
XMapWindow(dpy, m_window);
eventType = MapNotify;
}
else
{
XUnmapWindow(dpy, m_window);
eventType = UnmapNotify;
}
// We are only interested about exposure/structure notify events, not user input
XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask);
do
{
XNextEvent(dpy, &event);
} while (event.type != eventType);
m_visible = visible;
}
void Window::getDimensions (int* width, int* height) const
{
int x, y;
::Window root;
unsigned width_, height_, borderWidth, depth;
XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth);
if (width != DE_NULL)
*width = static_cast<int>(width_);
if (height != DE_NULL)
*height = static_cast<int>(height_);
}
void Window::setDimensions (int width, int height)
{
const unsigned int mask = CWWidth | CWHeight;
XWindowChanges changes;
changes.width = width;
changes.height = height;
XConfigureWindow(m_display.getXDisplay(), m_window, mask, &changes);
}
void Window::processEvents (void)
{
// A bit of a hack, since we don't really handle all the events.
m_display.processEvents();
}
Window::~Window (void)
{
XDestroyWindow(m_display.getXDisplay(), m_window);
if (m_colormap != None)
XFreeColormap(m_display.getXDisplay(), m_colormap);
}
} // x11
} // tcu
<commit_msg>x11: Fix deadlock am: 5e863331b2 am: f49e8bfc0e am: 1eb4f43dc4 am: c1c16c73e6<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 utilities.
*//*--------------------------------------------------------------------*/
#include "tcuX11.hpp"
#include "gluRenderConfig.hpp"
#include "deMemory.h"
#include <X11/Xutil.h>
namespace tcu
{
namespace x11
{
enum
{
DEFAULT_WINDOW_WIDTH = 400,
DEFAULT_WINDOW_HEIGHT = 300
};
EventState::EventState (void)
: m_quit(false)
{
}
EventState::~EventState (void)
{
}
void EventState::setQuitFlag (bool quit)
{
de::ScopedLock lock(m_mutex);
m_quit = quit;
}
bool EventState::getQuitFlag (void)
{
de::ScopedLock lock(m_mutex);
return m_quit;
}
Display::Display (EventState& eventState, const char* name)
: m_eventState (eventState)
, m_display (DE_NULL)
, m_deleteAtom (DE_NULL)
{
m_display = XOpenDisplay((char*)name); // Won't modify argument string.
if (!m_display)
throw ResourceError("Failed to open display", name, __FILE__, __LINE__);
m_deleteAtom = XInternAtom(m_display, "WM_DELETE_WINDOW", False);
}
Display::~Display (void)
{
XCloseDisplay(m_display);
}
void Display::processEvents (void)
{
XEvent event;
while (XPending(m_display))
{
XNextEvent(m_display, &event);
// \todo [2010-10-27 pyry] Handle ConfigureNotify?
if (event.type == ClientMessage && (unsigned)event.xclient.data.l[0] == m_deleteAtom)
m_eventState.setQuitFlag(true);
}
}
bool Display::getVisualInfo (VisualID visualID, XVisualInfo& dst)
{
XVisualInfo query;
query.visualid = visualID;
int numVisuals = 0;
XVisualInfo* response = XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals);
bool succ = false;
if (response != DE_NULL)
{
if (numVisuals > 0) // should be 1, but you never know...
{
dst = response[0];
succ = true;
}
XFree(response);
}
return succ;
}
::Visual* Display::getVisual (VisualID visualID)
{
XVisualInfo info;
if (getVisualInfo(visualID, info))
return info.visual;
return DE_NULL;
}
Window::Window (Display& display, int width, int height, ::Visual* visual)
: m_display (display)
, m_colormap (None)
, m_window (None)
, m_visible (false)
{
XSetWindowAttributes swa;
::Display* const dpy = m_display.getXDisplay();
::Window root = DefaultRootWindow(dpy);
unsigned long mask = CWBorderPixel | CWEventMask;
// If redirect is enabled, window size can't be guaranteed and it is up to
// the window manager to decide whether to honor sizing requests. However,
// overriding that causes window to appear as an overlay, which causes
// other issues, so this is disabled by default.
const bool overrideRedirect = false;
if (overrideRedirect)
{
mask |= CWOverrideRedirect;
swa.override_redirect = true;
}
if (visual == DE_NULL)
visual = CopyFromParent;
else
{
XVisualInfo info = XVisualInfo();
bool succ = display.getVisualInfo(XVisualIDFromVisual(visual), info);
TCU_CHECK_INTERNAL(succ);
root = RootWindow(dpy, info.screen);
m_colormap = XCreateColormap(dpy, root, visual, AllocNone);
swa.colormap = m_colormap;
mask |= CWColormap;
}
swa.border_pixel = 0;
swa.event_mask = ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask;
if (width == glu::RenderConfig::DONT_CARE)
width = DEFAULT_WINDOW_WIDTH;
if (height == glu::RenderConfig::DONT_CARE)
height = DEFAULT_WINDOW_HEIGHT;
m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0,
CopyFromParent, InputOutput, visual, mask, &swa);
TCU_CHECK(m_window);
Atom deleteAtom = m_display.getDeleteAtom();
XSetWMProtocols(dpy, m_window, &deleteAtom, 1);
}
void Window::setVisibility (bool visible)
{
::Display* dpy = m_display.getXDisplay();
int eventType = None;
XEvent event;
if (visible == m_visible)
return;
if (visible)
{
XMapWindow(dpy, m_window);
eventType = MapNotify;
}
else
{
XUnmapWindow(dpy, m_window);
eventType = UnmapNotify;
}
// We are only interested about exposure/structure notify events, not user input
XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask);
do
{
XWindowEvent(dpy, m_window, ExposureMask | StructureNotifyMask, &event);
} while (event.type != eventType);
m_visible = visible;
}
void Window::getDimensions (int* width, int* height) const
{
int x, y;
::Window root;
unsigned width_, height_, borderWidth, depth;
XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth);
if (width != DE_NULL)
*width = static_cast<int>(width_);
if (height != DE_NULL)
*height = static_cast<int>(height_);
}
void Window::setDimensions (int width, int height)
{
const unsigned int mask = CWWidth | CWHeight;
XWindowChanges changes;
changes.width = width;
changes.height = height;
XConfigureWindow(m_display.getXDisplay(), m_window, mask, &changes);
}
void Window::processEvents (void)
{
// A bit of a hack, since we don't really handle all the events.
m_display.processEvents();
}
Window::~Window (void)
{
XDestroyWindow(m_display.getXDisplay(), m_window);
if (m_colormap != None)
XFreeColormap(m_display.getXDisplay(), m_colormap);
}
} // x11
} // tcu
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#pragma warning(disable: 4351)
#endif
#include "FanTable.h"
#include "FanDefinition.h"
#include "../mahjong-algorithm/fan_calculator.h"
#include "../common.h"
USING_NS_CC;
static const char *principle_title[] = { "不重复", "不拆移", "不得相同", "就高不就低", "套算一次" };
static const int fanLevel[] = { 0, 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 88 }; // 番种
static const size_t eachLevelCounts[] = { 5, 13, 10, 4, 7, 9, 5, 6, 9, 3, 2, 6, 7 }; // 各档次番种的个数
static const size_t eachLevelBeginIndex[] = { 0, 69, 59, 55, 48, 39, 34, 28, 19, 16, 14, 8, 1 };
static inline size_t computeRowsAlign4(size_t cnt) {
return (cnt >> 2) + !!(cnt & 0x3);
}
bool FanTableScene::init() {
if (UNLIKELY(!BaseScene::initWithTitle("国标麻将番种表"))) {
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
cw::TableView *tableView = cw::TableView::create();
tableView->setScrollBarPositionFromCorner(Vec2(2, 2));
tableView->setScrollBarWidth(4);
tableView->setScrollBarOpacity(0x99);
tableView->setContentSize(Size(visibleSize.width - 5, visibleSize.height - 35));
tableView->setDelegate(this);
tableView->setDirection(ui::ScrollView::Direction::VERTICAL);
tableView->setVerticalFillOrder(cw::TableView::VerticalFillOrder::TOP_DOWN);
tableView->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
tableView->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f - 15.0f));
tableView->reloadData();
this->addChild(tableView);
return true;
}
ssize_t FanTableScene::numberOfCellsInTableView(cw::TableView *table) {
return 13;
}
cocos2d::Size FanTableScene::tableCellSizeForIndex(cw::TableView *table, ssize_t idx) {
size_t cnt = eachLevelCounts[idx];
float height = computeRowsAlign4(cnt) * 25.0f;
return Size(0, height + 15.0f);
}
cw::TableViewCell *FanTableScene::tableCellAtIndex(cw::TableView *table, ssize_t idx) {
typedef cw::TableViewCellEx<Label *, ui::Button *[13]> CustomCell;
CustomCell *cell = (CustomCell *)table->dequeueCell();
Size visibleSize = Director::getInstance()->getVisibleSize();
const float gap = (visibleSize.width - 5.0f) * 0.25f;
if (cell == nullptr) {
cell = CustomCell::create();
CustomCell::ExtDataType &ext = cell->getExtData();
Label *&label = std::get<0>(ext);
ui::Button *(&buttons)[13] = std::get<1>(ext);
label = Label::createWithSystemFont("1番", "Arial", 12);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
cell->addChild(label);
label->setColor(Color3B::BLACK);
for (size_t k = 0; k < 13; ++k) {
ui::Button *button = ui::Button::create("source_material/btn_square_normal.png", "source_material/btn_square_highlighted.png");
button->setScale9Enabled(true);
button->setContentSize(Size(gap - 4.0f, 20.0f));
button->setTitleColor(Color3B::BLACK);
button->setTitleFontSize(12);
button->addClickEventListener(std::bind(&FanTableScene::onPointsNameButton, this, std::placeholders::_1));
cell->addChild(button);
buttons[k] = button;
}
}
const size_t currentLevelCount = eachLevelCounts[idx];
size_t totalRows = computeRowsAlign4(currentLevelCount);
const CustomCell::ExtDataType ext = cell->getExtData();
Label *label = std::get<0>(ext);
ui::Button *const (&buttons)[13] = std::get<1>(ext);
size_t idx0;
const char **titleTexts;
if (fanLevel[idx] == 0) {
label->setString("基本计分原则");
idx0 = 100;
titleTexts = &principle_title[0];
}
else {
label->setString(std::to_string(fanLevel[idx]).append("番"));
idx0 = eachLevelBeginIndex[idx];
titleTexts = &mahjong::fan_name[idx0];
}
label->setPosition(Vec2(5.0f, totalRows * 25.0f + 7.0f));
for (size_t k = 0; k < currentLevelCount; ++k) {
ui::Button *button = buttons[k];
button->setTitleText(titleTexts[k]);
button->setUserData(reinterpret_cast<void *>(idx0 + k));
button->setVisible(true);
button->setEnabled(true);
size_t col = k & 0x3;
size_t row = k >> 2;
button->setPosition(Vec2(gap * (col + 0.5f), (totalRows - row - 0.5f) * 25.0f));
Common::scaleLabelToFitWidth(button->getTitleLabel(), gap - 8.0f);
}
for (size_t k = currentLevelCount; k < 13; ++k) {
buttons[k]->setVisible(false);
buttons[k]->setEnabled(false);
}
return cell;
}
void FanTableScene::onPointsNameButton(cocos2d::Ref *sender) {
ui::Button *button = (ui::Button *)sender;
size_t idx = reinterpret_cast<size_t>(button->getUserData());
Director::getInstance()->pushScene(FanDefinitionScene::create(idx));
}
<commit_msg>增加“原则”二字<commit_after>#ifdef _MSC_VER
#pragma warning(disable: 4351)
#endif
#include "FanTable.h"
#include "FanDefinition.h"
#include "../mahjong-algorithm/fan_calculator.h"
#include "../common.h"
USING_NS_CC;
static const char *principle_title[] = { "不重复原则", "不拆移原则", "不得相同原则", "就高不就低", "套算一次原则" };
static const int fanLevel[] = { 0, 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 88 }; // 番种
static const size_t eachLevelCounts[] = { 5, 13, 10, 4, 7, 9, 5, 6, 9, 3, 2, 6, 7 }; // 各档次番种的个数
static const size_t eachLevelBeginIndex[] = { 0, 69, 59, 55, 48, 39, 34, 28, 19, 16, 14, 8, 1 };
static inline size_t computeRowsAlign4(size_t cnt) {
return (cnt >> 2) + !!(cnt & 0x3);
}
bool FanTableScene::init() {
if (UNLIKELY(!BaseScene::initWithTitle("国标麻将番种表"))) {
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
cw::TableView *tableView = cw::TableView::create();
tableView->setScrollBarPositionFromCorner(Vec2(2, 2));
tableView->setScrollBarWidth(4);
tableView->setScrollBarOpacity(0x99);
tableView->setContentSize(Size(visibleSize.width - 5, visibleSize.height - 35));
tableView->setDelegate(this);
tableView->setDirection(ui::ScrollView::Direction::VERTICAL);
tableView->setVerticalFillOrder(cw::TableView::VerticalFillOrder::TOP_DOWN);
tableView->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
tableView->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f - 15.0f));
tableView->reloadData();
this->addChild(tableView);
return true;
}
ssize_t FanTableScene::numberOfCellsInTableView(cw::TableView *table) {
return 13;
}
cocos2d::Size FanTableScene::tableCellSizeForIndex(cw::TableView *table, ssize_t idx) {
size_t cnt = eachLevelCounts[idx];
float height = computeRowsAlign4(cnt) * 25.0f;
return Size(0, height + 15.0f);
}
cw::TableViewCell *FanTableScene::tableCellAtIndex(cw::TableView *table, ssize_t idx) {
typedef cw::TableViewCellEx<Label *, ui::Button *[13]> CustomCell;
CustomCell *cell = (CustomCell *)table->dequeueCell();
Size visibleSize = Director::getInstance()->getVisibleSize();
const float gap = (visibleSize.width - 5.0f) * 0.25f;
if (cell == nullptr) {
cell = CustomCell::create();
CustomCell::ExtDataType &ext = cell->getExtData();
Label *&label = std::get<0>(ext);
ui::Button *(&buttons)[13] = std::get<1>(ext);
label = Label::createWithSystemFont("1番", "Arial", 12);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
cell->addChild(label);
label->setColor(Color3B::BLACK);
for (size_t k = 0; k < 13; ++k) {
ui::Button *button = ui::Button::create("source_material/btn_square_normal.png", "source_material/btn_square_highlighted.png");
button->setScale9Enabled(true);
button->setContentSize(Size(gap - 4.0f, 20.0f));
button->setTitleColor(Color3B::BLACK);
button->setTitleFontSize(12);
button->addClickEventListener(std::bind(&FanTableScene::onPointsNameButton, this, std::placeholders::_1));
cell->addChild(button);
buttons[k] = button;
}
}
const size_t currentLevelCount = eachLevelCounts[idx];
size_t totalRows = computeRowsAlign4(currentLevelCount);
const CustomCell::ExtDataType ext = cell->getExtData();
Label *label = std::get<0>(ext);
ui::Button *const (&buttons)[13] = std::get<1>(ext);
size_t idx0;
const char **titleTexts;
if (fanLevel[idx] == 0) {
label->setString("基本计分原则");
idx0 = 100;
titleTexts = &principle_title[0];
}
else {
label->setString(std::to_string(fanLevel[idx]).append("番"));
idx0 = eachLevelBeginIndex[idx];
titleTexts = &mahjong::fan_name[idx0];
}
label->setPosition(Vec2(5.0f, totalRows * 25.0f + 7.0f));
for (size_t k = 0; k < currentLevelCount; ++k) {
ui::Button *button = buttons[k];
button->setTitleText(titleTexts[k]);
button->setUserData(reinterpret_cast<void *>(idx0 + k));
button->setVisible(true);
button->setEnabled(true);
size_t col = k & 0x3;
size_t row = k >> 2;
button->setPosition(Vec2(gap * (col + 0.5f), (totalRows - row - 0.5f) * 25.0f));
Common::scaleLabelToFitWidth(button->getTitleLabel(), gap - 8.0f);
}
for (size_t k = currentLevelCount; k < 13; ++k) {
buttons[k]->setVisible(false);
buttons[k]->setEnabled(false);
}
return cell;
}
void FanTableScene::onPointsNameButton(cocos2d::Ref *sender) {
ui::Button *button = (ui::Button *)sender;
size_t idx = reinterpret_cast<size_t>(button->getUserData());
Director::getInstance()->pushScene(FanDefinitionScene::create(idx));
}
<|endoftext|> |
<commit_before><commit_msg>Disk cache: Cleanup file_posix so that it uses the latest version of InFlightIO & Co.<commit_after><|endoftext|> |
<commit_before><commit_msg>[http] use proper conversion from string to unsigned long<commit_after><|endoftext|> |
<commit_before>#include "Log.h"
#include "Platform.h"
#include "MemoryBuffer.h"
#include <gtest/gtest.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/coded_stream.h>
#include <fcntl.h> // FOR MINGW + O_RDONLY
using namespace std;
using namespace google::protobuf;
TEST(TestFileSystem3, ZeroCopyInputStream)
{
fs::path path = "Georgia_Regular_64.fnt";
io::CodedInputStream *codedInput = nullptr;
io::ZeroCopyInputStream *rawInput = nullptr;
shared_ptr<chr::MemoryBuffer> memoryBuffer;
int fd = 0;
if (chr::hasMemoryResources())
{
memoryBuffer = chr::getResourceBuffer(path);
if (memoryBuffer)
{
codedInput = new io::CodedInputStream(reinterpret_cast<const uint8*>(memoryBuffer->data()), memoryBuffer->size());
}
else
{
ADD_FAILURE() << "chr::getResourceBuffer";
}
}
else if (chr::hasFileResources())
{
auto resPath = chr::getResourcePath(path);
fd = open(resPath.string().data(), O_RDONLY);
if (fd > 0)
{
rawInput = new io::FileInputStream(fd);
codedInput = new io::CodedInputStream(rawInput);
}
else
{
ADD_FAILURE() << "open";
}
}
if (codedInput)
{
string version;
if (codedInput->ReadString(&version, 9))
{
LOGI << "{" << version << "}" << endl;
delete codedInput;
if (rawInput)
{
delete rawInput;
close(fd);
}
}
else
{
ADD_FAILURE() << "CodedInputStream::ReadString";
}
}
}
<commit_msg>TestingFileSystem3: CHECKING CodedInputStream::ReadLittleEndian32()<commit_after>#include "Log.h"
#include "Platform.h"
#include "MemoryBuffer.h"
#include <gtest/gtest.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/coded_stream.h>
#include <fcntl.h> // FOR MINGW + O_RDONLY
using namespace std;
using namespace google::protobuf;
TEST(TestFileSystem3, ZeroCopyInputStream)
{
fs::path path = "Georgia_Regular_64.fnt";
io::CodedInputStream *codedInput = nullptr;
io::ZeroCopyInputStream *rawInput = nullptr;
shared_ptr<chr::MemoryBuffer> memoryBuffer;
int fd = 0;
if (chr::hasMemoryResources())
{
memoryBuffer = chr::getResourceBuffer(path);
if (memoryBuffer)
{
codedInput = new io::CodedInputStream(reinterpret_cast<const uint8*>(memoryBuffer->data()), memoryBuffer->size());
}
else
{
ADD_FAILURE() << "chr::getResourceBuffer";
}
}
else if (chr::hasFileResources())
{
auto resPath = chr::getResourcePath(path);
fd = open(resPath.string().data(), O_RDONLY);
if (fd > 0)
{
rawInput = new io::FileInputStream(fd);
codedInput = new io::CodedInputStream(rawInput);
}
else
{
ADD_FAILURE() << "open";
}
}
if (codedInput)
{
string version;
EXPECT_TRUE(codedInput->ReadString(&version, 9));
EXPECT_EQ("XFONT.004", version);
EXPECT_TRUE(codedInput->Skip(1)); // XXX
uint32 glyphCount;
EXPECT_TRUE(codedInput->ReadLittleEndian32(&glyphCount));
EXPECT_EQ(191, glyphCount);
float baseSize;
EXPECT_TRUE(codedInput->ReadLittleEndian32(reinterpret_cast<uint32_t*>(&baseSize)));
EXPECT_EQ(64, baseSize);
// ---
delete codedInput;
if (rawInput)
{
delete rawInput;
close(fd);
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008-2015 The Communi Project
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "textinput.h"
#include <QStyleOptionFrame>
#include <IrcCommandParser>
#include <IrcBufferModel>
#include <IrcConnection>
#include <QMessageBox>
#include <QSettings>
#include <QCheckBox>
#include <IrcBuffer>
#include <QKeyEvent>
#include <QPainter>
TextInput::TextInput(QWidget* parent) : QLineEdit(parent)
{
setAttribute(Qt::WA_MacShowFocusRect, false);
d.hint = "...";
d.index = 0;
d.buffer = 0;
d.parser = 0;
d.completer = new IrcCompleter(this);
connect(this, SIGNAL(bufferChanged(IrcBuffer*)), d.completer, SLOT(setBuffer(IrcBuffer*)));
connect(this, SIGNAL(parserChanged(IrcCommandParser*)), d.completer, SLOT(setParser(IrcCommandParser*)));
connect(d.completer, SIGNAL(completed(QString,int)), this, SLOT(doComplete(QString,int)));
connect(this, SIGNAL(textEdited(QString)), d.completer, SLOT(reset()));
connect(this, SIGNAL(returnPressed()), this, SLOT(sendInput()));
connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateHint(QString)));
}
IrcBuffer* TextInput::buffer() const
{
return d.buffer;
}
IrcCommandParser* TextInput::parser() const
{
return d.parser;
}
static void bind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::connect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::connect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
parser->setTarget(buffer->title());
parser->setChannels(buffer->model()->channels());
} else if (parser) {
parser->reset();
}
}
static void unbind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::disconnect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::disconnect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
}
}
void TextInput::setBuffer(IrcBuffer* buffer)
{
if (d.buffer != buffer) {
unbind(d.buffer, d.parser);
bind(buffer, d.parser);
if (d.buffer)
d.states.insert(d.buffer, saveState());
d.buffer = buffer;
if (buffer)
restoreState(d.states.value(buffer));
emit bufferChanged(buffer);
}
}
void TextInput::setParser(IrcCommandParser* parser)
{
if (d.parser != parser) {
unbind(d.buffer, d.parser);
bind(d.buffer, parser);
d.parser = parser;
emit parserChanged(parser);
}
}
bool TextInput::event(QEvent* event)
{
if (event->type() == QEvent::KeyPress) {
switch (static_cast<QKeyEvent*>(event)->key()) {
case Qt::Key_Tab:
tryComplete(IrcCompleter::Forward);
return true;
case Qt::Key_Backtab:
tryComplete(IrcCompleter::Backward);
return true;
case Qt::Key_Up:
goBackward();
return true;
case Qt::Key_Down:
goForward();
return true;
default:
break;
}
}
return QLineEdit::event(event);
}
// copied from qlineedit.cpp:
#define vMargin 1
#define hMargin 2
void TextInput::paintEvent(QPaintEvent* event)
{
QLineEdit::paintEvent(event);
if (!d.hint.isEmpty()) {
QStyleOptionFrameV2 option;
initStyleOption(&option);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &option, this);
int left, top, right, bottom;
getTextMargins(&left, &top, &right, &bottom);
left += qMax(0, -fontMetrics().minLeftBearing());
r.adjust(left, top, -right, -bottom);
r.adjust(hMargin, vMargin, -hMargin, -vMargin);
QString txt = text();
if (!txt.isEmpty()) {
if (!txt.endsWith(" "))
txt += " ";
r.adjust(fontMetrics().width(txt), 0, 0, 0);
}
QPainter painter(this);
QColor color = palette().text().color();
color.setAlpha(128);
painter.setPen(color);
QString hint = fontMetrics().elidedText(d.hint, Qt::ElideRight, r.width());
painter.drawText(r, alignment(), hint);
}
}
void TextInput::updateHint(const QString& text)
{
QString match;
QStringList params;
QStringList suggestions;
if (d.parser) {
if (text.startsWith('/')) {
QStringList words = text.mid(1).split(" ");
QString command = words.value(0);
params = words.mid(1);
foreach (const QString& available, d.parser->commands()) {
if (!command.compare(available, Qt::CaseInsensitive)) {
match = available;
break;
} else if (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)) {
suggestions += available;
}
}
}
}
if (!match.isEmpty()) {
QStringList syntax = d.parser->syntax(match).split(" ", QString::SkipEmptyParts).mid(1);
if (!params.isEmpty())
d.hint = QStringList(syntax.mid(params.count() - 1)).join(" ");
else
d.hint = syntax.join(" ");
} else if (suggestions.isEmpty()) {
d.hint = text.isEmpty() ? "..." : "";
} else if (suggestions.count() == 1) {
d.hint = d.parser->syntax(suggestions.first());
} else {
d.hint = suggestions.join(" ");
}
}
void TextInput::goBackward()
{
if (!text().isEmpty() && !d.history.contains(text()))
d.current = text();
if (d.index > 0)
setText(d.history.value(--d.index));
}
void TextInput::goForward()
{
if (d.index < d.history.count())
setText(d.history.value(++d.index));
if (text().isEmpty())
setText(d.current);
}
void TextInput::sendInput()
{
IrcBuffer* b = buffer();
IrcCommandParser* p = parser();
IrcConnection* c = b ? b->connection() : 0;
if (!c || !p)
return;
const QStringList lines = text().split(QRegExp("[\\r\\n]"), QString::SkipEmptyParts);
#if QT_VERSION >= 0x050200
if (lines.count() > 2) {
QSettings settings;
bool warn = settings.value("warn", true).toBool();
if (warn) {
QMessageBox msgBox;
msgBox.setText(tr("The input contains more than two lines."));
msgBox.setInformativeText(tr("IRC is not a suitable medium for pasting multiple lines of text. Consider using a pastebin site instead.\n\n"
"Do you still want to proceed and send %1 lines of text?\n").arg(lines.count()));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
QCheckBox* checkBox = new QCheckBox(tr("Do not show again"), &msgBox);
msgBox.setCheckBox(checkBox);
int res = msgBox.exec();
settings.setValue("warn", !checkBox->isChecked());
if (res != QMessageBox::Yes)
return;
}
}
#endif
if (!text().isEmpty()) {
d.current.clear();
d.history.append(text());
d.index = d.history.count();
}
bool error = false;
foreach (const QString& line, lines) {
if (!line.trimmed().isEmpty()) {
IrcCommand* cmd = p->parse(line);
if (cmd) {
cmd->setProperty("TextInput", true);
b->sendCommand(cmd);
IrcNetwork* network = b->network();
if (network && network->isCapable("echo-message"))
continue;
if (cmd->type() == IrcCommand::Message || cmd->type() == IrcCommand::Notice || cmd->type() == IrcCommand::CtcpAction) {
IrcMessage* msg = cmd->toMessage(c->nickName(), c);
if (msg) {
b->receiveMessage(msg);
msg->deleteLater();
}
}
} else {
error = true;
}
}
}
if (!error)
clear();
}
void TextInput::tryComplete(IrcCompleter::Direction direction)
{
d.completer->complete(text(), cursorPosition(), direction);
}
void TextInput::doComplete(const QString& text, int cursor)
{
setText(text);
setCursorPosition(cursor);
}
QByteArray TextInput::saveState() const
{
QByteArray data;
QDataStream out(&data, QIODevice::WriteOnly);
out << d.index << d.current << d.history;
out << text() << cursorPosition() << selectionStart() << selectedText().length();
return data;
}
void TextInput::restoreState(const QByteArray& state)
{
QDataStream in(state);
in >> d.index >> d.current >> d.history;
QString txt;
int pos, start, len;
in >> txt >> pos >> start >> len;
setText(txt);
setCursorPosition(pos);
if (start != -1)
setSelection(start, len);
}
<commit_msg>TextInput: let sent messages through even when echo-message is active<commit_after>/*
Copyright (C) 2008-2015 The Communi Project
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "textinput.h"
#include <QStyleOptionFrame>
#include <IrcCommandParser>
#include <IrcBufferModel>
#include <IrcConnection>
#include <QMessageBox>
#include <QSettings>
#include <QCheckBox>
#include <IrcBuffer>
#include <QKeyEvent>
#include <QPainter>
TextInput::TextInput(QWidget* parent) : QLineEdit(parent)
{
setAttribute(Qt::WA_MacShowFocusRect, false);
d.hint = "...";
d.index = 0;
d.buffer = 0;
d.parser = 0;
d.completer = new IrcCompleter(this);
connect(this, SIGNAL(bufferChanged(IrcBuffer*)), d.completer, SLOT(setBuffer(IrcBuffer*)));
connect(this, SIGNAL(parserChanged(IrcCommandParser*)), d.completer, SLOT(setParser(IrcCommandParser*)));
connect(d.completer, SIGNAL(completed(QString,int)), this, SLOT(doComplete(QString,int)));
connect(this, SIGNAL(textEdited(QString)), d.completer, SLOT(reset()));
connect(this, SIGNAL(returnPressed()), this, SLOT(sendInput()));
connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateHint(QString)));
}
IrcBuffer* TextInput::buffer() const
{
return d.buffer;
}
IrcCommandParser* TextInput::parser() const
{
return d.parser;
}
static void bind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::connect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::connect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
parser->setTarget(buffer->title());
parser->setChannels(buffer->model()->channels());
} else if (parser) {
parser->reset();
}
}
static void unbind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::disconnect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::disconnect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
}
}
void TextInput::setBuffer(IrcBuffer* buffer)
{
if (d.buffer != buffer) {
unbind(d.buffer, d.parser);
bind(buffer, d.parser);
if (d.buffer)
d.states.insert(d.buffer, saveState());
d.buffer = buffer;
if (buffer)
restoreState(d.states.value(buffer));
emit bufferChanged(buffer);
}
}
void TextInput::setParser(IrcCommandParser* parser)
{
if (d.parser != parser) {
unbind(d.buffer, d.parser);
bind(d.buffer, parser);
d.parser = parser;
emit parserChanged(parser);
}
}
bool TextInput::event(QEvent* event)
{
if (event->type() == QEvent::KeyPress) {
switch (static_cast<QKeyEvent*>(event)->key()) {
case Qt::Key_Tab:
tryComplete(IrcCompleter::Forward);
return true;
case Qt::Key_Backtab:
tryComplete(IrcCompleter::Backward);
return true;
case Qt::Key_Up:
goBackward();
return true;
case Qt::Key_Down:
goForward();
return true;
default:
break;
}
}
return QLineEdit::event(event);
}
// copied from qlineedit.cpp:
#define vMargin 1
#define hMargin 2
void TextInput::paintEvent(QPaintEvent* event)
{
QLineEdit::paintEvent(event);
if (!d.hint.isEmpty()) {
QStyleOptionFrameV2 option;
initStyleOption(&option);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &option, this);
int left, top, right, bottom;
getTextMargins(&left, &top, &right, &bottom);
left += qMax(0, -fontMetrics().minLeftBearing());
r.adjust(left, top, -right, -bottom);
r.adjust(hMargin, vMargin, -hMargin, -vMargin);
QString txt = text();
if (!txt.isEmpty()) {
if (!txt.endsWith(" "))
txt += " ";
r.adjust(fontMetrics().width(txt), 0, 0, 0);
}
QPainter painter(this);
QColor color = palette().text().color();
color.setAlpha(128);
painter.setPen(color);
QString hint = fontMetrics().elidedText(d.hint, Qt::ElideRight, r.width());
painter.drawText(r, alignment(), hint);
}
}
void TextInput::updateHint(const QString& text)
{
QString match;
QStringList params;
QStringList suggestions;
if (d.parser) {
if (text.startsWith('/')) {
QStringList words = text.mid(1).split(" ");
QString command = words.value(0);
params = words.mid(1);
foreach (const QString& available, d.parser->commands()) {
if (!command.compare(available, Qt::CaseInsensitive)) {
match = available;
break;
} else if (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)) {
suggestions += available;
}
}
}
}
if (!match.isEmpty()) {
QStringList syntax = d.parser->syntax(match).split(" ", QString::SkipEmptyParts).mid(1);
if (!params.isEmpty())
d.hint = QStringList(syntax.mid(params.count() - 1)).join(" ");
else
d.hint = syntax.join(" ");
} else if (suggestions.isEmpty()) {
d.hint = text.isEmpty() ? "..." : "";
} else if (suggestions.count() == 1) {
d.hint = d.parser->syntax(suggestions.first());
} else {
d.hint = suggestions.join(" ");
}
}
void TextInput::goBackward()
{
if (!text().isEmpty() && !d.history.contains(text()))
d.current = text();
if (d.index > 0)
setText(d.history.value(--d.index));
}
void TextInput::goForward()
{
if (d.index < d.history.count())
setText(d.history.value(++d.index));
if (text().isEmpty())
setText(d.current);
}
void TextInput::sendInput()
{
IrcBuffer* b = buffer();
IrcCommandParser* p = parser();
IrcConnection* c = b ? b->connection() : 0;
if (!c || !p)
return;
const QStringList lines = text().split(QRegExp("[\\r\\n]"), QString::SkipEmptyParts);
#if QT_VERSION >= 0x050200
if (lines.count() > 2) {
QSettings settings;
bool warn = settings.value("warn", true).toBool();
if (warn) {
QMessageBox msgBox;
msgBox.setText(tr("The input contains more than two lines."));
msgBox.setInformativeText(tr("IRC is not a suitable medium for pasting multiple lines of text. Consider using a pastebin site instead.\n\n"
"Do you still want to proceed and send %1 lines of text?\n").arg(lines.count()));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
QCheckBox* checkBox = new QCheckBox(tr("Do not show again"), &msgBox);
msgBox.setCheckBox(checkBox);
int res = msgBox.exec();
settings.setValue("warn", !checkBox->isChecked());
if (res != QMessageBox::Yes)
return;
}
}
#endif
if (!text().isEmpty()) {
d.current.clear();
d.history.append(text());
d.index = d.history.count();
}
bool error = false;
foreach (const QString& line, lines) {
if (!line.trimmed().isEmpty()) {
IrcCommand* cmd = p->parse(line);
if (cmd) {
cmd->setProperty("TextInput", true);
b->sendCommand(cmd);
if (cmd->type() == IrcCommand::Message || cmd->type() == IrcCommand::Notice || cmd->type() == IrcCommand::CtcpAction) {
IrcMessage* msg = cmd->toMessage(c->nickName(), c);
if (msg) {
b->receiveMessage(msg);
msg->deleteLater();
}
}
} else {
error = true;
}
}
}
if (!error)
clear();
}
void TextInput::tryComplete(IrcCompleter::Direction direction)
{
d.completer->complete(text(), cursorPosition(), direction);
}
void TextInput::doComplete(const QString& text, int cursor)
{
setText(text);
setCursorPosition(cursor);
}
QByteArray TextInput::saveState() const
{
QByteArray data;
QDataStream out(&data, QIODevice::WriteOnly);
out << d.index << d.current << d.history;
out << text() << cursorPosition() << selectionStart() << selectedText().length();
return data;
}
void TextInput::restoreState(const QByteArray& state)
{
QDataStream in(state);
in >> d.index >> d.current >> d.history;
QString txt;
int pos, start, len;
in >> txt >> pos >> start >> len;
setText(txt);
setCursorPosition(pos);
if (start != -1)
setSelection(start, len);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2002-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* XSEC
*
* XSECCryptoSymmetricKey := Bulk encryption algorithms should all be
* implemented via this interface
*
* Author(s): Berin Lautenbach
*
* $Id$
*
*/
#ifndef WINCAPICRYPTOSYMMETRICKEY_INCLUDE
#define WINCAPICRYPTOSYMMETRICKEY_INCLUDE
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/enc/XSECCryptoSymmetricKey.hpp>
#if defined (HAVE_WINCAPI)
#if !defined(_WIN32_WINNT)
# define _WIN32_WINNT 0x0400
#endif
#include <wincrypt.h>
#define WINCAPI_MAX_BLOCK_SIZE 32
/**
* \ingroup wincapicrypto
* @{
*/
/**
* \brief Base interface definition for symmetric key material.
*
* This is the implementation for a wrapper of Windows CryptoAPI symmetric
* crypto functions.
*/
class DSIG_EXPORT WinCAPICryptoSymmetricKey : public XSECCryptoSymmetricKey {
public :
/** @name Constructors and Destructors */
//@{
/**
* \brief Constructor
*
* Can only construct a Symmetric key if we know what type it is
*
* @param prov The appropriate provider that supports the required algorithm.
* Can be 0 if the app is going to pass in an octet via setKey, as the library
* will use its own internal key store and handle to CSP.
* @param type The type of key (i.e. algorithm) to create
**/
WinCAPICryptoSymmetricKey(HCRYPTPROV prov, XSECCryptoSymmetricKey::SymmetricKeyType type);
/**
* \brief Destructor
*
* Implementations must ensure that the held key is properly destroyed
* (overwritten) when key objects are deleted.
*/
virtual ~WinCAPICryptoSymmetricKey();
//@}
/** @name Basic CryptoKey Interface methods */
//@{
/**
* \brief Returns a string that identifies the crypto owner of this library.
*/
virtual const XMLCh * getProviderName();
/**
* \brief Clone the key
*
* All keys need to be able to copy themselves and return
* a pointer to the copy. This allows the library to
* duplicate keys.
*/
virtual XSECCryptoKey * clone();
//@}
/** @name Symmetric key interface methods */
//@{
/**
* \brief What type of symmetric key is this?
*
* There are a number of different types of symmetric key.
* This method allows callers to determine the type of this
* particular key
*/
SymmetricKeyType getSymmetricKeyType(void);
/**
* \brief Set the key from the provided bytes
*
* Symmetric keys can all be loaded from a buffer containing a series
* of bytes.
*
* @param key The buffer containing the key bytes
* @param keyLen The number of key bytes in the buffer
*
*/
void setKey(const unsigned char * key, unsigned int keyLen);
/**
* \brief Initialise an decryption process
*
* Setup the key to get ready for a decryption session.
* Callers can pass in an IV. If one is not provided,
* but the algorithm requires one (e.g. 3DES_CBC), then
* implementations should assume that the start of the
* cipher text stream will in fact be the IV.
*
* @param doPad By default, we perform padding for last block
* @param mode mode selection (Currently ECB or CBC mode only)
* @param iv Initialisation Vector to be used. NULL if one is
* not required, or if IV will be set from data stream
* @returns true if the initialisation succeeded.
*/
virtual bool decryptInit(bool doPad = true,
SymmetricKeyMode mode = MODE_CBC,
const unsigned char * iv = NULL);
/**
* \brief Continue an decrypt operation using this key.
*
* Decryption must have been set up using an encryptInit
* call. Takes the inBuf and continues a decryption operation,
* writing the output to outBuf.
*
* This function does not have to guarantee that all input
* will be decrypted. In cases where the input is not a length
* of the block size, the implementation will need to hold back
* cipher-text to be handles during the next operation.
*
* @note While maxOutLength is defined, the OpenSSL libraries will
* not read the value, so the onus is on the caller to ensure the
* buffer is long enough to hold the output!
*
* @param inBuf Octets to be decrypted
* @param plainBuf Buffer to place output in
* @param inLength Number of bytes to decrypt
* @param maxOutLength Maximum number of bytes to place in output
* buffer
* @returns Bytes placed in output Buffer
*/
virtual unsigned int decrypt(const unsigned char * inBuf,
unsigned char * plainBuf,
unsigned int inLength,
unsigned int maxOutLength);
/**
* \brief Finish a decryption operation
*
* Complete a decryption process. No cipher text is passed in,
* as this should simply be removing any remaining text from
* the plain storage buffer.
*
* May throw an exception if there is some stored cipher text
* that is not the length of the block size for block algorithms.
*
* @note While maxOutLength is defined, the OpenSSL libraries will
* not read the value, so the onus is on the caller to ensure the
* buffer is long enough to hold the output!
*
* @param plainBuf Buffer to place any remaining plain text in
* @param maxOutLength Maximum number of bytes to pace in output
* @returns Bytes placed in output buffer
*/
virtual unsigned int decryptFinish(unsigned char * plainBuf,
unsigned int maxOutLength);
/**
* \brief Initialise an encryption process
*
* Setup the key to get ready for a decryption session.
* Callers can pass in an IV. If one is not provided,
* but the algorithm requires one (e.g. 3DES_CBC), then
* implementations are required to generate one.
*
* @param doPad By default, we perform padding for last block
* @param mode What mode to handle blocks (Currently CBC or ECB)
* @param iv Initialisation Vector to be used. NULL if one is
* not required, or if IV is to be generated
* @returns true if the initialisation succeeded.
*/
virtual bool encryptInit(bool doPad = true,
SymmetricKeyMode mode = MODE_CBC,
const unsigned char * iv = NULL);
/**
* \brief Continue an encryption operation using this key.
*
* Encryption must have been set up using an encryptInit
* call. Takes the inBuf and continues a encryption operation,
* writing the output to outBuf.
*
* This function does not have to guarantee that all input
* will be encrypted. In cases where the input is not a length
* of the block size, the implementation will need to hold back
* plain-text to be handled during the next operation.
*
* @param inBuf Octets to be encrypted
* @param cipherBuf Buffer to place output in
* @param inLength Number of bytes to encrypt
* @param maxOutLength Maximum number of bytes to place in output
* buffer
* @returns Bytes placed in output Buffer
*/
virtual unsigned int encrypt(const unsigned char * inBuf,
unsigned char * cipherBuf,
unsigned int inLength,
unsigned int maxOutLength);
/**
* \brief Finish a encryption operation
*
* Complete a encryption process. No plain text is passed in,
* as this should simply be removing any remaining text from
* the plain storage buffer and creating a final padded block.
*
* Padding is performed by taking the remaining block, and
* setting the last byte to equal the number of bytes of
* padding. If the plain was an exact multiple of the block size,
* then an extra block of padding will be used. For example, if
* the block size is 8 bytes, and there were three remaining plain
* text bytes (0x01, 0x02 and 0x03), the final block will be :
*
* 0x010203????????05
*
* @param cipherBuf Buffer to place final block of cipher text in
* @param maxOutLength Maximum number of bytes to pace in output
* @returns Bytes placed in output buffer
*/
virtual unsigned int encryptFinish(unsigned char * plainBuf,
unsigned int maxOutLength);
//@}
/** @name Windows utility functions */
//@{
/**
* \brief Create a symmetric key from a octet string
*
* Uses the ApacheKeyStore to wrap an octet string in a public key
* and then load it into the Apache Key Container within the defined
* CSP
*
* @param key The buffer of bytes to load from
* @param keyLen The number of bytes to load
* @param type The key type to create from the bytes
* @param prov If NULL, ignored. If non-null, but *prov == 0, the
* function will use an internal handle to a CSP and return the value
* in *prov. If *prov != 0, use contents of *prov as the provider to
* load the key into. NOTE - The provider <em>must</em> have a
* AT_KEYEXCHANGE key pair available.
* @returns a pointer to the key or 0 on failure
*/
static HCRYPTKEY createWindowsKey(const unsigned char * key,
unsigned int keyLen,
XSECCryptoSymmetricKey::SymmetricKeyType type,
HCRYPTPROV * prov);
private:
// Unimplemented constructors
WinCAPICryptoSymmetricKey();
WinCAPICryptoSymmetricKey(const WinCAPICryptoSymmetricKey &);
WinCAPICryptoSymmetricKey & operator= (const WinCAPICryptoSymmetricKey &);
int decryptCtxInit(const unsigned char * iv);
void encryptCtxInit(const unsigned char * iv);
// Private variables
SymmetricKeyType m_keyType;
SymmetricKeyMode m_keyMode; // ECB or CBC
safeBuffer m_keyBuf; // Holder of the key
unsigned int m_keyLen;
bool m_initialised;
bool m_doPad;
unsigned char m_lastBlock[WINCAPI_MAX_BLOCK_SIZE];
unsigned int m_bytesInLastBlock;
unsigned int m_blockSize;
unsigned int m_ivSize;
HCRYPTPROV m_p;
HCRYPTKEY m_k;
};
#endif /* HAVE_WINCAPI */
#endif /* WINCAPICRYPTOSYMMETRICKEY_INCLUDE */
<commit_msg>Minor typo fix.<commit_after>/*
* Copyright 2002-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* XSEC
*
* XSECCryptoSymmetricKey := Bulk encryption algorithms should all be
* implemented via this interface
*
* Author(s): Berin Lautenbach
*
* $Id$
*
*/
#ifndef WINCAPICRYPTOSYMMETRICKEY_INCLUDE
#define WINCAPICRYPTOSYMMETRICKEY_INCLUDE
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/enc/XSECCryptoSymmetricKey.hpp>
#if defined (HAVE_WINCAPI)
#if !defined(_WIN32_WINNT)
# define _WIN32_WINNT 0x0400
#endif
#include <wincrypt.h>
#define WINCAPI_MAX_BLOCK_SIZE 32
/**
* \ingroup wincapicrypto
* @{
*/
/**
* \brief Base interface definition for symmetric key material.
*
* This is the implementation for a wrapper of Windows CryptoAPI symmetric
* crypto functions.
*/
class DSIG_EXPORT WinCAPICryptoSymmetricKey : public XSECCryptoSymmetricKey {
public :
/** @name Constructors and Destructors */
//@{
/**
* \brief Constructor
*
* Can only construct a Symmetric key if we know what type it is
*
* @param prov The appropriate provider that supports the required algorithm.
* Can be 0 if the app is going to pass in an octet via setKey, as the library
* will use its own internal key store and handle to CSP.
* @param type The type of key (i.e. algorithm) to create
**/
WinCAPICryptoSymmetricKey(HCRYPTPROV prov, XSECCryptoSymmetricKey::SymmetricKeyType type);
/**
* \brief Destructor
*
* Implementations must ensure that the held key is properly destroyed
* (overwritten) when key objects are deleted.
*/
virtual ~WinCAPICryptoSymmetricKey();
//@}
/** @name Basic CryptoKey Interface methods */
//@{
/**
* \brief Returns a string that identifies the crypto owner of this library.
*/
virtual const XMLCh * getProviderName();
/**
* \brief Clone the key
*
* All keys need to be able to copy themselves and return
* a pointer to the copy. This allows the library to
* duplicate keys.
*/
virtual XSECCryptoKey * clone();
//@}
/** @name Symmetric key interface methods */
//@{
/**
* \brief What type of symmetric key is this?
*
* There are a number of different types of symmetric key.
* This method allows callers to determine the type of this
* particular key
*/
SymmetricKeyType getSymmetricKeyType(void);
/**
* \brief Set the key from the provided bytes
*
* Symmetric keys can all be loaded from a buffer containing a series
* of bytes.
*
* @param key The buffer containing the key bytes
* @param keyLen The number of key bytes in the buffer
*
*/
void setKey(const unsigned char * key, unsigned int keyLen);
/**
* \brief Initialise an decryption process
*
* Setup the key to get ready for a decryption session.
* Callers can pass in an IV. If one is not provided,
* but the algorithm requires one (e.g. 3DES_CBC), then
* implementations should assume that the start of the
* cipher text stream will in fact be the IV.
*
* @param doPad By default, we perform padding for last block
* @param mode mode selection (Currently ECB or CBC mode only)
* @param iv Initialisation Vector to be used. NULL if one is
* not required, or if IV will be set from data stream
* @returns true if the initialisation succeeded.
*/
virtual bool decryptInit(bool doPad = true,
SymmetricKeyMode mode = MODE_CBC,
const unsigned char * iv = NULL);
/**
* \brief Continue an decrypt operation using this key.
*
* Decryption must have been set up using an encryptInit
* call. Takes the inBuf and continues a decryption operation,
* writing the output to outBuf.
*
* This function does not have to guarantee that all input
* will be decrypted. In cases where the input is not a length
* of the block size, the implementation will need to hold back
* cipher-text to be handles during the next operation.
*
* @note While maxOutLength is defined, the WinCAPI library will
* not read the value, so the onus is on the caller to ensure the
* buffer is long enough to hold the output!
*
* @param inBuf Octets to be decrypted
* @param plainBuf Buffer to place output in
* @param inLength Number of bytes to decrypt
* @param maxOutLength Maximum number of bytes to place in output
* buffer
* @returns Bytes placed in output Buffer
*/
virtual unsigned int decrypt(const unsigned char * inBuf,
unsigned char * plainBuf,
unsigned int inLength,
unsigned int maxOutLength);
/**
* \brief Finish a decryption operation
*
* Complete a decryption process. No cipher text is passed in,
* as this should simply be removing any remaining text from
* the plain storage buffer.
*
* May throw an exception if there is some stored cipher text
* that is not the length of the block size for block algorithms.
*
* @note While maxOutLength is defined, the WinCAPI library will
* not read the value, so the onus is on the caller to ensure the
* buffer is long enough to hold the output!
*
* @param plainBuf Buffer to place any remaining plain text in
* @param maxOutLength Maximum number of bytes to pace in output
* @returns Bytes placed in output buffer
*/
virtual unsigned int decryptFinish(unsigned char * plainBuf,
unsigned int maxOutLength);
/**
* \brief Initialise an encryption process
*
* Setup the key to get ready for a decryption session.
* Callers can pass in an IV. If one is not provided,
* but the algorithm requires one (e.g. 3DES_CBC), then
* implementations are required to generate one.
*
* @param doPad By default, we perform padding for last block
* @param mode What mode to handle blocks (Currently CBC or ECB)
* @param iv Initialisation Vector to be used. NULL if one is
* not required, or if IV is to be generated
* @returns true if the initialisation succeeded.
*/
virtual bool encryptInit(bool doPad = true,
SymmetricKeyMode mode = MODE_CBC,
const unsigned char * iv = NULL);
/**
* \brief Continue an encryption operation using this key.
*
* Encryption must have been set up using an encryptInit
* call. Takes the inBuf and continues a encryption operation,
* writing the output to outBuf.
*
* This function does not have to guarantee that all input
* will be encrypted. In cases where the input is not a length
* of the block size, the implementation will need to hold back
* plain-text to be handled during the next operation.
*
* @param inBuf Octets to be encrypted
* @param cipherBuf Buffer to place output in
* @param inLength Number of bytes to encrypt
* @param maxOutLength Maximum number of bytes to place in output
* buffer
* @returns Bytes placed in output Buffer
*/
virtual unsigned int encrypt(const unsigned char * inBuf,
unsigned char * cipherBuf,
unsigned int inLength,
unsigned int maxOutLength);
/**
* \brief Finish a encryption operation
*
* Complete a encryption process. No plain text is passed in,
* as this should simply be removing any remaining text from
* the plain storage buffer and creating a final padded block.
*
* Padding is performed by taking the remaining block, and
* setting the last byte to equal the number of bytes of
* padding. If the plain was an exact multiple of the block size,
* then an extra block of padding will be used. For example, if
* the block size is 8 bytes, and there were three remaining plain
* text bytes (0x01, 0x02 and 0x03), the final block will be :
*
* 0x010203????????05
*
* @param cipherBuf Buffer to place final block of cipher text in
* @param maxOutLength Maximum number of bytes to pace in output
* @returns Bytes placed in output buffer
*/
virtual unsigned int encryptFinish(unsigned char * plainBuf,
unsigned int maxOutLength);
//@}
/** @name Windows utility functions */
//@{
/**
* \brief Create a symmetric key from a octet string
*
* Uses the ApacheKeyStore to wrap an octet string in a public key
* and then load it into the Apache Key Container within the defined
* CSP
*
* @param key The buffer of bytes to load from
* @param keyLen The number of bytes to load
* @param type The key type to create from the bytes
* @param prov If NULL, ignored. If non-null, but *prov == 0, the
* function will use an internal handle to a CSP and return the value
* in *prov. If *prov != 0, use contents of *prov as the provider to
* load the key into. NOTE - The provider <em>must</em> have a
* AT_KEYEXCHANGE key pair available.
* @returns a pointer to the key or 0 on failure
*/
static HCRYPTKEY createWindowsKey(const unsigned char * key,
unsigned int keyLen,
XSECCryptoSymmetricKey::SymmetricKeyType type,
HCRYPTPROV * prov);
private:
// Unimplemented constructors
WinCAPICryptoSymmetricKey();
WinCAPICryptoSymmetricKey(const WinCAPICryptoSymmetricKey &);
WinCAPICryptoSymmetricKey & operator= (const WinCAPICryptoSymmetricKey &);
int decryptCtxInit(const unsigned char * iv);
void encryptCtxInit(const unsigned char * iv);
// Private variables
SymmetricKeyType m_keyType;
SymmetricKeyMode m_keyMode; // ECB or CBC
safeBuffer m_keyBuf; // Holder of the key
unsigned int m_keyLen;
bool m_initialised;
bool m_doPad;
unsigned char m_lastBlock[WINCAPI_MAX_BLOCK_SIZE];
unsigned int m_bytesInLastBlock;
unsigned int m_blockSize;
unsigned int m_ivSize;
HCRYPTPROV m_p;
HCRYPTKEY m_k;
};
#endif /* HAVE_WINCAPI */
#endif /* WINCAPICRYPTOSYMMETRICKEY_INCLUDE */
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/rendezvous_mgr.h"
#include <unordered_set>
#include "tensorflow/core/common_runtime/copy_tensor.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
IntraProcessRendezvous::IntraProcessRendezvous(const DeviceMgr* device_mgr)
: device_mgr_(device_mgr), local_(NewLocalRendezvous()) {}
IntraProcessRendezvous::~IntraProcessRendezvous() { local_->Unref(); }
Status IntraProcessRendezvous::Send(const ParsedKey& parsed,
const Rendezvous::Args& args,
const Tensor& val, const bool is_dead) {
VLOG(1) << "IntraProcessRendezvous Send " << this << " " << parsed.FullKey();
{
mutex_lock l(mu_);
if (!status_.ok()) return status_;
}
// Buffers "val" and "device_context" in local_.
return local_->Send(parsed, args, val, is_dead);
}
Status IntraProcessRendezvous::ParseKey(const string& key, bool is_src,
Rendezvous::ParsedKey* parsed) {
{
mutex_lock l(mu_);
if (!status_.ok()) return status_;
}
TF_RETURN_IF_ERROR(Rendezvous::ParseKey(key, parsed));
return Status::OK();
}
void IntraProcessRendezvous::SameWorkerRecvDone(
const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& in, Tensor* out,
StatusCallback done) {
// Do a quick copy (sharing the underlying buffer) if both tensors
// are on host memory.
const bool src_host =
(send_args.alloc_attrs.on_host() || parsed.src.type == "CPU");
const bool dst_host =
(recv_args.alloc_attrs.on_host() || parsed.dst.type == "CPU");
if (src_host && dst_host) {
*out = in;
done(Status::OK());
return;
}
// This copy must involve a non-CPU device. Hence, "in" must support DMA
// (e.g., string tensors do not work on GPU). Variant copy DMA
// checks happen inside CopyTensor::ViaDMA.
if (!DataTypeCanUseMemcpy(in.dtype()) && in.dtype() != DT_VARIANT) {
done(errors::InvalidArgument("Non-DMA-safe ", DataTypeString(in.dtype()),
" tensor may not be copied from/to a GPU."));
return;
}
Device* src_device;
Status s = device_mgr_->LookupDevice(parsed.src_device, &src_device);
if (!s.ok()) {
done(s);
return;
}
Device* dst_device;
s = device_mgr_->LookupDevice(parsed.dst_device, &dst_device);
if (!s.ok()) {
done(s);
return;
}
AllocatorAttributes attr = recv_args.alloc_attrs;
attr.set_gpu_compatible(send_args.alloc_attrs.gpu_compatible() ||
recv_args.alloc_attrs.gpu_compatible());
Allocator* out_allocator = dst_device->GetAllocator(attr);
if (in.dtype() != DT_VARIANT) {
// Variants are handled by CopyTensor::ViaDMA.
Tensor copy(out_allocator, in.dtype(), in.shape());
*out = copy;
}
CopyTensor::ViaDMA(parsed.edge_name, send_args.device_context,
recv_args.device_context, src_device, dst_device,
send_args.alloc_attrs, recv_args.alloc_attrs, &in, out,
std::move(done));
}
void IntraProcessRendezvous::RecvAsync(const ParsedKey& parsed,
const Rendezvous::Args& recv_args,
DoneCallback done) {
VLOG(1) << "IntraProcessRendezvous Recv " << this << " " << parsed.FullKey();
// Recv the tensor from local_.
local_->RecvAsync(
parsed, recv_args,
[this, parsed, done](
const Status& status, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& in, bool is_dead) {
// If "in" is an uninitialized tensor, do copy-construction to preserve
// the uninitialized state, along with data type and shape info, which
// is useful for debugger purposes.
Tensor* out = in.IsInitialized() ? new Tensor : new Tensor(in);
StatusCallback final_callback = [done, send_args, recv_args, out,
is_dead](const Status& s) {
done(s, send_args, recv_args, *out, is_dead);
delete out;
};
if (status.ok() && in.IsInitialized()) {
SameWorkerRecvDone(parsed, send_args, recv_args, in, out,
std::move(final_callback));
} else {
final_callback(status);
}
});
}
void IntraProcessRendezvous::StartAbort(const Status& s) {
CHECK(!s.ok());
local_->StartAbort(s);
}
} // end namespace tensorflow
<commit_msg>Move callback into bound function to avoid copying.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/rendezvous_mgr.h"
#include <unordered_set>
#include "tensorflow/core/common_runtime/copy_tensor.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
IntraProcessRendezvous::IntraProcessRendezvous(const DeviceMgr* device_mgr)
: device_mgr_(device_mgr), local_(NewLocalRendezvous()) {}
IntraProcessRendezvous::~IntraProcessRendezvous() { local_->Unref(); }
Status IntraProcessRendezvous::Send(const ParsedKey& parsed,
const Rendezvous::Args& args,
const Tensor& val, const bool is_dead) {
VLOG(1) << "IntraProcessRendezvous Send " << this << " " << parsed.FullKey();
{
mutex_lock l(mu_);
if (!status_.ok()) return status_;
}
// Buffers "val" and "device_context" in local_.
return local_->Send(parsed, args, val, is_dead);
}
Status IntraProcessRendezvous::ParseKey(const string& key, bool is_src,
Rendezvous::ParsedKey* parsed) {
{
mutex_lock l(mu_);
if (!status_.ok()) return status_;
}
TF_RETURN_IF_ERROR(Rendezvous::ParseKey(key, parsed));
return Status::OK();
}
void IntraProcessRendezvous::SameWorkerRecvDone(
const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& in, Tensor* out,
StatusCallback done) {
// Do a quick copy (sharing the underlying buffer) if both tensors
// are on host memory.
const bool src_host =
(send_args.alloc_attrs.on_host() || parsed.src.type == "CPU");
const bool dst_host =
(recv_args.alloc_attrs.on_host() || parsed.dst.type == "CPU");
if (src_host && dst_host) {
*out = in;
done(Status::OK());
return;
}
// This copy must involve a non-CPU device. Hence, "in" must support DMA
// (e.g., string tensors do not work on GPU). Variant copy DMA
// checks happen inside CopyTensor::ViaDMA.
if (!DataTypeCanUseMemcpy(in.dtype()) && in.dtype() != DT_VARIANT) {
done(errors::InvalidArgument("Non-DMA-safe ", DataTypeString(in.dtype()),
" tensor may not be copied from/to a GPU."));
return;
}
Device* src_device;
Status s = device_mgr_->LookupDevice(parsed.src_device, &src_device);
if (!s.ok()) {
done(s);
return;
}
Device* dst_device;
s = device_mgr_->LookupDevice(parsed.dst_device, &dst_device);
if (!s.ok()) {
done(s);
return;
}
AllocatorAttributes attr = recv_args.alloc_attrs;
attr.set_gpu_compatible(send_args.alloc_attrs.gpu_compatible() ||
recv_args.alloc_attrs.gpu_compatible());
Allocator* out_allocator = dst_device->GetAllocator(attr);
if (in.dtype() != DT_VARIANT) {
// Variants are handled by CopyTensor::ViaDMA.
Tensor copy(out_allocator, in.dtype(), in.shape());
*out = copy;
}
CopyTensor::ViaDMA(parsed.edge_name, send_args.device_context,
recv_args.device_context, src_device, dst_device,
send_args.alloc_attrs, recv_args.alloc_attrs, &in, out,
std::move(done));
}
void IntraProcessRendezvous::RecvAsync(const ParsedKey& parsed,
const Rendezvous::Args& recv_args,
DoneCallback done) {
VLOG(1) << "IntraProcessRendezvous Recv " << this << " " << parsed.FullKey();
// Recv the tensor from local_.
local_->RecvAsync(
parsed, recv_args,
std::bind(
[this, parsed](DoneCallback done,
// Begin unbound arguments.
const Status& status,
const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& in,
bool is_dead) {
// If "in" is an uninitialized tensor, do copy-construction to
// preserve the uninitialized state, along with data type and shape
// info, which is useful for debugger purposes.
Tensor* out = in.IsInitialized() ? new Tensor : new Tensor(in);
auto final_callback = std::bind(
[send_args, recv_args, out, is_dead](DoneCallback done,
// Begin unbound arguments.
const Status& s) {
done(s, send_args, recv_args, *out, is_dead);
delete out;
},
std::move(done), std::placeholders::_1);
if (status.ok() && in.IsInitialized()) {
SameWorkerRecvDone(parsed, send_args, recv_args, in, out,
std::move(final_callback));
} else {
final_callback(status);
}
},
std::move(done), std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
}
void IntraProcessRendezvous::StartAbort(const Status& s) {
CHECK(!s.ok());
local_->StartAbort(s);
}
} // end namespace tensorflow
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.