text stringlengths 54 60.6k |
|---|
<commit_before>/*
.L $ALICE_ROOT/TPC/Upgrade/macros/AnaEpsScan.C
AnaEpsScan();
*/
void AnaEpsScan(TString dir=".",TString baseFile="0.0_1_2_130_10")
{
TString files=gSystem->GetFromPipe( Form("ls %s/eps*/*%s*.root", dir.Data(), baseFile.Data() ) );
TObjArray *arr=files.Tokenize("\n");
TGraph *grFrac05=new TGraph;
TGraph *grFrac10=new TGraph;
grFrac05->SetNameTitle("grFrac05",";#varepsilon;fraction of tracks");
grFrac05->SetMarkerSize(1);
grFrac10->SetLineColor(kRed);
grFrac10->SetMarkerColor(kRed);
grFrac10->SetMarkerStyle(21);
grFrac10->SetMarkerSize(1);
Int_t colors[7]={kBlack, kRed, kBlue, kGreen, kMagenta, kCyan, kYellow};
Int_t markers[7]={20,21,22,23,24,25,26};
TObjArray arrHists;
for (Int_t ifile=0; ifile<arr->GetEntriesFast(); ++ifile) {
TString file=arr->At(ifile)->GetName();
TString epsilon=gSystem->GetFromPipe(Form("echo %s | sed 's|.*/eps\\([0-9][0-9]\\)/.*|\\1|'",file.Data()));
printf("%s: %s\n", file.Data(), epsilon.Data());
TH1F *h=new TH1F(Form("hResY30_%s",epsilon.Data()), Form("#varepsilon %d;fraction of clusters more than 3#sigma from track;#tracks", epsilon.Atoi()),100,0,1);
h->SetLineColor(colors[ifile]);
h->SetMarkerColor(colors[ifile]);
h->SetMarkerStyle(colors[ifile]);
arrHists.Add(h);
TFile f(file);
gROOT->cd();
TTree *t=(TTree*)f.Get("Tracks");
// Float_t clFracY30=0.;
// t->SetBranchStatus("*",0);
// t->SetBranchStatus("clFracY30",1);
// t->SetBranchAddress("clFracY30",&clFracY30);
t->Draw(Form("clFracY30>>hResY30_%s",epsilon.Data()),"","goff");
printf("entries: %d %d %d\n", grFrac05->GetN(), h->GetEntries(), t->GetEntries());
Double_t frac05 = h->Integral(h->FindBin(.05),h->GetNbinsX())/h->GetEntries();
Double_t frac10 = h->Integral(h->FindBin(.10),h->GetNbinsX())/h->GetEntries();
grFrac05->SetPoint(grFrac05->GetN(), epsilon.Atoi(), frac05);
grFrac10->SetPoint(grFrac10->GetN(), epsilon.Atoi(), frac10);
delete t;
f.Close();
}
TCanvas *c1=new TCanvas("c1");
c1->cd();
gPad->SetLogy();
TLegend *leg = new TLegend(.7,.3,.9,.9);
leg->SetBorderSize(1);
leg->SetFillColor(10);
for (Int_t ihist=0; ihist<arrHists.GetEntriesFast();++ihist) {
TH1F *h=(TH1F*)arrHists.At(ihist);
h->Draw((ihist==0)?"":"same");
leg->AddEntry(h,h->GetTitle(),"lp");
}
leg->Draw("same");
TCanvas *c2=new TCanvas("c2");
c2->cd();
TLegend *leg2 = new TLegend(.1,.7,.5,.9);
leg2->SetBorderSize(1);
leg2->SetFillColor(10);
grFrac05->Draw("alp");
grFrac10->Draw("lp");
leg2->AddEntry(grFrac05,"3#sigma deviation >5%","lp");
leg2->AddEntry(grFrac10,"3#sigma deviation >10%","lp");
leg2->Draw("same");
}
<commit_msg>o update macro<commit_after>/*
.L $ALICE_ROOT/TPC/Upgrade/macros/AnaEpsScan.C
AnaEpsScan();
*/
void AnaEpsScan(TString dir=".",TString baseFile="0.0_1_2_130_10", Float_t nSigmas=3.)
{
TString files=gSystem->GetFromPipe( Form("ls %s/eps*/*%s*.root", dir.Data(), baseFile.Data() ) );
TObjArray *arr=files.Tokenize("\n");
TGraph *grFrac01=new TGraph;
TGraph *grFrac05=new TGraph;
TGraph *grFrac10=new TGraph;
grFrac01->SetNameTitle("grFrac01",";#varepsilon;fraction of tracks");
grFrac01->SetMarkerStyle(20);
grFrac01->SetMarkerSize(1);
// grFrac05->SetNameTitle("grFrac05",";#varepsilon;fraction of tracks");
grFrac05->SetLineColor(kBlue);
grFrac05->SetMarkerColor(kBlue);
grFrac05->SetMarkerStyle(21);
grFrac05->SetMarkerSize(1);
grFrac10->SetLineColor(kRed);
grFrac10->SetMarkerColor(kRed);
grFrac10->SetMarkerStyle(22);
grFrac10->SetMarkerSize(1);
Int_t colors[7]={kBlack, kRed, kBlue, kGreen, kMagenta, kCyan, kYellow};
Int_t markers[7]={20,21,22,23,24,25,26};
TObjArray arrHists;
for (Int_t ifile=0; ifile<arr->GetEntriesFast(); ++ifile) {
TString file=arr->At(ifile)->GetName();
TString epsilon=gSystem->GetFromPipe(Form("echo %s | sed 's|.*/eps\\([0-9][0-9]\\)/.*|\\1|'",file.Data()));
printf("%s: %s\n", file.Data(), epsilon.Data());
TH1F *h=new TH1F(Form("hResY%.0f_%s",10*nSigmas, epsilon.Data()), Form("#varepsilon %d;fraction of clusters more than %.1f#sigma from track;#tracks", nSigmas, epsilon.Atoi()),1000,0,1);
h->SetLineColor(colors[ifile]);
h->SetMarkerColor(colors[ifile]);
h->SetMarkerStyle(colors[ifile]);
arrHists.Add(h);
TFile f(file);
gROOT->cd();
TTree *t=(TTree*)f.Get("Tracks");
// Float_t clFracY30=0.;
// t->SetBranchStatus("*",0);
// t->SetBranchStatus("clFracY30",1);
// t->SetBranchAddress("clFracY30",&clFracY30);
t->Draw(Form("clFracY%.0f>>hResY%.0f_%s",10*nSigmas,10*nSigmas,epsilon.Data()),"","goff");
printf("entries: %d %d %d\n", grFrac05->GetN(), h->GetEntries(), t->GetEntries());
Double_t frac01 = h->Integral(h->FindBin(.01),h->GetNbinsX())/h->GetEntries();
Double_t frac05 = h->Integral(h->FindBin(.05),h->GetNbinsX())/h->GetEntries();
Double_t frac10 = h->Integral(h->FindBin(.10),h->GetNbinsX())/h->GetEntries();
grFrac01->SetPoint(grFrac01->GetN(), epsilon.Atoi(), frac01);
grFrac05->SetPoint(grFrac05->GetN(), epsilon.Atoi(), frac05);
grFrac10->SetPoint(grFrac10->GetN(), epsilon.Atoi(), frac10);
delete t;
f.Close();
}
TCanvas *c1=new TCanvas("c1");
c1->cd();
gPad->SetLogy();
TLegend *leg = new TLegend(.7,.3,.9,.9);
leg->SetBorderSize(1);
leg->SetFillColor(10);
for (Int_t ihist=0; ihist<arrHists.GetEntriesFast();++ihist) {
TH1F *h=(TH1F*)arrHists.At(ihist);
h->Draw((ihist==0)?"":"same");
leg->AddEntry(h,h->GetTitle(),"lp");
}
leg->Draw("same");
c1->SaveAs(Form("~/tmp/epsScan_clFrac_%.0fsigma.png",10*nSigmas));
TCanvas *c2=new TCanvas("c2");
c2->cd();
TLegend *leg2 = new TLegend(.1,.7,.5,.9);
leg2->SetBorderSize(1);
leg2->SetFillColor(10);
TH1F *hDummy = new TH1F("hDummy",";#varepsilon;fraction of tracks",100,0,45);
hDummy->SetMinimum(0);
hDummy->SetMaximum(.5);
hDummy->Draw();
grFrac01->Draw("lp");
grFrac05->Draw("lp");
grFrac10->Draw("lp");
leg2->AddEntry(grFrac01,Form("%.1f#sigma deviation >1%%",nSigmas),"lp");
leg2->AddEntry(grFrac05,Form("%.1f#sigma deviation >5%%",nSigmas),"lp");
leg2->AddEntry(grFrac10,Form("%.1f#sigma deviation >10%%",nSigmas),"lp");
leg2->Draw("same");
c2->SaveAs(Form("~/tmp/epsScan_trFrac_eps_%.0fsigma.png",10*nSigmas));
}
<|endoftext|> |
<commit_before>/*
* pv.cpp
*
*/
#include "../PetaVision/src/columns/buildandrun.hpp"
#define MAIN_USES_CUSTOMGROUPS
#ifdef MAIN_USES_CUSTOMGROUPS
void * customgroup(const char * name, const char * groupname, HyPerCol * hc);
// customgroups is for adding objects not supported by build().
#endif // MAIN_USES_ADDCUSTOM
void * customgroup(const char * keyword, const char * name, HyPerCol * hc);
int main(int argc, char * argv[]) {
int status;
#ifdef MAIN_USES_CUSTOMGROUPS
status = buildandrun(argc, argv, NULL, NULL, &customgroup);
#else
status = buildandrun(argc, argv);
#endif // MAIN_USES_CUSTOMGROUPS
return status==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}
#ifdef MAIN_USES_CUSTOMGROUPS
void * customgroup(const char * keyword, const char * name, HyPerCol * hc) {
void * addedGroup = NULL;
return addedGroup;
}
#endif // MAIN_USES_CUSTOMGROUPS
<commit_msg>Deleting unnecessary declaration of customgroup (if MAIN_USES_CUSTOMGROUPS is defined, the line is a duplicate; if it is undefined, the line prototypes a function that isn't defined or called).<commit_after>/*
* pv.cpp
*
*/
#include "../PetaVision/src/columns/buildandrun.hpp"
#define MAIN_USES_CUSTOMGROUPS
#ifdef MAIN_USES_CUSTOMGROUPS
void * customgroup(const char * name, const char * groupname, HyPerCol * hc);
// customgroups is for adding objects not supported by build().
#endif // MAIN_USES_ADDCUSTOM
int main(int argc, char * argv[]) {
int status;
#ifdef MAIN_USES_CUSTOMGROUPS
status = buildandrun(argc, argv, NULL, NULL, &customgroup);
#else
status = buildandrun(argc, argv);
#endif // MAIN_USES_CUSTOMGROUPS
return status==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}
#ifdef MAIN_USES_CUSTOMGROUPS
void * customgroup(const char * keyword, const char * name, HyPerCol * hc) {
void * addedGroup = NULL;
return addedGroup;
}
#endif // MAIN_USES_CUSTOMGROUPS
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "ConnectionService.h"
#include "ConnectionAcceptor.h"
#include "Server.h"
#include "TcpSocket.h"
#include "Convert.h"
using namespace std;
using namespace db::modest;
using namespace db::net;
using namespace db::rt;
using namespace db::util;
// initialize server connections permits key
const char* ConnectionService::SERVER_CONNECTION_PERMITS_KEY =
"com.db.net.server.connections.permits";
ConnectionService::ConnectionService(
Server* server,
InternetAddress* address,
ConnectionServicer* servicer,
SocketDataPresenter* presenter) :
PortService(server, address), mRunningServicers(false)
{
mServicer = servicer;
mDataPresenter = presenter;
mSocket = NULL;
mMaxConnectionCount = 10000;
mConnectionCount = 0;
mConnectionPermitsKey =
"com.db.net.server.connections.ports." +
Convert::integerToString(getAddress()->getPort()) +
".permits";
}
ConnectionService::~ConnectionService()
{
// ensure service is stopped
ConnectionService::stop();
}
Operation* ConnectionService::initialize()
{
Operation* rval = NULL;
// no connections yet
mConnectionCount = 0;
// create tcp socket
mSocket = new TcpSocket();
// bind socket to the address and start listening
if(mSocket->bind(getAddress()) && mSocket->listen())
{
// create Operation for running service
rval = new Operation(this, this, this);
}
return rval;
}
void ConnectionService::cleanup()
{
if(mSocket != NULL)
{
// clean up socket
delete mSocket;
mSocket = NULL;
}
}
void ConnectionService::cleanupWorkers()
{
for(list<ConnectionWorker*>::iterator i = mWorkers.begin();
i != mWorkers.end();)
{
ConnectionWorker* cw = *i;
if(cw->getOperation()->stopped())
{
// remove the operation from the running servicers list
mRunningServicers.remove(cw->getOperation());
// delete the worker
delete cw;
i = mWorkers.erase(i);
}
else
{
i++;
}
}
}
bool ConnectionService::canExecuteOperation(ImmutableState* s)
{
bool rval = false;
// get permit counts for server and service
int serverPermits = mServer->getMaxConnectionCount();
int servicePermits = mMaxConnectionCount;
s->getInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits);
s->getInteger(mConnectionPermitsKey.c_str(), servicePermits);
// subtract current connection counts
serverPermits = (mServer->getConnectionCount() > serverPermits) ?
0 : serverPermits -= mServer->getConnectionCount();
servicePermits = (mConnectionCount > servicePermits) ?
0 : servicePermits -= mConnectionCount;
// can only execute if permits exist for both server and service
if(serverPermits > 0 && servicePermits > 0)
{
rval = true;
}
return rval;
}
bool ConnectionService::mustCancelOperation(ImmutableState* s)
{
// cancel accepting connections if server is no longer running
return !mServer->isRunning();
}
void ConnectionService::mutatePreExecutionState(State* s, Operation* op)
{
// get permit counts for server and service
int serverPermits = mServer->getMaxConnectionCount();
int servicePermits = mMaxConnectionCount;
s->getInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits);
s->getInteger(mConnectionPermitsKey.c_str(), servicePermits);
// decrement permits
s->setInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits - 1);
s->setInteger(mConnectionPermitsKey.c_str(), servicePermits - 1);
}
void ConnectionService::mutatePostExecutionState(State* s, Operation* op)
{
// get permit counts for server and service
int serverPermits = mServer->getMaxConnectionCount();
int servicePermits = mMaxConnectionCount;
s->getInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits);
s->getInteger(mConnectionPermitsKey.c_str(), servicePermits);
// increment permits
s->setInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits + 1);
s->setInteger(mConnectionPermitsKey.c_str(), servicePermits + 1);
}
void ConnectionService::run()
{
// create a connection acceptor
ConnectionAcceptor ca(mSocket, this);
while(!mOperation->isInterrupted())
{
// run accept operation
Operation op(&ca, this, this);
mServer->getKernel()->getEngine()->queue(&op);
// prune running servicers, clean up workers
mRunningServicers.prune();
cleanupWorkers();
// wait for operation to complete, do not allow interruptions
op.waitFor(false);
}
// close socket
mSocket->close();
// terminate running servicers, clean up workers
mRunningServicers.terminate();
cleanupWorkers();
}
void ConnectionService::createConnection(Socket* s)
{
// try to wrap Socket for standard data presentation
bool secure = false;
Socket* wrapper = s;
if(mDataPresenter != NULL)
{
wrapper = mDataPresenter->createPresentationWrapper(s, secure);
}
if(wrapper != NULL)
{
// create connection
Connection* c = new Connection(wrapper, true);
c->setSecure(secure);
// increase connection count
mServer->mConnectionCount++;
mConnectionCount++;
// create ConnectionWorker and Operation to run it
ConnectionWorker* worker = new ConnectionWorker(this, c);
Operation* op = new Operation(worker, NULL, NULL);
worker->setOperation(op);
mRunningServicers.add(op);
mWorkers.push_back(worker);
// queue operation for execution
mServer->getKernel()->getEngine()->queue(op);
}
else
{
// close socket, data cannot be presented in standard format
s->close();
delete s;
}
}
void ConnectionService::serviceConnection(Connection* c)
{
// service the connection
mServicer->serviceConnection(c);
// ensure connection is closed
c->close();
// decrease connection count
mServer->mConnectionCount--;
mConnectionCount--;
}
void ConnectionService::setMaxConnectionCount(unsigned int count)
{
mMaxConnectionCount = count;
}
unsigned int ConnectionService::getMaxConnectionCount()
{
return mMaxConnectionCount;
}
unsigned int ConnectionService::getConnectionCount()
{
return mConnectionCount;
}
<commit_msg>Removed accidental use of state mutator/operation guard where not applicable.<commit_after>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "ConnectionService.h"
#include "ConnectionAcceptor.h"
#include "Server.h"
#include "TcpSocket.h"
#include "Convert.h"
using namespace std;
using namespace db::modest;
using namespace db::net;
using namespace db::rt;
using namespace db::util;
// initialize server connections permits key
const char* ConnectionService::SERVER_CONNECTION_PERMITS_KEY =
"com.db.net.server.connections.permits";
ConnectionService::ConnectionService(
Server* server,
InternetAddress* address,
ConnectionServicer* servicer,
SocketDataPresenter* presenter) :
PortService(server, address), mRunningServicers(false)
{
mServicer = servicer;
mDataPresenter = presenter;
mSocket = NULL;
mMaxConnectionCount = 10000;
mConnectionCount = 0;
mConnectionPermitsKey =
"com.db.net.server.connections.ports." +
Convert::integerToString(getAddress()->getPort()) +
".permits";
}
ConnectionService::~ConnectionService()
{
// ensure service is stopped
ConnectionService::stop();
}
Operation* ConnectionService::initialize()
{
Operation* rval = NULL;
// no connections yet
mConnectionCount = 0;
// create tcp socket
mSocket = new TcpSocket();
// bind socket to the address and start listening
if(mSocket->bind(getAddress()) && mSocket->listen())
{
// create Operation for running service
rval = new Operation(this, NULL, NULL);
}
return rval;
}
void ConnectionService::cleanup()
{
if(mSocket != NULL)
{
// clean up socket
delete mSocket;
mSocket = NULL;
}
}
void ConnectionService::cleanupWorkers()
{
for(list<ConnectionWorker*>::iterator i = mWorkers.begin();
i != mWorkers.end();)
{
ConnectionWorker* cw = *i;
if(cw->getOperation()->stopped())
{
// remove the operation from the running servicers list
mRunningServicers.remove(cw->getOperation());
// delete the worker
delete cw;
i = mWorkers.erase(i);
}
else
{
i++;
}
}
}
bool ConnectionService::canExecuteOperation(ImmutableState* s)
{
bool rval = false;
// get permit counts for server and service
int serverPermits = mServer->getMaxConnectionCount();
int servicePermits = mMaxConnectionCount;
s->getInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits);
s->getInteger(mConnectionPermitsKey.c_str(), servicePermits);
// subtract current connection counts
serverPermits = (mServer->getConnectionCount() > serverPermits) ?
0 : serverPermits -= mServer->getConnectionCount();
servicePermits = (mConnectionCount > servicePermits) ?
0 : servicePermits -= mConnectionCount;
// can only execute if permits exist for both server and service
if(serverPermits > 0 && servicePermits > 0)
{
rval = true;
}
return rval;
}
bool ConnectionService::mustCancelOperation(ImmutableState* s)
{
// cancel accepting connections if server is no longer running
return !mServer->isRunning();
}
void ConnectionService::mutatePreExecutionState(State* s, Operation* op)
{
// get permit counts for server and service
int serverPermits = mServer->getMaxConnectionCount();
int servicePermits = mMaxConnectionCount;
s->getInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits);
s->getInteger(mConnectionPermitsKey.c_str(), servicePermits);
// decrement permits
s->setInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits - 1);
s->setInteger(mConnectionPermitsKey.c_str(), servicePermits - 1);
}
void ConnectionService::mutatePostExecutionState(State* s, Operation* op)
{
// get permit counts for server and service
int serverPermits = mServer->getMaxConnectionCount();
int servicePermits = mMaxConnectionCount;
s->getInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits);
s->getInteger(mConnectionPermitsKey.c_str(), servicePermits);
// increment permits
s->setInteger(SERVER_CONNECTION_PERMITS_KEY, serverPermits + 1);
s->setInteger(mConnectionPermitsKey.c_str(), servicePermits + 1);
}
void ConnectionService::run()
{
// create a connection acceptor
ConnectionAcceptor ca(mSocket, this);
while(!mOperation->isInterrupted())
{
// run accept operation
Operation op(&ca, this, this);
mServer->getKernel()->getEngine()->queue(&op);
// prune running servicers, clean up workers
mRunningServicers.prune();
cleanupWorkers();
// wait for operation to complete, do not allow interruptions
op.waitFor(false);
}
// close socket
mSocket->close();
// terminate running servicers, clean up workers
mRunningServicers.terminate();
cleanupWorkers();
}
void ConnectionService::createConnection(Socket* s)
{
// try to wrap Socket for standard data presentation
bool secure = false;
Socket* wrapper = s;
if(mDataPresenter != NULL)
{
wrapper = mDataPresenter->createPresentationWrapper(s, secure);
}
if(wrapper != NULL)
{
// create connection
Connection* c = new Connection(wrapper, true);
c->setSecure(secure);
// increase connection count
mServer->mConnectionCount++;
mConnectionCount++;
// create ConnectionWorker and Operation to run it
ConnectionWorker* worker = new ConnectionWorker(this, c);
Operation* op = new Operation(worker, NULL, NULL);
worker->setOperation(op);
mRunningServicers.add(op);
mWorkers.push_back(worker);
// queue operation for execution
mServer->getKernel()->getEngine()->queue(op);
}
else
{
// close socket, data cannot be presented in standard format
s->close();
delete s;
}
}
void ConnectionService::serviceConnection(Connection* c)
{
// service the connection
mServicer->serviceConnection(c);
// ensure connection is closed
c->close();
// decrease connection count
mServer->mConnectionCount--;
mConnectionCount--;
}
void ConnectionService::setMaxConnectionCount(unsigned int count)
{
mMaxConnectionCount = count;
}
unsigned int ConnectionService::getMaxConnectionCount()
{
return mMaxConnectionCount;
}
unsigned int ConnectionService::getConnectionCount()
{
return mConnectionCount;
}
<|endoftext|> |
<commit_before>void fit1() {
//Simple fitting example (1-d histogram with an interpreted function)
//To see the output of this macro, click begin_html <a href="gif/fit1.gif">here</a>. end_html
//Author: Rene Brun
TCanvas *c1 = new TCanvas("c1_fit1","The Fit Canvas",200,10,700,500);
c1->SetGridx();
c1->SetGridy();
c1->GetFrame()->SetFillColor(21);
c1->GetFrame()->SetBorderMode(-1);
c1->GetFrame()->SetBorderSize(5);
gBenchmark->Start("fit1");
//
// We connect the ROOT file generated in a previous tutorial
// (see begin_html <a href="fillrandom.C.html">Filling histograms with random numbers from a function</a>) end_html
//
TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
dir.ReplaceAll("fit1.C","");
dir.ReplaceAll("/./","/");
TFile *fill = TFile::Open("fillrandom.root");
if (!fill) {
gROOT->ProcessLine(Form(".x %s../hist/fillrandom.C",dir.Data()));
fill = TFile::Open("fillrandom.root");
if (!fill) return;
}
//
// The function "ls()" lists the directory contents of this file
//
fill->ls();
//
// Get object "sqroot" from the file.
//
TF1 *sqroot = static_cast<TF1*>(fill->GetObjectChecked("sqroot","TF1"));
if (!sqroot){
Error("","Cannot find object sqroot of type TF1\n");
return;
}
sqroot->Print();
//
// Now fit histogram h1f with the function sqroot
//
TH1F* h1f = static_cast<TH1F*>(fill->GetObjectChecked("h1f","TH1F"));
if (!h1f){
Error("","Cannot find object h1f of type TH1F\n");
return;
}
h1f->SetFillColor(45);
h1f->Fit("sqroot");
// We now annotate the picture by creating a PaveText object
// and displaying the list of commands in this macro
//
auto fitlabel = new TPaveText(0.6,0.3,0.9,0.80,"NDC");
fitlabel->SetTextAlign(12);
fitlabel->SetFillColor(42);
fitlabel->ReadFile(Form("%sfit1_C.C",dir.Data()));
fitlabel->Draw();
c1->Update();
gBenchmark->Show("fit1");
}
<commit_msg>Align the tutorial to the recommended way to get objects from TFiles<commit_after>void fit1() {
//Simple fitting example (1-d histogram with an interpreted function)
//To see the output of this macro, click begin_html <a href="gif/fit1.gif">here</a>. end_html
//Author: Rene Brun
TCanvas *c1 = new TCanvas("c1_fit1","The Fit Canvas",200,10,700,500);
c1->SetGridx();
c1->SetGridy();
c1->GetFrame()->SetFillColor(21);
c1->GetFrame()->SetBorderMode(-1);
c1->GetFrame()->SetBorderSize(5);
gBenchmark->Start("fit1");
//
// We connect the ROOT file generated in a previous tutorial
// (see begin_html <a href="fillrandom.C.html">Filling histograms with random numbers from a function</a>) end_html
//
TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
dir.ReplaceAll("fit1.C","");
dir.ReplaceAll("/./","/");
TFile *fill = TFile::Open("fillrandom.root");
if (!fill) {
gROOT->ProcessLine(Form(".x %s../hist/fillrandom.C",dir.Data()));
fill = TFile::Open("fillrandom.root");
if (!fill) return;
}
//
// The function "ls()" lists the directory contents of this file
//
fill->ls();
//
// Get object "sqroot" from the file.
//
TF1 *sqroot = nullptr;
fill->GetObject("sqroot",sqroot);
if (!sqroot){
Error("","Cannot find object sqroot of type TF1\n");
return;
}
sqroot->Print();
//
// Now fit histogram h1f with the function sqroot
//
TH1F* h1f = nullptr;
fill->GetObject("h1f",h1f);
if (!h1f){
Error("","Cannot find object h1f of type TH1F\n");
return;
}
h1f->SetFillColor(45);
h1f->Fit("sqroot");
// We now annotate the picture by creating a PaveText object
// and displaying the list of commands in this macro
//
auto fitlabel = new TPaveText(0.6,0.3,0.9,0.80,"NDC");
fitlabel->SetTextAlign(12);
fitlabel->SetFillColor(42);
fitlabel->ReadFile(Form("%sfit1_C.C",dir.Data()));
fitlabel->Draw();
c1->Update();
gBenchmark->Show("fit1");
}
<|endoftext|> |
<commit_before>// JSBsim.cxx -- interface to the JSBsim flight model
//
// Written by Curtis Olson, started February 1999.
//
// Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id: JSBSim.cxx,v 1.14 2000/05/15 12:37:00 jsb Exp $
#include <simgear/compiler.h>
#ifdef FG_MATH_EXCEPTION_CLASH
# include <math.h>
#endif
#include STL_STRING
#include <simgear/constants.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/math/fg_geodesy.hxx>
#include <simgear/misc/fgpath.hxx>
#include <Scenery/scenery.hxx>
#include <Aircraft/aircraft.hxx>
#include <Controls/controls.hxx>
#include <Main/options.hxx>
#include <FDM/JSBsim/FGFDMExec.h>
#include <FDM/JSBsim/FGAircraft.h>
#include <FDM/JSBsim/FGFCS.h>
#include <FDM/JSBsim/FGPosition.h>
#include <FDM/JSBsim/FGRotation.h>
#include <FDM/JSBsim/FGState.h>
#include <FDM/JSBsim/FGTranslation.h>
#include <FDM/JSBsim/FGAuxiliary.h>
#include <FDM/JSBsim/FGDefs.h>
#include <FDM/JSBsim/FGInitialCondition.h>
#include <FDM/JSBsim/FGTrimLong.h>
#include <FDM/JSBsim/FGAtmosphere.h>
#include "JSBsim.hxx"
double geocRwyRadius;
/******************************************************************************/
// Initialize the JSBsim flight model, dt is the time increment for
// each subsequent iteration through the EOM
int FGJSBsim::init( double dt ) {
FG_LOG( FG_FLIGHT, FG_INFO, "Starting and initializing JSBsim" );
FG_LOG( FG_FLIGHT, FG_INFO, " created FDMExec" );
FGPath aircraft_path( current_options.get_fg_root() );
aircraft_path.append( "Aircraft" );
FGPath engine_path( current_options.get_fg_root() );
engine_path.append( "Engine" );
FDMExec.GetState()->Setdt( dt );
FDMExec.GetAircraft()->LoadAircraft( aircraft_path.str(),
engine_path.str(),
current_options.get_aircraft() );
FG_LOG( FG_FLIGHT, FG_INFO, " loaded aircraft" <<
current_options.get_aircraft() );
FDMExec.GetAtmosphere()->UseInternal();
FG_LOG( FG_FLIGHT, FG_INFO, " Initializing JSBsim with:" );
FGInitialCondition *fgic = new FGInitialCondition(&FDMExec);
fgic->SetAltitudeFtIC(get_Altitude());
if((current_options.get_mach() < 0) && (current_options.get_vc() < 0 )) {
fgic->SetUBodyFpsIC(current_options.get_uBody());
fgic->SetVBodyFpsIC(current_options.get_vBody());
fgic->SetWBodyFpsIC(current_options.get_wBody());
FG_LOG(FG_FLIGHT,FG_INFO, " U,V,W= " << current_options.get_uBody()
<< ", " << current_options.get_vBody()
<< ", " << current_options.get_wBody());
} else if (current_options.get_vc() < 0) {
fgic->SetMachIC(current_options.get_mach());
FG_LOG(FG_FLIGHT,FG_INFO, " mach: " << current_options.get_mach() );
} else {
fgic->SetVcalibratedKtsIC(current_options.get_vc());
FG_LOG(FG_FLIGHT,FG_INFO, " vc: " << current_options.get_vc() );
//this should cover the case in which no speed switches are used
//current_options.get_vc() will return zero by default
}
fgic->SetRollAngleRadIC(get_Phi());
fgic->SetPitchAngleRadIC(get_Theta());
fgic->SetHeadingRadIC(get_Psi());
fgic->SetLatitudeRadIC(get_Latitude());
fgic->SetLongitudeRadIC(get_Longitude());
FDMExec.GetPosition()->SetRunwayRadius(geocRwyRadius);
FG_LOG( FG_FLIGHT, FG_INFO, " phi: " << get_Phi());
FG_LOG( FG_FLIGHT, FG_INFO, " theta: " << get_Theta() );
FG_LOG( FG_FLIGHT, FG_INFO, " psi: " << get_Psi() );
FG_LOG( FG_FLIGHT, FG_INFO, " lat: " << get_Latitude() );
FG_LOG( FG_FLIGHT, FG_INFO, " lon: " << get_Longitude() );
FG_LOG( FG_FLIGHT, FG_INFO, " alt: " << get_Altitude() );
if(current_options.get_trim_mode() == true) {
FG_LOG( FG_FLIGHT, FG_INFO, " Starting trim..." );
FGTrimLong *fgtrim=new FGTrimLong(&FDMExec,fgic);
fgtrim->DoTrim();
fgtrim->Report();
fgtrim->TrimStats();
fgtrim->ReportState();
controls.set_elevator(FDMExec.GetFCS()->GetDeCmd());
for(int i=0;i<FDMExec.GetAircraft()->GetNumEngines();i++) {
controls.set_throttle(i,FDMExec.GetFCS()->GetThrottleCmd(i)/100);
}
delete fgtrim;
FG_LOG( FG_FLIGHT, FG_INFO, " Trim complete." );
} else {
FG_LOG( FG_FLIGHT, FG_INFO, " Initializing without trim" );
FDMExec.GetState()->Initialize(fgic);
}
delete fgic;
FG_LOG( FG_FLIGHT, FG_INFO, " loaded initial conditions" );
FG_LOG( FG_FLIGHT, FG_INFO, " set dt" );
FG_LOG( FG_FLIGHT, FG_INFO, "Finished initializing JSBsim" );
copy_from_JSBsim();
return 1;
}
/******************************************************************************/
// Run an iteration of the EOM (equations of motion)
int FGJSBsim::update( int multiloop ) {
double save_alt = 0.0;
double time_step = (1.0 / current_options.get_model_hz()) * multiloop;
double start_elev = get_Altitude();
// lets try to avoid really screwing up the JSBsim model
if ( get_Altitude() < -9000 ) {
save_alt = get_Altitude();
set_Altitude( 0.0 );
}
// copy control positions into the JSBsim structure
FDMExec.GetFCS()->SetDaCmd( controls.get_aileron());
FDMExec.GetFCS()->SetDeCmd( controls.get_elevator()
+ controls.get_elevator_trim() );
FDMExec.GetFCS()->SetDrCmd( controls.get_rudder());
FDMExec.GetFCS()->SetDfCmd( 0.0 );
FDMExec.GetFCS()->SetDsbCmd( 0.0 );
FDMExec.GetFCS()->SetDspCmd( 0.0 );
FDMExec.GetFCS()->SetThrottleCmd( FGControls::ALL_ENGINES,
controls.get_throttle( 0 ) * 100.0 );
FDMExec.GetFCS()->SetThrottlePos( FGControls::ALL_ENGINES,
controls.get_throttle( 0 ) * 100.0 );
//FDMExec.GetFCS()->SetThrottlePos( FGControls::ALL_ENGINES,
// controls.get_throttle( 0 ) * 100.0 );
// FCS->SetBrake( controls.get_brake( 0 ) );
// Inform JSBsim of the local terrain altitude; uncommented 5/3/00
// FDMExec.GetPosition()->SetRunwayElevation(get_Runway_altitude()); // seems to work
FDMExec.GetPosition()->SetRunwayRadius(geocRwyRadius);
FDMExec.GetAtmosphere()->SetExTemperature(get_Static_temperature());
FDMExec.GetAtmosphere()->SetExPressure(get_Static_pressure());
FDMExec.GetAtmosphere()->SetExDensity(get_Density());
FDMExec.GetAtmosphere()->SetWindNED(get_V_north_airmass(),
get_V_east_airmass(),
get_V_down_airmass());
for ( int i = 0; i < multiloop; i++ ) {
FDMExec.Run();
}
// printf("%d FG_Altitude = %.2f\n", i, FG_Altitude * 0.3048);
// printf("%d Altitude = %.2f\n", i, Altitude * 0.3048);
// translate JSBsim back to FG structure so that the
// autopilot (and the rest of the sim can use the updated values
copy_from_JSBsim();
// but lets restore our original bogus altitude when we are done
if ( save_alt < -9000.0 ) {
set_Altitude( save_alt );
}
double end_elev = get_Altitude();
if ( time_step > 0.0 ) {
// feet per second
set_Climb_Rate( (end_elev - start_elev) / time_step );
}
return 1;
}
/******************************************************************************/
// Convert from the FGInterface struct to the JSBsim generic_ struct
int FGJSBsim::copy_to_JSBsim() {
return 1;
}
/******************************************************************************/
// Convert from the JSBsim generic_ struct to the FGInterface struct
int FGJSBsim::copy_from_JSBsim() {
// Velocities
set_Velocities_Local( FDMExec.GetPosition()->GetVn(),
FDMExec.GetPosition()->GetVe(),
FDMExec.GetPosition()->GetVd() );
set_V_equiv_kts( FDMExec.GetAuxiliary()->GetVequivalentKTS() );
//set_V_calibrated( FDMExec.GetAuxiliary()->GetVcalibratedFPS() );
set_V_calibrated_kts( FDMExec.GetAuxiliary()->GetVcalibratedKTS() );
set_Omega_Body( FDMExec.GetState()->GetParameter(FG_ROLLRATE),
FDMExec.GetState()->GetParameter(FG_PITCHRATE),
FDMExec.GetState()->GetParameter(FG_YAWRATE) );
set_Euler_Rates( FDMExec.GetRotation()->Getphi(),
FDMExec.GetRotation()->Gettht(),
FDMExec.GetRotation()->Getpsi() );
// ***FIXME*** set_Geocentric_Rates( Latitude_dot, Longitude_dot, Radius_dot );
set_Mach_number( FDMExec.GetTranslation()->GetMach());
// Positions
double lat_geoc = FDMExec.GetPosition()->GetLatitude();
double lon = FDMExec.GetPosition()->GetLongitude();
double alt = FDMExec.GetPosition()->Geth();
double lat_geod, tmp_alt, sl_radius1, sl_radius2, tmp_lat_geoc;
fgGeocToGeod( lat_geoc, EQUATORIAL_RADIUS_M + alt * FEET_TO_METER,
&lat_geod, &tmp_alt, &sl_radius1 );
fgGeodToGeoc( lat_geod, alt * FEET_TO_METER, &sl_radius2, &tmp_lat_geoc );
FG_LOG( FG_FLIGHT, FG_DEBUG, "lon = " << lon << " lat_geod = " << lat_geod
<< " lat_geoc = " << lat_geoc
<< " alt = " << alt << " tmp_alt = " << tmp_alt * METER_TO_FEET
<< " sl_radius1 = " << sl_radius1 * METER_TO_FEET
<< " sl_radius2 = " << sl_radius2 * METER_TO_FEET
<< " Equator = " << EQUATORIAL_RADIUS_FT );
set_Geocentric_Position( lat_geoc, lon,
sl_radius2 * METER_TO_FEET + alt );
set_Geodetic_Position( lat_geod, lon, alt );
set_Euler_Angles( FDMExec.GetRotation()->Getphi(),
FDMExec.GetRotation()->Gettht(),
FDMExec.GetRotation()->Getpsi() );
set_Alpha( FDMExec.GetTranslation()->Getalpha() );
set_Beta( FDMExec.GetTranslation()->Getbeta() );
set_Gamma_vert_rad( FDMExec.GetPosition()->GetGamma() );
// set_Gamma_horiz_rad( Gamma_horiz_rad );
/* **FIXME*** */
set_Sea_level_radius( sl_radius2 * METER_TO_FEET );
/* **FIXME*** */
set_Earth_position_angle( 0.0 );
// /* ***FIXME*** */ set_Runway_altitude( 0.0 );
set_sin_lat_geocentric( lat_geoc );
set_cos_lat_geocentric( lat_geoc );
set_sin_cos_longitude( lon );
set_sin_cos_latitude( lat_geod );
return 1;
}
/******************************************************************************/
<commit_msg>Updates to set FG trimmed throttle and elevator trim<commit_after>// JSBsim.cxx -- interface to the JSBsim flight model
//
// Written by Curtis Olson, started February 1999.
//
// Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id: JSBSim.cxx,v 1.15 2000/05/16 10:19:18 jsb Exp $
#include <simgear/compiler.h>
#ifdef FG_MATH_EXCEPTION_CLASH
# include <math.h>
#endif
#include STL_STRING
#include <simgear/constants.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/math/fg_geodesy.hxx>
#include <simgear/misc/fgpath.hxx>
#include <Scenery/scenery.hxx>
#include <Aircraft/aircraft.hxx>
#include <Controls/controls.hxx>
#include <Main/options.hxx>
#include <FDM/JSBsim/FGFDMExec.h>
#include <FDM/JSBsim/FGAircraft.h>
#include <FDM/JSBsim/FGFCS.h>
#include <FDM/JSBsim/FGPosition.h>
#include <FDM/JSBsim/FGRotation.h>
#include <FDM/JSBsim/FGState.h>
#include <FDM/JSBsim/FGTranslation.h>
#include <FDM/JSBsim/FGAuxiliary.h>
#include <FDM/JSBsim/FGDefs.h>
#include <FDM/JSBsim/FGInitialCondition.h>
#include <FDM/JSBsim/FGTrimLong.h>
#include <FDM/JSBsim/FGAtmosphere.h>
#include "JSBsim.hxx"
double geocRwyRadius;
/******************************************************************************/
// Initialize the JSBsim flight model, dt is the time increment for
// each subsequent iteration through the EOM
int FGJSBsim::init( double dt ) {
FG_LOG( FG_FLIGHT, FG_INFO, "Starting and initializing JSBsim" );
FG_LOG( FG_FLIGHT, FG_INFO, " created FDMExec" );
FGPath aircraft_path( current_options.get_fg_root() );
aircraft_path.append( "Aircraft" );
FGPath engine_path( current_options.get_fg_root() );
engine_path.append( "Engine" );
FDMExec.GetState()->Setdt( dt );
FDMExec.GetAircraft()->LoadAircraft( aircraft_path.str(),
engine_path.str(),
current_options.get_aircraft() );
FG_LOG( FG_FLIGHT, FG_INFO, " loaded aircraft" <<
current_options.get_aircraft() );
FDMExec.GetAtmosphere()->UseInternal();
FG_LOG( FG_FLIGHT, FG_INFO, " Initializing JSBsim with:" );
FGInitialCondition *fgic = new FGInitialCondition(&FDMExec);
fgic->SetAltitudeFtIC(get_Altitude());
if((current_options.get_mach() < 0) && (current_options.get_vc() < 0 )) {
fgic->SetUBodyFpsIC(current_options.get_uBody());
fgic->SetVBodyFpsIC(current_options.get_vBody());
fgic->SetWBodyFpsIC(current_options.get_wBody());
FG_LOG(FG_FLIGHT,FG_INFO, " u,v,w= " << current_options.get_uBody()
<< ", " << current_options.get_vBody()
<< ", " << current_options.get_wBody());
} else if (current_options.get_vc() < 0) {
fgic->SetMachIC(current_options.get_mach());
FG_LOG(FG_FLIGHT,FG_INFO, " mach: " << current_options.get_mach() );
} else {
fgic->SetVcalibratedKtsIC(current_options.get_vc());
FG_LOG(FG_FLIGHT,FG_INFO, " vc: " << current_options.get_vc() );
//this should cover the case in which no speed switches are used
//current_options.get_vc() will return zero by default
}
fgic->SetRollAngleRadIC(get_Phi());
fgic->SetPitchAngleRadIC(get_Theta());
fgic->SetHeadingRadIC(get_Psi());
fgic->SetLatitudeRadIC(get_Latitude());
fgic->SetLongitudeRadIC(get_Longitude());
FDMExec.GetPosition()->SetRunwayRadius(geocRwyRadius);
FG_LOG( FG_FLIGHT, FG_INFO, " phi: " << get_Phi());
FG_LOG( FG_FLIGHT, FG_INFO, " theta: " << get_Theta() );
FG_LOG( FG_FLIGHT, FG_INFO, " psi: " << get_Psi() );
FG_LOG( FG_FLIGHT, FG_INFO, " lat: " << get_Latitude() );
FG_LOG( FG_FLIGHT, FG_INFO, " lon: " << get_Longitude() );
FG_LOG( FG_FLIGHT, FG_INFO, " alt: " << get_Altitude() );
if(current_options.get_trim_mode() == true) {
FG_LOG( FG_FLIGHT, FG_INFO, " Starting trim..." );
FGTrimLong *fgtrim=new FGTrimLong(&FDMExec,fgic);
fgtrim->DoTrim();
fgtrim->Report();
fgtrim->TrimStats();
fgtrim->ReportState();
controls.set_elevator_trim(FDMExec.GetFCS()->GetDeCmd());
controls.set_trimmed_throttle(FGControls::ALL_ENGINES,GetThrottleCmd(0)/100);
//the trimming routine only knows how to get 1 value for throttle
//for(int i=0;i<FDMExec.GetAircraft()->GetNumEngines();i++) {
// controls.set_throttle(i,FDMExec.GetFCS()->GetThrottleCmd(i)/100);
//}
delete fgtrim;
FG_LOG( FG_FLIGHT, FG_INFO, " Trim complete." );
} else {
FG_LOG( FG_FLIGHT, FG_INFO, " Initializing without trim" );
FDMExec.GetState()->Initialize(fgic);
}
delete fgic;
FG_LOG( FG_FLIGHT, FG_INFO, " loaded initial conditions" );
FG_LOG( FG_FLIGHT, FG_INFO, " set dt" );
FG_LOG( FG_FLIGHT, FG_INFO, "Finished initializing JSBsim" );
copy_from_JSBsim();
return 1;
}
/******************************************************************************/
// Run an iteration of the EOM (equations of motion)
int FGJSBsim::update( int multiloop ) {
double save_alt = 0.0;
double time_step = (1.0 / current_options.get_model_hz()) * multiloop;
double start_elev = get_Altitude();
// lets try to avoid really screwing up the JSBsim model
if ( get_Altitude() < -9000 ) {
save_alt = get_Altitude();
set_Altitude( 0.0 );
}
// copy control positions into the JSBsim structure
FDMExec.GetFCS()->SetDaCmd( controls.get_aileron());
FDMExec.GetFCS()->SetDeCmd( controls.get_elevator());
FDMExec.GetFCS()->SetPitchTrimCmd(controls.get_elevator_trim());
FDMExec.GetFCS()->SetDrCmd( controls.get_rudder());
FDMExec.GetFCS()->SetDfCmd( controls.get_flaps() );
FDMExec.GetFCS()->SetDsbCmd( 0.0 );
FDMExec.GetFCS()->SetDspCmd( 0.0 );
FDMExec.GetFCS()->SetThrottleCmd( FGControls::ALL_ENGINES,
controls.get_throttle( 0 ) * 100.0 );
// FCS->SetBrake( controls.get_brake( 0 ) );
// Inform JSBsim of the local terrain altitude; uncommented 5/3/00
// FDMExec.GetPosition()->SetRunwayElevation(get_Runway_altitude()); // seems to work
FDMExec.GetPosition()->SetRunwayRadius(geocRwyRadius);
FDMExec.GetAtmosphere()->SetExTemperature(get_Static_temperature());
FDMExec.GetAtmosphere()->SetExPressure(get_Static_pressure());
FDMExec.GetAtmosphere()->SetExDensity(get_Density());
FDMExec.GetAtmosphere()->SetWindNED(get_V_north_airmass(),
get_V_east_airmass(),
get_V_down_airmass());
for ( int i = 0; i < multiloop; i++ ) {
FDMExec.Run();
}
// printf("%d FG_Altitude = %.2f\n", i, FG_Altitude * 0.3048);
// printf("%d Altitude = %.2f\n", i, Altitude * 0.3048);
// translate JSBsim back to FG structure so that the
// autopilot (and the rest of the sim can use the updated values
copy_from_JSBsim();
// but lets restore our original bogus altitude when we are done
if ( save_alt < -9000.0 ) {
set_Altitude( save_alt );
}
double end_elev = get_Altitude();
if ( time_step > 0.0 ) {
// feet per second
set_Climb_Rate( (end_elev - start_elev) / time_step );
}
return 1;
}
/******************************************************************************/
// Convert from the FGInterface struct to the JSBsim generic_ struct
int FGJSBsim::copy_to_JSBsim() {
return 1;
}
/******************************************************************************/
// Convert from the JSBsim generic_ struct to the FGInterface struct
int FGJSBsim::copy_from_JSBsim() {
// Velocities
set_Velocities_Local( FDMExec.GetPosition()->GetVn(),
FDMExec.GetPosition()->GetVe(),
FDMExec.GetPosition()->GetVd() );
set_V_equiv_kts( FDMExec.GetAuxiliary()->GetVequivalentKTS() );
//set_V_calibrated( FDMExec.GetAuxiliary()->GetVcalibratedFPS() );
set_V_calibrated_kts( FDMExec.GetAuxiliary()->GetVcalibratedKTS() );
set_Omega_Body( FDMExec.GetState()->GetParameter(FG_ROLLRATE),
FDMExec.GetState()->GetParameter(FG_PITCHRATE),
FDMExec.GetState()->GetParameter(FG_YAWRATE) );
set_Euler_Rates( FDMExec.GetRotation()->Getphi(),
FDMExec.GetRotation()->Gettht(),
FDMExec.GetRotation()->Getpsi() );
// ***FIXME*** set_Geocentric_Rates( Latitude_dot, Longitude_dot, Radius_dot );
set_Mach_number( FDMExec.GetTranslation()->GetMach());
// Positions
double lat_geoc = FDMExec.GetPosition()->GetLatitude();
double lon = FDMExec.GetPosition()->GetLongitude();
double alt = FDMExec.GetPosition()->Geth();
double lat_geod, tmp_alt, sl_radius1, sl_radius2, tmp_lat_geoc;
fgGeocToGeod( lat_geoc, EQUATORIAL_RADIUS_M + alt * FEET_TO_METER,
&lat_geod, &tmp_alt, &sl_radius1 );
fgGeodToGeoc( lat_geod, alt * FEET_TO_METER, &sl_radius2, &tmp_lat_geoc );
FG_LOG( FG_FLIGHT, FG_DEBUG, "lon = " << lon << " lat_geod = " << lat_geod
<< " lat_geoc = " << lat_geoc
<< " alt = " << alt << " tmp_alt = " << tmp_alt * METER_TO_FEET
<< " sl_radius1 = " << sl_radius1 * METER_TO_FEET
<< " sl_radius2 = " << sl_radius2 * METER_TO_FEET
<< " Equator = " << EQUATORIAL_RADIUS_FT );
set_Geocentric_Position( lat_geoc, lon,
sl_radius2 * METER_TO_FEET + alt );
set_Geodetic_Position( lat_geod, lon, alt );
set_Euler_Angles( FDMExec.GetRotation()->Getphi(),
FDMExec.GetRotation()->Gettht(),
FDMExec.GetRotation()->Getpsi() );
set_Alpha( FDMExec.GetTranslation()->Getalpha() );
set_Beta( FDMExec.GetTranslation()->Getbeta() );
set_Gamma_vert_rad( FDMExec.GetPosition()->GetGamma() );
// set_Gamma_horiz_rad( Gamma_horiz_rad );
/* **FIXME*** */ set_Sea_level_radius( sl_radius2 * METER_TO_FEET );
/* **FIXME*** */ set_Earth_position_angle( 0.0 );
// /* ***FIXME*** */ set_Runway_altitude( 0.0 );
set_sin_lat_geocentric( lat_geoc );
set_cos_lat_geocentric( lat_geoc );
set_sin_cos_longitude( lon );
set_sin_cos_latitude( lat_geod );
return 1;
}
/******************************************************************************/
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Header: JSBSim.hxx
Author: Curtis L. Olson
Maintained by: Tony Peden, Curt Olson
Date started: 02/01/1999
------ Copyright (C) 1999 - 2000 Curtis L. Olson (curt@flightgear.org) ------
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
HISTORY
--------------------------------------------------------------------------------
02/01/1999 CLO Created
Additional log messages stored in CVS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SENTRY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef _JSBSIM_HXX
#define _JSBSIM_HXX
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#undef MAX_ENGINES
#include <Aircraft/aircraft.hxx>
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DEFINITIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#define ID_JSBSIMXX "$Header JSBSim.hxx,v 1.4 2000/10/22 14:02:16 jsb Exp $"
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FORWARD DECLARATIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
class FGState;
class FGAtmosphere;
class FGFCS;
class FGPropulsion;
class FGMassBalance;
class FGAerodynamics;
class FGInertial;
class FGAircraft;
class FGTranslation;
class FGRotation;
class FGPosition;
class FGAuxiliary;
class FGOutput;
class FGInitialCondition;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES [use "class documentation" below for API docs]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DOCUMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/** FGFS / JSBSim interface (aka "The Bus").
This class provides for an interface between FlightGear and its data
structures and JSBSim and its data structures. This is the class which is
used to command JSBSim when integrated with FlightGear. See the
documentation for main for direction on running JSBSim apart from FlightGear.
@author Curtis L. Olson (original)
@author Tony Peden (Maintained and refined)
@version $Id: JSBSim.hxx,v 1.17 2001/06/05 19:00:39 jberndt Exp $
@see main in file JSBSim.cpp (use main() wrapper for standalone usage)
*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DECLARATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
class FGJSBsim: public FGInterface {
public:
/// Constructor
FGJSBsim::FGJSBsim( double dt );
/// Destructor
FGJSBsim::~FGJSBsim();
/// copy FDM state to LaRCsim structures
bool copy_to_JSBsim();
/// copy FDM state from LaRCsim structures
bool copy_from_JSBsim();
/// Reset flight params to a specific position
void init();
/// @name Position Parameter Set
//@{
/** Set geocentric latitude
@param lat latitude in radians measured from the 0 meridian where
the westerly direction is positive and east is negative */
void set_Latitude(double lat); // geocentric
/** Set longitude
@param lon longitude in radians measured from the equator where
the northerly direction is positive and south is negative */
void set_Longitude(double lon);
/** Set altitude
Note: this triggers a recalculation of AGL altitude
@param alt altitude in feet */
void set_Altitude(double alt); // triggers re-calc of AGL altitude
//@}
//void set_AltitudeAGL(double altagl); // and vice-versa
/// @name Velocity Parameter Set
//@{
/** Sets calibrated airspeed
Setting this will trigger a recalc of the other velocity terms.
@param vc Calibrated airspeed in ft/sec */
void set_V_calibrated_kts(double vc);
/** Sets Mach number.
Setting this will trigger a recalc of the other velocity terms.
@param mach Mach number */
void set_Mach_number(double mach);
/** Sets velocity in N-E-D coordinates.
Setting this will trigger a recalc of the other velocity terms.
@param north velocity northward in ft/sec
@param east velocity eastward in ft/sec
@param down velocity downward in ft/sec */
void set_Velocities_Local( double north, double east, double down );
/** Sets aircraft velocity in stability frame.
Setting this will trigger a recalc of the other velocity terms.
@param u X velocity in ft/sec
@param v Y velocity in ft/sec
@param w Z velocity in ft/sec */
void set_Velocities_Wind_Body( double u, double v, double w);
//@}
/** Euler Angle Parameter Set
@param phi roll angle in radians
@param theta pitch angle in radians
@param psi heading angle in radians */
void set_Euler_Angles( double phi, double theta, double psi );
/// @name Flight Path Parameter Set
//@{
/** Sets rate of climb
@param roc Rate of climb in ft/sec */
void set_Climb_Rate( double roc);
/** Sets the flight path angle in radians
@param gamma flight path angle in radians. */
void set_Gamma_vert_rad( double gamma);
//@}
/// @name Earth Parameter Set
//@{
/** Sets the sea level radius in feet.
@param slr Sea Level Radius in feet */
void set_Sea_level_radius(double slr);
/** Sets the runway altitude in feet above sea level.
@param ralt Runway altitude in feet above sea level. */
void set_Runway_altitude(double ralt);
//@}
/// @name Atmospheric Parameter Set
//@{
/** Sets the atmospheric static pressure
@param p pressure in psf */
void set_Static_pressure(double p);
/** Sets the atmospheric temperature
@param T temperature in degrees rankine */
void set_Static_temperature(double T);
/** Sets the atmospheric density.
@param rho air density slugs/cubic foot */
void set_Density(double rho);
/** Sets the velocity of the local airmass for wind modeling.
@param wnorth velocity north in fps
@param weast velocity east in fps
@param wdown velocity down in fps*/
void set_Velocities_Local_Airmass (double wnorth,
double weast,
double wdown );
//@}
/** Update the position based on inputs, positions, velocities, etc.
@param multiloop number of times to loop through the FDM
@return true if successful */
bool update( int multiloop );
bool ToggleDataLogging(bool state);
bool ToggleDataLogging(void);
private:
FGFDMExec *fdmex;
FGInitialCondition *fgic;
bool needTrim;
FGState* State;
FGAtmosphere* Atmosphere;
FGFCS* FCS;
FGPropulsion* Propulsion;
FGMassBalance* MassBalance;
FGAircraft* Aircraft;
FGTranslation* Translation;
FGRotation* Rotation;
FGPosition* Position;
FGAuxiliary* Auxiliary;
FGAerodynamics* Aerodynamics;
int runcount;
float trim_elev;
float trim_throttle;
SGValue *trimmed;
void snap_shot(void);
};
#endif // _JSBSIM_HXX
<commit_msg>More fixes to compile under FGFS<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Header: JSBSim.hxx
Author: Curtis L. Olson
Maintained by: Tony Peden, Curt Olson
Date started: 02/01/1999
------ Copyright (C) 1999 - 2000 Curtis L. Olson (curt@flightgear.org) ------
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
HISTORY
--------------------------------------------------------------------------------
02/01/1999 CLO Created
Additional log messages stored in CVS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SENTRY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef _JSBSIM_HXX
#define _JSBSIM_HXX
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#undef MAX_ENGINES
#include <Aircraft/aircraft.hxx>
#include "FDM/JSBSim/FGDefs.h"
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DEFINITIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#define ID_JSBSIMXX "$Header JSBSim.hxx,v 1.4 2000/10/22 14:02:16 jsb Exp $"
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FORWARD DECLARATIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
class FGState;
class FGAtmosphere;
class FGFCS;
class FGPropulsion;
class FGMassBalance;
class FGAerodynamics;
class FGInertial;
class FGAircraft;
class FGTranslation;
class FGRotation;
class FGPosition;
class FGAuxiliary;
class FGOutput;
class FGInitialCondition;
class FGFDMExec;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES [use "class documentation" below for API docs]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DOCUMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/** FGFS / JSBSim interface (aka "The Bus").
This class provides for an interface between FlightGear and its data
structures and JSBSim and its data structures. This is the class which is
used to command JSBSim when integrated with FlightGear. See the
documentation for main for direction on running JSBSim apart from FlightGear.
@author Curtis L. Olson (original)
@author Tony Peden (Maintained and refined)
@version $Id: JSBSim.hxx,v 1.18 2001/06/05 19:20:44 jberndt Exp $
@see main in file JSBSim.cpp (use main() wrapper for standalone usage)
*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DECLARATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
class FGJSBsim: public FGInterface {
public:
/// Constructor
FGJSBsim::FGJSBsim( double dt );
/// Destructor
FGJSBsim::~FGJSBsim();
/// copy FDM state to LaRCsim structures
bool copy_to_JSBsim();
/// copy FDM state from LaRCsim structures
bool copy_from_JSBsim();
/// Reset flight params to a specific position
void init();
/// @name Position Parameter Set
//@{
/** Set geocentric latitude
@param lat latitude in radians measured from the 0 meridian where
the westerly direction is positive and east is negative */
void set_Latitude(double lat); // geocentric
/** Set longitude
@param lon longitude in radians measured from the equator where
the northerly direction is positive and south is negative */
void set_Longitude(double lon);
/** Set altitude
Note: this triggers a recalculation of AGL altitude
@param alt altitude in feet */
void set_Altitude(double alt); // triggers re-calc of AGL altitude
//@}
//void set_AltitudeAGL(double altagl); // and vice-versa
/// @name Velocity Parameter Set
//@{
/** Sets calibrated airspeed
Setting this will trigger a recalc of the other velocity terms.
@param vc Calibrated airspeed in ft/sec */
void set_V_calibrated_kts(double vc);
/** Sets Mach number.
Setting this will trigger a recalc of the other velocity terms.
@param mach Mach number */
void set_Mach_number(double mach);
/** Sets velocity in N-E-D coordinates.
Setting this will trigger a recalc of the other velocity terms.
@param north velocity northward in ft/sec
@param east velocity eastward in ft/sec
@param down velocity downward in ft/sec */
void set_Velocities_Local( double north, double east, double down );
/** Sets aircraft velocity in stability frame.
Setting this will trigger a recalc of the other velocity terms.
@param u X velocity in ft/sec
@param v Y velocity in ft/sec
@param w Z velocity in ft/sec */
void set_Velocities_Wind_Body( double u, double v, double w);
//@}
/** Euler Angle Parameter Set
@param phi roll angle in radians
@param theta pitch angle in radians
@param psi heading angle in radians */
void set_Euler_Angles( double phi, double theta, double psi );
/// @name Flight Path Parameter Set
//@{
/** Sets rate of climb
@param roc Rate of climb in ft/sec */
void set_Climb_Rate( double roc);
/** Sets the flight path angle in radians
@param gamma flight path angle in radians. */
void set_Gamma_vert_rad( double gamma);
//@}
/// @name Earth Parameter Set
//@{
/** Sets the sea level radius in feet.
@param slr Sea Level Radius in feet */
void set_Sea_level_radius(double slr);
/** Sets the runway altitude in feet above sea level.
@param ralt Runway altitude in feet above sea level. */
void set_Runway_altitude(double ralt);
//@}
/// @name Atmospheric Parameter Set
//@{
/** Sets the atmospheric static pressure
@param p pressure in psf */
void set_Static_pressure(double p);
/** Sets the atmospheric temperature
@param T temperature in degrees rankine */
void set_Static_temperature(double T);
/** Sets the atmospheric density.
@param rho air density slugs/cubic foot */
void set_Density(double rho);
/** Sets the velocity of the local airmass for wind modeling.
@param wnorth velocity north in fps
@param weast velocity east in fps
@param wdown velocity down in fps*/
void set_Velocities_Local_Airmass (double wnorth,
double weast,
double wdown );
//@}
/** Update the position based on inputs, positions, velocities, etc.
@param multiloop number of times to loop through the FDM
@return true if successful */
bool update( int multiloop );
bool ToggleDataLogging(bool state);
bool ToggleDataLogging(void);
private:
FGFDMExec *fdmex;
FGInitialCondition *fgic;
bool needTrim;
FGState* State;
FGAtmosphere* Atmosphere;
FGFCS* FCS;
FGPropulsion* Propulsion;
FGMassBalance* MassBalance;
FGAircraft* Aircraft;
FGTranslation* Translation;
FGRotation* Rotation;
FGPosition* Position;
FGAuxiliary* Auxiliary;
FGAerodynamics* Aerodynamics;
int runcount;
float trim_elev;
float trim_throttle;
SGValue *trimmed;
void snap_shot(void);
};
#endif // _JSBSIM_HXX
<|endoftext|> |
<commit_before>#include "TChain.h"
#include "TTree.h"
#include "TH1F.h"
#include "TF1.h"
#include "TH2F.h"
#include "TCanvas.h"
#include "TObjArray.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliT0AnalysisTaskQA.h"
#include "AliESDpid.h"
//#include "AliCDBMetaData.h"
//#include "AliCDBId.h"
//#include "AliCDBEntry.h"
//#include "AliCDBManager.h"
//#include "AliCDBStorage.h"
// Task should calculate channels offset
// Authors: Alla
//last change 23 Feb 2012 FK
ClassImp(AliT0AnalysisTaskQA)
//________________________________________________________________________
AliT0AnalysisTaskQA::AliT0AnalysisTaskQA()
: AliAnalysisTaskSE(), fESD(0x0), fTzeroObject(0x0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0), fTzeroTof(0x0),
fRunNumber(0),fTimeVSAmplitude(0x0),fCFDVSPmtId(0x0),fSPDVertexVST0Vertex(0x0),
fOrAvsNtracks(0x0), fOrCvsNtracks(0x0), fT0vsNtracks(0x0),fT0TimevsT0Tof(0x0),
fESDpid(new AliESDpid()), f0TVX(0)
{
// Constructor
// Define input and output slots here
// Input slot #0 works with a TChain
// ########### NEVER define slots in the IO constructor
// DefineInput(0, TChain::Class());
// DefineOutput(1, TObjArray::Class());
}
//________________________________________________________________________
AliT0AnalysisTaskQA::AliT0AnalysisTaskQA(const char *name)
: AliAnalysisTaskSE(name), fESD(0x0), fTzeroObject(0x0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0), fTzeroTof(0x0),
fRunNumber(0),fTimeVSAmplitude(0x0),fCFDVSPmtId(0x0),fSPDVertexVST0Vertex(0x0),
fOrAvsNtracks(0x0), fOrCvsNtracks(0x0), fT0vsNtracks(0x0),fT0TimevsT0Tof(0x0),
fESDpid(new AliESDpid()), f0TVX(0)
{
// Constructor
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
DefineOutput(1, TObjArray::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
}
//________________________________________________________________________
AliT0AnalysisTaskQA::~AliT0AnalysisTaskQA()
{
// Destructor
// printf("AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() ");
delete fTzeroORA;
delete fTzeroORC;
delete fResolution;
delete fTzeroORAplusORC;
delete fTzeroTof;
delete [] fTimeVSAmplitude;
delete fCFDVSPmtId;
delete fSPDVertexVST0Vertex;
delete fOrAvsNtracks;
delete fOrCvsNtracks;
delete fT0vsNtracks;
delete fT0TimevsT0Tof;
delete fESDpid;
delete fTzeroObject;
}
//------------------------------------------------------------------
void AliT0AnalysisTaskQA::UserCreateOutputObjects()
{
// Create histograms
fTimeVSAmplitude = new TH2F*[kNPMT0];
for (Int_t i=0; i<kNPMT0; i++) {
fTimeVSAmplitude[i]= new TH2F (Form("fTimeVSAmplitude%d",i+1),"fTimeVsAmplitude",600, -10, 50,500,10000,12000);
}
fTzeroORAplusORC = new TH1F("fTzeroORAplusORC","ORA+ORC /2",100,-2000,2000); //or A plus or C
fTzeroTof = new TH1F("fTzeroTof","t0 from TOF",100,-2000,2000); //t0 start time from TOF
fResolution = new TH1F("fResolution","fResolution",100,-500,500);// or A minus or C spectrum
fTzeroORA = new TH1F("fTzeroORA","fTzeroORA",100,-2000,2000);// or A spectrum
fTzeroORC = new TH1F("fTzeroORC","fTzeroORC",100,-2000,2000);// or C spectrum
fCFDVSPmtId = new TH2F("fCFDVSPmtId","fCFDVSPmtId",24,0,24,500,2000,1000); //
fSPDVertexVST0Vertex = new TH2F("fSPDVertexVST0Vertex","fSPDVertexVST0Vertex",30,-30,30,30,-30,30);
fOrAvsNtracks = new TH2F("fAvstracks", "A vs tracks",200, 0, 1000, 200, -1000, 1000);
fOrCvsNtracks = new TH2F("fCvstracks", "C vs tracks",200, 0, 1000, 200, -1000, 1000);
fT0vsNtracks = new TH2F("fT0ACvstrackes", "T0AC vs tracks",200, 0, 1000, 200, -1000, 1000);
fT0TimevsT0Tof = new TH2F("fT0TimevsT0Tof", "fT0TimevsT0Tof",50, -1000,1000, 50, -1000,1000);
f0TVX = new TH1F("f0TVX","0TVX position [channels]",200,-500,500);// or C spectrum
fTzeroObject = new TObjArray(0);
fTzeroObject->SetOwner(kTRUE);
for (Int_t i=0; i<kNPMT0; i++)
fTzeroObject->AddAtAndExpand(fTimeVSAmplitude[i],i);
fTzeroObject->AddAtAndExpand(fCFDVSPmtId,24);
fTzeroObject->AddAtAndExpand(fSPDVertexVST0Vertex,25);
fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 26);
fTzeroObject->AddAtAndExpand(fResolution, 27);
fTzeroObject->AddAtAndExpand(fTzeroORA, 28);
fTzeroObject->AddAtAndExpand(fTzeroORC, 29);
fTzeroObject->AddAtAndExpand(fT0vsNtracks, 30);
fTzeroObject->AddAtAndExpand(fOrAvsNtracks,31);
fTzeroObject->AddAtAndExpand(fOrCvsNtracks, 32);
fTzeroObject->AddAtAndExpand(fTzeroTof, 33);
fTzeroObject->AddAtAndExpand(fT0TimevsT0Tof, 34);
fTzeroObject->AddAtAndExpand(f0TVX, 35);
PostData(1, fTzeroObject);
// Called once
}
//________________________________________________________________________
void AliT0AnalysisTaskQA::UserExec(Option_t *)
{
// Main loop
// Called for each event
// Post output data.
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESD) {
printf("ERROR: fESD not available\n");
return;
}
fRunNumber = fESD->GetRunNumber() ;
const Double32_t* time = fESD->GetT0time();
const Double32_t* amplitude = fESD->GetT0amplitude();
for (Int_t i=0; i<kNPMT0; i++) {
if(time[i]<99999 )
{
if(amplitude[i]<50){
fTimeVSAmplitude[i]->Fill(amplitude[i],time[i]);
}
else {
fTimeVSAmplitude[i]->Fill(amplitude[i]/1000.,time[i]); //in RUN2 we don't convert to MIPs
}
fCFDVSPmtId->Fill(i,time[i]);
}
}
const Double32_t* mean = fESD->GetT0TOF();
Double32_t orA = mean[1];
Double32_t orC = mean[2];
Int_t ntracks = fESD->GetNumberOfTracks();
Int_t ntracksMatchedToTOF = 0;
for(Int_t itrk=0;itrk<ntracks;itrk++){
AliESDtrack* track = fESD->GetTrack(itrk);
if (!track) {
Printf("ERROR: Could not receive track %d", itrk);
continue;
}
//no track selection just TOF hit
if (track->IsOn(AliESDtrack::kTOFout)) ntracksMatchedToTOF++;
}
if(orA<9999){
fTzeroORA->Fill(orA);
fOrAvsNtracks->Fill(ntracksMatchedToTOF, orA);
}
if(orC<9999) {
fTzeroORC->Fill(orC);
fOrCvsNtracks->Fill(ntracksMatchedToTOF, orC);
}
if(orA<9999 && orC<9999) {
fResolution->Fill((orA-orC)/2.);
fTzeroORAplusORC->Fill(mean[0]);
fT0vsNtracks->Fill(ntracksMatchedToTOF, mean[0]);
}
if(fESDpid){ //get T0_TOF
fESDpid->SetTOFResponse(fESD,AliESDpid::kTOF_T0);
Float_t t0tofTrack =(Float_t) (fESDpid->GetTOFResponse().GetStartTime(10.0)); //Get start time from all tracks
if (t0tofTrack !=0) fTzeroTof->Fill(t0tofTrack);
if(orA<9999 && orC<9999 && t0tofTrack !=0){ // T0 time and TOF time simultaneously
fT0TimevsT0Tof->Fill(t0tofTrack, mean[0]);
}
}
Double32_t t0vertex = fESD->GetT0zVertex();
// cout << "t0 vertex "<<t0vertex<<endl;
Double32_t esdzvertex;
const AliESDVertex * esdvertex = fESD->GetPrimaryVertex();
Int_t nofcontrib=-1;
if(esdvertex && t0vertex<999)
{
nofcontrib=esdvertex->GetNContributors();
if(nofcontrib>1)
{
esdzvertex=esdvertex->GetZ();
// cout << "esd vertex "<<esdzvertex<<endl;
fSPDVertexVST0Vertex->Fill(t0vertex,esdzvertex);
}
}
//0TVX position
AliESDTZERO* tz= (AliESDTZERO*) fESD->GetESDTZERO();
Float_t tvdc = tz->GetTVDC(0);
if (tvdc!=0) f0TVX->Fill(tvdc);
// printf("%f %f %f\n",orA,orC,time);
PostData(1, fTzeroObject);
}
//________________________________________________________________________
void AliT0AnalysisTaskQA::Terminate(Option_t *)
{
// Called once at the end of the query
}
<commit_msg>number of TOF tracks with all cuts<commit_after>#include "TChain.h"
#include "TTree.h"
#include "TH1F.h"
#include "TF1.h"
#include "TH2F.h"
#include "TCanvas.h"
#include "TObjArray.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliT0AnalysisTaskQA.h"
#include "AliESDpid.h"
//#include "AliCDBMetaData.h"
//#include "AliCDBId.h"
//#include "AliCDBEntry.h"
//#include "AliCDBManager.h"
//#include "AliCDBStorage.h"
// Task should calculate channels offset
// Authors: Alla
//last change 23 Feb 2012 FK
ClassImp(AliT0AnalysisTaskQA)
//________________________________________________________________________
AliT0AnalysisTaskQA::AliT0AnalysisTaskQA()
: AliAnalysisTaskSE(), fESD(0x0), fTzeroObject(0x0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0), fTzeroTof(0x0),
fRunNumber(0),fTimeVSAmplitude(0x0),fCFDVSPmtId(0x0),fSPDVertexVST0Vertex(0x0),
fOrAvsNtracks(0x0), fOrCvsNtracks(0x0), fT0vsNtracks(0x0),fT0TimevsT0Tof(0x0),
fESDpid(new AliESDpid()), f0TVX(0)
{
// Constructor
// Define input and output slots here
// Input slot #0 works with a TChain
// ########### NEVER define slots in the IO constructor
// DefineInput(0, TChain::Class());
// DefineOutput(1, TObjArray::Class());
}
//________________________________________________________________________
AliT0AnalysisTaskQA::AliT0AnalysisTaskQA(const char *name)
: AliAnalysisTaskSE(name), fESD(0x0), fTzeroObject(0x0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0), fTzeroTof(0x0),
fRunNumber(0),fTimeVSAmplitude(0x0),fCFDVSPmtId(0x0),fSPDVertexVST0Vertex(0x0),
fOrAvsNtracks(0x0), fOrCvsNtracks(0x0), fT0vsNtracks(0x0),fT0TimevsT0Tof(0x0),
fESDpid(new AliESDpid()), f0TVX(0)
{
// Constructor
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
DefineOutput(1, TObjArray::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
}
//________________________________________________________________________
AliT0AnalysisTaskQA::~AliT0AnalysisTaskQA()
{
// Destructor
// printf("AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() ");
delete fTzeroORA;
delete fTzeroORC;
delete fResolution;
delete fTzeroORAplusORC;
delete fTzeroTof;
delete [] fTimeVSAmplitude;
delete fCFDVSPmtId;
delete fSPDVertexVST0Vertex;
delete fOrAvsNtracks;
delete fOrCvsNtracks;
delete fT0vsNtracks;
delete fT0TimevsT0Tof;
delete fESDpid;
delete fTzeroObject;
}
//------------------------------------------------------------------
void AliT0AnalysisTaskQA::UserCreateOutputObjects()
{
// Create histograms
fTimeVSAmplitude = new TH2F*[kNPMT0];
for (Int_t i=0; i<kNPMT0; i++) {
fTimeVSAmplitude[i]= new TH2F (Form("fTimeVSAmplitude%d",i+1),"fTimeVsAmplitude",600, -10, 50,500,9000,10000);
}
fTzeroORAplusORC = new TH1F("fTzeroORAplusORC","ORA+ORC /2",100,-2000,2000); //or A plus or C
fTzeroTof = new TH1F("fTzeroTof","t0 from TOF",100,-2000,2000); //t0 start time from TOF
fResolution = new TH1F("fResolution","fResolution",100,-500,500);// or A minus or C spectrum
fTzeroORA = new TH1F("fTzeroORA","fTzeroORA",100,-2000,2000);// or A spectrum
fTzeroORC = new TH1F("fTzeroORC","fTzeroORC",100,-2000,2000);// or C spectrum
fCFDVSPmtId = new TH2F("fCFDVSPmtId","fCFDVSPmtId",24,0,24,500,2000,1000); //
fSPDVertexVST0Vertex = new TH2F("fSPDVertexVST0Vertex","fSPDVertexVST0Vertex",30,-30,30,30,-30,30);
fOrAvsNtracks = new TH2F("fAvstracks", "A vs tracks",100, 0, 100, 200, -1000, 1000);
fOrCvsNtracks = new TH2F("fCvstracks", "C vs tracks",100, 0, 100, 200, -1000, 1000);
fT0vsNtracks = new TH2F("fT0ACvstrackes", "T0AC vs tracks",100, 0, 100, 200, -1000, 1000);
fT0TimevsT0Tof = new TH2F("fT0TimevsT0Tof", "fT0TimevsT0Tof",50, -1000,1000, 50, -1000,1000);
f0TVX = new TH1F("f0TVX","0TVX position [channels]",200,-500,500);// or C spectrum
fTzeroObject = new TObjArray(0);
fTzeroObject->SetOwner(kTRUE);
for (Int_t i=0; i<kNPMT0; i++)
fTzeroObject->AddAtAndExpand(fTimeVSAmplitude[i],i);
fTzeroObject->AddAtAndExpand(fCFDVSPmtId,24);
fTzeroObject->AddAtAndExpand(fSPDVertexVST0Vertex,25);
fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 26);
fTzeroObject->AddAtAndExpand(fResolution, 27);
fTzeroObject->AddAtAndExpand(fTzeroORA, 28);
fTzeroObject->AddAtAndExpand(fTzeroORC, 29);
fTzeroObject->AddAtAndExpand(fT0vsNtracks, 30);
fTzeroObject->AddAtAndExpand(fOrAvsNtracks,31);
fTzeroObject->AddAtAndExpand(fOrCvsNtracks, 32);
fTzeroObject->AddAtAndExpand(fTzeroTof, 33);
fTzeroObject->AddAtAndExpand(fT0TimevsT0Tof, 34);
fTzeroObject->AddAtAndExpand(f0TVX, 35);
PostData(1, fTzeroObject);
// Called once
}
//________________________________________________________________________
void AliT0AnalysisTaskQA::UserExec(Option_t *)
{
// Main loop
// Called for each event
// Post output data.
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESD) {
printf("ERROR: fESD not available\n");
return;
}
fRunNumber = fESD->GetRunNumber() ;
const Double32_t* time = fESD->GetT0time();
const Double32_t* amplitude = fESD->GetT0amplitude();
for (Int_t i=0; i<kNPMT0; i++) {
if(time[i]<99999 )
{
if(amplitude[i]<50){
fTimeVSAmplitude[i]->Fill(amplitude[i],time[i]);
}
else {
fTimeVSAmplitude[i]->Fill(amplitude[i]/1000.,time[i]); //in RUN2 we don't convert to MIPs
}
fCFDVSPmtId->Fill(i,time[i]);
}
}
const Double32_t* mean = fESD->GetT0TOF();
Double32_t orA = mean[1];
Double32_t orC = mean[2];
Int_t ntracks = fESD->GetNumberOfTracks();
Int_t ntracksMatchedToTOF = 0;
for(Int_t itrk=0;itrk<ntracks;itrk++){
AliESDtrack* track = fESD->GetTrack(itrk);
if (!track) {
Printf("ERROR: Could not receive track %d", itrk);
continue;
}
//no track selection just TOF hit
if (track->IsOn(AliESDtrack::kTOFout)) ntracksMatchedToTOF++;
}
if(orA<9999){
fTzeroORA->Fill(orA);
fOrAvsNtracks->Fill(ntracksMatchedToTOF, orA);
}
if(orC<9999) {
fTzeroORC->Fill(orC);
fOrCvsNtracks->Fill(ntracksMatchedToTOF, orC);
}
if(orA<9999 && orC<9999) {
fResolution->Fill((orA-orC)/2.);
fTzeroORAplusORC->Fill(mean[0]);
fT0vsNtracks->Fill(ntracksMatchedToTOF, mean[0]);
}
//number of good TOF tracks
Int_t TofTrk=0, CutTrk=0, ntracksMatchedToTOF=0;
Int_t ntracks = fESD->GetNumberOfTracks();
for(Int_t itrk=0;itrk<ntracks;itrk++){
AliVParticle *trk = fESD->GetTrack(itrk);
AliVTrack *Vtrack = dynamic_cast<AliVTrack*>(trk);
AliESDtrack *esdtrack = dynamic_cast<AliESDtrack*>(trk);
if( ( (Vtrack->GetStatus() & AliVTrack::kTOFout) ==
AliVTrack::kTOFout) && ((Vtrack->GetStatus() & AliVTrack::kTIME) ==
AliVTrack::kTIME ) ) {TofTrk++;} else {continue;}
if (!fESDtrackCuts->AcceptTrack(esdtrack)) {
continue;}
CutTrk++;
Float_t feta=Vtrack->Eta();// return pseudorapidity return
if(TMath::Abs(feta)<0.9)
{
ntracksMatchedToTOF++;}
else {continue;};
}
if(fESDpid){ //get T0_TOF
fESDpid->SetTOFResponse(fESD,AliESDpid::kTOF_T0);
Float_t t0tofTrack =(Float_t) ntracksMatchedToTOF;
//(fESDpid->GetTOFResponse().GetStartTime(10.0)); //Get start time from all tracks
if (t0tofTrack !=0) fTzeroTof->Fill(t0tofTrack);
if(orA<9999 && orC<9999 && t0tofTrack !=0){ // T0 time and TOF time simultaneously
fT0TimevsT0Tof->Fill(t0tofTrack, mean[0]);
}
}
Double32_t t0vertex = fESD->GetT0zVertex();
// cout << "t0 vertex "<<t0vertex<<endl;
Double32_t esdzvertex;
const AliESDVertex * esdvertex = fESD->GetPrimaryVertex();
Int_t nofcontrib=-1;
if(esdvertex && t0vertex<999)
{
nofcontrib=esdvertex->GetNContributors();
if(nofcontrib>1)
{
esdzvertex=esdvertex->GetZ();
// cout << "esd vertex "<<esdzvertex<<endl;
fSPDVertexVST0Vertex->Fill(t0vertex,esdzvertex);
}
}
//0TVX position
AliESDTZERO* tz= (AliESDTZERO*) fESD->GetESDTZERO();
Float_t tvdc = tz->GetTVDC(0);
if (tvdc!=0) f0TVX->Fill(tvdc);
// printf("%f %f %f\n",orA,orC,time);
PostData(1, fTzeroObject);
}
//________________________________________________________________________
void AliT0AnalysisTaskQA::Terminate(Option_t *)
{
// Called once at the end of the query
}
<|endoftext|> |
<commit_before>/***
__ __ _ _ __ __ ___
/ _\ ( )( \/ )( ) / \ / __)
/ \ )( ) ( / (_/\( O )( (_ \
\_/\_/(__)(_/\_)\____/ \__/ \___/
This file is part of aixlog
Copyright (C) 2017-2020 Johannes Pohl
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
***/
#include "aixlog.hpp"
using namespace std;
int main(int /*argc*/, char** /*argv*/)
{
AixLog::Log::init<AixLog::SinkCout>(AixLog::Severity::trace);
LOG(TRACE, "LOG_TAG") << "Logger with one cout log sink\n";
LOG(DEBUG, "LOG_TAG") << "Logger with one cout log sink\n";
LOG(INFO, "LOG_TAG") << "Logger with one cout log sink\n";
AixLog::Filter filter;
// log all lines with "trace" severity
filter.add_filter("*:TRACE");
// log all lines with tag "LOG_TAG" with debug or higher severity
filter.add_filter("LOG_TAG:DEBUG");
auto sink_cout = make_shared<AixLog::SinkCout>(filter);
AixLog::Filter filter_syslog;
// log lines with tag "SYSLOG" to syslog
filter_syslog.add_filter("SYSLOG:TRACE");
auto sink_syslog = make_shared<AixLog::SinkSyslog>("aixlog example", filter_syslog);
AixLog::Log::init({sink_cout, sink_syslog});
LOG(TRACE, "LOG_TAG") << "Logger with one cout log sink (filtered out)\n";
LOG(TRACE, "OTHER TAG") << "Logger with one cout log sink (not filtered out)\n";
LOG(DEBUG, "SYSLOG") << "Ths will go also to syslog\n";
AixLog::Log::init({/// Log everything into file "all.log"
make_shared<AixLog::SinkFile>(AixLog::Severity::trace, "all.log"),
/// Log everything to SinkCout
make_shared<AixLog::SinkCout>(AixLog::Severity::trace, "cout: %Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func) #message"),
/// Log error and higher severity messages to cerr
make_shared<AixLog::SinkCerr>(AixLog::Severity::error, "cerr: %Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)"),
/// Callback log sink with cout logging in a lambda function
/// Could also do file logging
make_shared<AixLog::SinkCallback>(AixLog::Severity::trace, [](const AixLog::Metadata& metadata, const std::string& message) {
cout << "Callback:\n\tmsg: " << message << "\n\ttag: " << metadata.tag.text
<< "\n\tsever: " << AixLog::to_string(metadata.severity) << " (" << static_cast<int>(metadata.severity) << ")\n";
if (metadata.timestamp)
cout << "\ttime: " << metadata.timestamp.to_string() << "\n";
if (metadata.function)
cout << "\tfunc: " << metadata.function.name << "\n\tline: " << metadata.function.line
<< "\n\tfile: " << metadata.function.file << "\n";
})});
/// Log with info severity
LOG(INFO) << "LOG(INFO)\n";
/// ... with a tag
LOG(INFO, "guten tag") << "LOG(INFO, \"guten tag\")\n";
/// ... with an explicit tag (same result as above)
LOG(INFO) << TAG("guten tag") << "LOG(INFO) << TAG(\"guten tag\")\n";
/// Different log severities
LOG(FATAL) << "LOG(FATAL)\nLOG(FATAL) Second line\n";
LOG(FATAL) << TAG("hello") << "LOG(FATAL) << TAG(\"hello\") no line break";
LOG(FATAL) << "LOG(FATAL) 2 no line break";
LOG(ERROR) << "LOG(ERROR): change in log-level will add a line break";
LOG(WARNING) << "LOG(WARNING)";
LOG(NOTICE) << "LOG(NOTICE)";
LOG(INFO) << "LOG(INFO)\n";
LOG(INFO) << TAG("my tag") << "LOG(INFO) << TAG(\"my tag\")\n";
LOG(DEBUG) << "LOG(DEBUG)\n";
LOG(TRACE) << "LOG(TRACE)\n";
/// Conditional logging
LOG(DEBUG) << COND(1 == 1) << "LOG(DEBUG) will be logged\n";
LOG(DEBUG) << COND(1 == 2) << "LOG(DEBUG) will not be logged\n";
/// Colors :-)
LOG(FATAL) << "LOG(FATAL) " << AixLog::Color::red << "red" << AixLog::Color::none << ", default color\n";
LOG(FATAL) << "LOG(FATAL) " << COLOR(red) << "red" << COLOR(none) << ", default color (using macros)\n";
LOG(FATAL) << "LOG(FATAL) " << AixLog::TextColor(AixLog::Color::yellow, AixLog::Color::blue) << "yellow on blue background" << AixLog::Color::none
<< ", default color\n";
LOG(FATAL) << "LOG(FATAL) " << COLOR(yellow, blue) << "yellow on blue background" << COLOR(none) << ", default color (using macros)\n";
AixLog::Severity severity(AixLog::Severity::debug);
LOG(severity) << "LOG(severity) << severity\n";
}
<commit_msg>Add example for conditional<commit_after>/***
__ __ _ _ __ __ ___
/ _\ ( )( \/ )( ) / \ / __)
/ \ )( ) ( / (_/\( O )( (_ \
\_/\_/(__)(_/\_)\____/ \__/ \___/
This file is part of aixlog
Copyright (C) 2017-2020 Johannes Pohl
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
***/
#include "aixlog.hpp"
using namespace std;
/// Log Conditional to log only every x-th message
struct EveryXConditional : public AixLog::Conditional
{
/// c'tor
/// @param every_x log only every_x-th line
EveryXConditional(size_t every_x) : every_x_(every_x), x_th_(0)
{
}
/// check if this is the x-th log message
/// @return true if this is the x-th log message
bool is_true() const override
{
if (++x_th_ == every_x_)
{
x_th_ = 0;
return true;
}
return false;
}
private:
size_t every_x_;
mutable size_t x_th_;
};
int main(int /*argc*/, char** /*argv*/)
{
AixLog::Log::init<AixLog::SinkCout>(AixLog::Severity::trace);
LOG(TRACE, "LOG_TAG") << "Logger with one cout log sink\n";
LOG(DEBUG, "LOG_TAG") << "Logger with one cout log sink\n";
LOG(INFO, "LOG_TAG") << "Logger with one cout log sink\n";
AixLog::Filter filter;
// log all lines with "trace" severity
filter.add_filter("*:TRACE");
// log all lines with tag "LOG_TAG" with debug or higher severity
filter.add_filter("LOG_TAG:DEBUG");
auto sink_cout = make_shared<AixLog::SinkCout>(filter);
AixLog::Filter filter_syslog;
// log lines with tag "SYSLOG" to syslog
filter_syslog.add_filter("SYSLOG:TRACE");
auto sink_syslog = make_shared<AixLog::SinkSyslog>("aixlog example", filter_syslog);
AixLog::Log::init({sink_cout, sink_syslog});
LOG(TRACE, "LOG_TAG") << "Logger with one cout log sink (filtered out)\n";
LOG(TRACE, "OTHER TAG") << "Logger with one cout log sink (not filtered out)\n";
LOG(DEBUG, "SYSLOG") << "Ths will go also to syslog\n";
AixLog::Log::init({/// Log everything into file "all.log"
make_shared<AixLog::SinkFile>(AixLog::Severity::trace, "all.log"),
/// Log everything to SinkCout
make_shared<AixLog::SinkCout>(AixLog::Severity::trace, "cout: %Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func) #message"),
/// Log error and higher severity messages to cerr
make_shared<AixLog::SinkCerr>(AixLog::Severity::error, "cerr: %Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)"),
/// Callback log sink with cout logging in a lambda function
/// Could also do file logging
make_shared<AixLog::SinkCallback>(AixLog::Severity::trace, [](const AixLog::Metadata& metadata, const std::string& message) {
cout << "Callback:\n\tmsg: " << message << "\n\ttag: " << metadata.tag.text
<< "\n\tsever: " << AixLog::to_string(metadata.severity) << " (" << static_cast<int>(metadata.severity) << ")\n";
if (metadata.timestamp)
cout << "\ttime: " << metadata.timestamp.to_string() << "\n";
if (metadata.function)
cout << "\tfunc: " << metadata.function.name << "\n\tline: " << metadata.function.line
<< "\n\tfile: " << metadata.function.file << "\n";
})});
/// Log with info severity
LOG(INFO) << "LOG(INFO)\n";
/// ... with a tag
LOG(INFO, "guten tag") << "LOG(INFO, \"guten tag\")\n";
/// ... with an explicit tag (same result as above)
LOG(INFO) << TAG("guten tag") << "LOG(INFO) << TAG(\"guten tag\")\n";
/// Different log severities
LOG(FATAL) << "LOG(FATAL)\nLOG(FATAL) Second line\n";
LOG(FATAL) << TAG("hello") << "LOG(FATAL) << TAG(\"hello\") no line break";
LOG(FATAL) << "LOG(FATAL) 2 no line break";
LOG(ERROR) << "LOG(ERROR): change in log-level will add a line break";
LOG(WARNING) << "LOG(WARNING)";
LOG(NOTICE) << "LOG(NOTICE)";
LOG(INFO) << "LOG(INFO)\n";
LOG(INFO) << TAG("my tag") << "LOG(INFO) << TAG(\"my tag\")\n";
LOG(DEBUG) << "LOG(DEBUG)\n";
LOG(TRACE) << "LOG(TRACE)\n";
/// Conditional logging
LOG(DEBUG) << COND(1 == 1) << "LOG(DEBUG) will be logged\n";
LOG(DEBUG) << COND(1 == 2) << "LOG(DEBUG) will not be logged\n";
/// Colors :-)
LOG(FATAL) << "LOG(FATAL) " << AixLog::Color::red << "red" << AixLog::Color::none << ", default color\n";
LOG(FATAL) << "LOG(FATAL) " << COLOR(red) << "red" << COLOR(none) << ", default color (using macros)\n";
LOG(FATAL) << "LOG(FATAL) " << AixLog::TextColor(AixLog::Color::yellow, AixLog::Color::blue) << "yellow on blue background" << AixLog::Color::none
<< ", default color\n";
LOG(FATAL) << "LOG(FATAL) " << COLOR(yellow, blue) << "yellow on blue background" << COLOR(none) << ", default color (using macros)\n";
AixLog::Severity severity(AixLog::Severity::debug);
LOG(severity) << "LOG(severity) << severity\n";
EveryXConditional every_x(3);
LOG(INFO) << every_x << "1st will not be logged\n";
LOG(INFO) << every_x << "2nd will not be logged\n";
LOG(INFO) << every_x << "3rd will be logged\n";
LOG(INFO) << every_x << "4th will not be logged\n";
LOG(INFO) << every_x << "5th will not be logged\n";
LOG(INFO) << every_x << "6th will be logged\n";
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE EquelleControllerTest
#include <memory>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <vector>
#include <numeric>
#include <fstream>
#include <boost/test/unit_test.hpp>
#include <zoltan_cpp.h>
#include "EquelleRuntimeCPU.hpp"
#include "equelle/mpiutils.hpp"
#include "equelle/RuntimeMPI.hpp"
#include "equelle/ZoltanGrid.hpp"
struct MPIConfig {
MPIConfig() {
MPI_SAFE_CALL( MPI_Init( NULL, NULL ) );
int size;
MPI_SAFE_CALL( MPI_Comm_size( MPI_COMM_WORLD, &size ) );
float zoltanVersion;
ZOLTAN_SAFE_CALL( Zoltan_Initialize( 0, NULL, &zoltanVersion ) );
}
~MPIConfig() {
MPI_SAFE_CALL( MPI_Finalize() );
}
};
BOOST_GLOBAL_FIXTURE( MPIConfig );
void dumpGrid( const UnstructuredGrid* grid ) {
std::stringstream centroids;
std::stringstream face_cells;
const auto dim = grid->dimensions;
centroids << "Centroids: ";
face_cells << "Face cells: ";
for( int i = 0; i < grid->number_of_cells; ++i ) {
centroids << "[";
std::copy( &grid->cell_centroids[i*dim], &grid->cell_centroids[i*dim + dim],
std::ostream_iterator<double>( centroids, " " ) );
centroids << "]";
}
for( int i = 0; i < grid->number_of_faces; ++i ) {
face_cells << i << ": [" << grid->face_cells[2*i] << ", " << grid->face_cells[2*i + 1 ] << "], ";
}
std::cerr << centroids.str() << std::endl;
std::cerr << face_cells.str();
}
BOOST_AUTO_TEST_CASE( gridExploration )
{
Opm::parameter::ParameterGroup paramgroup;
std::unique_ptr<Opm::GridManager> grid ( equelle::createGridManager(paramgroup) );
BOOST_CHECK_EQUAL( grid->c_grid()->number_of_cells, 6 );
//dumpGrid( grid->c_grid() );
}
BOOST_AUTO_TEST_CASE( RuntimeMPI_6x1grid ) {
equelle::RuntimeMPI runtime;
BOOST_CHECK( runtime.zoltan != NULL );
int ierr;
void* grid = const_cast<void*>( reinterpret_cast<const void*>(runtime.grid_manager->c_grid() ) );
if ( equelle::getMPIRank() == 0 ) {
BOOST_CHECK_EQUAL( runtime.grid_manager->c_grid()->number_of_cells, 6 );
BOOST_CHECK_EQUAL( equelle::ZoltanGrid::getNumberOfObjects( grid, &ierr ), 6 );
// Check our querying of the 6x1 grid.
const auto numCells = runtime.grid_manager->c_grid()->number_of_cells;
std::vector<unsigned int> cells( numCells );
for( unsigned int i = 0; i < numCells; ++i ) {
cells[i] = i;
}
std::vector<int> numEdges( numCells, -1 );
equelle::ZoltanGrid::getNumberOfEdgesMulti( grid, 1, 1, numCells, cells.data(), cells.data(), numEdges.data(),
&ierr );
BOOST_CHECK_EQUAL( ierr, ZOLTAN_OK );
BOOST_CHECK_EQUAL( numEdges[0], 1 );
BOOST_CHECK_EQUAL( numEdges[1], 2 );
BOOST_CHECK_EQUAL( numEdges[2], 2 );
BOOST_CHECK_EQUAL( numEdges[3], 2 );
BOOST_CHECK_EQUAL( numEdges[4], 2 );
BOOST_CHECK_EQUAL( numEdges[5], 1 );
auto totalNumberOfNeighbors = std::accumulate( numEdges.begin(), numEdges.end(), 0 );
std::vector<ZOLTAN_ID_TYPE> edgeList( totalNumberOfNeighbors, -1 );
std::vector<int> nbor_procs( edgeList.size() );
equelle::ZoltanGrid::getEdgeListMulti( grid, 1, 1, numCells,
cells.data(), cells.data(), numEdges.data(),
edgeList.data(), nbor_procs.data(), 0, NULL, &ierr );
// Cell 0
BOOST_CHECK_EQUAL( edgeList[0], 1 ); // 0 is neighbor with 1
// Cell 1
BOOST_CHECK_EQUAL( edgeList[1], 0 );
BOOST_CHECK_EQUAL( edgeList[2], 2 );
// Cell 2
BOOST_CHECK_EQUAL( edgeList[3], 1 );
BOOST_CHECK_EQUAL( edgeList[4], 3 );
// Cell 3
BOOST_CHECK_EQUAL( edgeList[5], 2 );
BOOST_CHECK_EQUAL( edgeList[6], 4 );
// Cell 4UTO
BOOST_CHECK_EQUAL( edgeList[7], 3 );
BOOST_CHECK_EQUAL( edgeList[8], 5 );
// Cell 5
BOOST_CHECK_EQUAL( edgeList[9], 4 );
BOOST_CHECK_EQUAL( ierr, ZOLTAN_OK );
} else {
BOOST_CHECK_EQUAL( runtime.grid_manager->c_grid()->number_of_cells, 0 );
BOOST_CHECK_EQUAL( equelle::ZoltanGrid::getNumberOfObjects( grid, &ierr ), 0 );
}
auto zr = runtime.computePartition();
BOOST_CHECK_EQUAL( zr.changes, 1 );
if ( equelle::getMPIRank() == 0 ) {
std::ofstream f("rank0-exports");
equelle::ZoltanGrid::dumpRank0Exports( runtime.grid_manager->c_grid()->number_of_cells, zr, f );
}
}
BOOST_AUTO_TEST_CASE( RuntimeMPI_6x2grid ) {
equelle::RuntimeMPI runtime;
if ( equelle::getMPIRank() == 0 ) {
runtime.grid_manager.reset( new Opm::GridManager( 6, 2 ) );
} // else the grid for other MPI nodes are empty in RuntimeMPI ctor.
auto zr = runtime.computePartition();
BOOST_CHECK_EQUAL( zr.changes, 1 );
if ( equelle::getMPIRank() == 0 ) {
std::ofstream f("rank0-6x2-exports");
equelle::ZoltanGrid::dumpRank0Exports( runtime.grid_manager->c_grid()->number_of_cells, zr, f );
}
}
<commit_msg>Added files and test for ZoltanGridMigrator.<commit_after>#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE EquelleControllerTest
#include <memory>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <vector>
#include <numeric>
#include <fstream>
#include <boost/test/unit_test.hpp>
#include <zoltan_cpp.h>
#include "EquelleRuntimeCPU.hpp"
#include "equelle/mpiutils.hpp"
#include "equelle/RuntimeMPI.hpp"
#include "equelle/ZoltanGrid.hpp"
#include "equelle/ZoltanGridMigrator.hpp"
struct MPIConfig {
MPIConfig() {
MPI_SAFE_CALL( MPI_Init( NULL, NULL ) );
int size;
MPI_SAFE_CALL( MPI_Comm_size( MPI_COMM_WORLD, &size ) );
float zoltanVersion;
ZOLTAN_SAFE_CALL( Zoltan_Initialize( 0, NULL, &zoltanVersion ) );
}
~MPIConfig() {
MPI_SAFE_CALL( MPI_Finalize() );
}
};
BOOST_GLOBAL_FIXTURE( MPIConfig );
void dumpGrid( const UnstructuredGrid* grid ) {
std::stringstream centroids;
std::stringstream face_cells;
const auto dim = grid->dimensions;
centroids << "Centroids: ";
face_cells << "Face cells: ";
for( int i = 0; i < grid->number_of_cells; ++i ) {
centroids << "[";
std::copy( &grid->cell_centroids[i*dim], &grid->cell_centroids[i*dim + dim],
std::ostream_iterator<double>( centroids, " " ) );
centroids << "]";
}
for( int i = 0; i < grid->number_of_faces; ++i ) {
face_cells << i << ": [" << grid->face_cells[2*i] << ", " << grid->face_cells[2*i + 1 ] << "], ";
}
std::cerr << centroids.str() << std::endl;
std::cerr << face_cells.str();
}
BOOST_AUTO_TEST_CASE( gridExploration )
{
Opm::parameter::ParameterGroup paramgroup;
std::unique_ptr<Opm::GridManager> grid ( equelle::createGridManager(paramgroup) );
BOOST_CHECK_EQUAL( grid->c_grid()->number_of_cells, 6 );
//dumpGrid( grid->c_grid() );
}
BOOST_AUTO_TEST_CASE( RuntimeMPI_6x1grid ) {
equelle::RuntimeMPI runtime;
BOOST_CHECK( runtime.zoltan != NULL );
int ierr;
void* grid = const_cast<void*>( reinterpret_cast<const void*>(runtime.grid_manager->c_grid() ) );
if ( equelle::getMPIRank() == 0 ) {
BOOST_CHECK_EQUAL( runtime.grid_manager->c_grid()->number_of_cells, 6 );
BOOST_CHECK_EQUAL( equelle::ZoltanGrid::getNumberOfObjects( grid, &ierr ), 6 );
// Check our querying of the 6x1 grid.
const auto numCells = runtime.grid_manager->c_grid()->number_of_cells;
std::vector<unsigned int> cells( numCells );
for( unsigned int i = 0; i < numCells; ++i ) {
cells[i] = i;
}
std::vector<int> numEdges( numCells, -1 );
equelle::ZoltanGrid::getNumberOfEdgesMulti( grid, 1, 1, numCells, cells.data(), cells.data(), numEdges.data(),
&ierr );
BOOST_CHECK_EQUAL( ierr, ZOLTAN_OK );
BOOST_CHECK_EQUAL( numEdges[0], 1 );
BOOST_CHECK_EQUAL( numEdges[1], 2 );
BOOST_CHECK_EQUAL( numEdges[2], 2 );
BOOST_CHECK_EQUAL( numEdges[3], 2 );
BOOST_CHECK_EQUAL( numEdges[4], 2 );
BOOST_CHECK_EQUAL( numEdges[5], 1 );
auto totalNumberOfNeighbors = std::accumulate( numEdges.begin(), numEdges.end(), 0 );
std::vector<ZOLTAN_ID_TYPE> edgeList( totalNumberOfNeighbors, -1 );
std::vector<int> nbor_procs( edgeList.size() );
equelle::ZoltanGrid::getEdgeListMulti( grid, 1, 1, numCells,
cells.data(), cells.data(), numEdges.data(),
edgeList.data(), nbor_procs.data(), 0, NULL, &ierr );
// Cell 0
BOOST_CHECK_EQUAL( edgeList[0], 1 ); // 0 is neighbor with 1
// Cell 1
BOOST_CHECK_EQUAL( edgeList[1], 0 );
BOOST_CHECK_EQUAL( edgeList[2], 2 );
// Cell 2
BOOST_CHECK_EQUAL( edgeList[3], 1 );
BOOST_CHECK_EQUAL( edgeList[4], 3 );
// Cell 3
BOOST_CHECK_EQUAL( edgeList[5], 2 );
BOOST_CHECK_EQUAL( edgeList[6], 4 );
// Cell 4UTO
BOOST_CHECK_EQUAL( edgeList[7], 3 );
BOOST_CHECK_EQUAL( edgeList[8], 5 );
// Cell 5
BOOST_CHECK_EQUAL( edgeList[9], 4 );
BOOST_CHECK_EQUAL( ierr, ZOLTAN_OK );
} else {
BOOST_CHECK_EQUAL( runtime.grid_manager->c_grid()->number_of_cells, 0 );
BOOST_CHECK_EQUAL( equelle::ZoltanGrid::getNumberOfObjects( grid, &ierr ), 0 );
}
auto zr = runtime.computePartition();
BOOST_CHECK_EQUAL( zr.changes, 1 );
if ( equelle::getMPIRank() == 0 ) {
std::ofstream f("rank0-exports");
equelle::ZoltanGrid::dumpRank0Exports( runtime.grid_manager->c_grid()->number_of_cells, zr, f );
}
}
BOOST_AUTO_TEST_CASE( RuntimeMPI_6x2grid ) {
equelle::RuntimeMPI runtime;
if ( equelle::getMPIRank() == 0 ) {
runtime.grid_manager.reset( new Opm::GridManager( 6, 2 ) );
} // else the grid for other MPI nodes are empty in RuntimeMPI ctor.
auto zr = runtime.computePartition();
BOOST_CHECK_EQUAL( zr.changes, 1 );
if ( equelle::getMPIRank() == 0 ) {
std::ofstream f("rank0-6x2-exports");
equelle::ZoltanGrid::dumpRank0Exports( runtime.grid_manager->c_grid()->number_of_cells, zr, f );
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/workspace/snap_sizer.h"
#include <cmath>
#include "ash/screen_ash.h"
#include "ash/wm/window_resizer.h"
#include "ui/aura/window.h"
#include "ui/gfx/screen.h"
namespace ash {
namespace internal {
namespace {
// Percent of the screen (width) to give the window.
const float kPercents[] = { .5f, 2.0f / 3.0f, .8f };
// Windows are initially snapped to the percent at index 0. The index into
// |kPercents| is changed if any of the following happen:
// . The user stops moving the mouse for |kDelayBeforeIncreaseMS| and then moves
// the mouse again.
// . The mouse moves |kPixelsBeforeAdjust| horizontal pixels.
// . The mouse is against the edge of the screen and the mouse is moved
// |kMovesBeforeAdjust| times.
const int kDelayBeforeIncreaseMS = 500;
const int kMovesBeforeAdjust = 50;
const int kPixelsBeforeAdjust = 200;
} // namespace
SnapSizer::SnapSizer(aura::Window* window,
const gfx::Point& start,
Edge edge,
int grid_size)
: window_(window),
edge_(edge),
grid_size_(grid_size),
time_last_update_(base::TimeTicks::Now()),
percent_index_(0),
num_moves_since_adjust_(0),
last_adjust_x_(start.x()),
last_update_x_(start.x()) {
target_bounds_ = GetTargetBounds();
}
void SnapSizer::Update(const gfx::Point& location) {
// See description above for details on this behavior.
num_moves_since_adjust_++;
if ((base::TimeTicks::Now() - time_last_update_).InMilliseconds() >
kDelayBeforeIncreaseMS) {
ChangeBounds(location.x(),
CalculateIncrement(location.x(), last_update_x_));
} else {
bool along_edge = AlongEdge(location.x());
if (std::abs(location.x() - last_adjust_x_) >= kPixelsBeforeAdjust ||
(along_edge && num_moves_since_adjust_ >= kMovesBeforeAdjust)) {
ChangeBounds(location.x(),
CalculateIncrement(location.x(), last_adjust_x_));
}
}
last_update_x_ = location.x();
time_last_update_ = base::TimeTicks::Now();
}
int SnapSizer::CalculateIncrement(int x, int reference_x) const {
if (AlongEdge(x))
return 1;
if (x == reference_x)
return 0;
if (edge_ == LEFT_EDGE) {
if (x < reference_x)
return 1;
return -1;
}
// edge_ == RIGHT_EDGE.
if (x > reference_x)
return 1;
return -1;
}
void SnapSizer::ChangeBounds(int x, int delta) {
int index = std::min(static_cast<int>(arraysize(kPercents)) - 1,
std::max(percent_index_ + delta, 0));
if (index != percent_index_) {
percent_index_ = index;
target_bounds_ = GetTargetBounds();
}
num_moves_since_adjust_ = 0;
last_adjust_x_ = x;
}
gfx::Rect SnapSizer::GetTargetBounds() const {
gfx::Rect work_area(ScreenAsh::GetUnmaximizedWorkAreaBounds(window_));
int y = WindowResizer::AlignToGridRoundUp(work_area.y(), grid_size_);
int max_y =
WindowResizer::AlignToGridRoundDown(work_area.bottom(), grid_size_);
int width = static_cast<float>(work_area.width()) * kPercents[percent_index_];
if (edge_ == LEFT_EDGE) {
int x = WindowResizer::AlignToGridRoundUp(work_area.x(), grid_size_);
int mid_x = WindowResizer::AlignToGridRoundUp(
work_area.x() + width, grid_size_);
return gfx::Rect(x, y, mid_x - x, max_y - y);
}
int max_x =
WindowResizer::AlignToGridRoundDown(work_area.right(), grid_size_);
int x = WindowResizer::AlignToGridRoundUp(max_x - width, grid_size_);
return gfx::Rect(x , y, max_x - x, max_y - y);
}
bool SnapSizer::AlongEdge(int x) const {
// TODO: need to support multi-monitor.
gfx::Rect area(gfx::Screen::GetMonitorAreaNearestWindow(window_));
return (x <= area.x()) || (x >= area.right() - 1);
}
} // namespace internal
} // namespace ash
<commit_msg>Decreases the number of pixels needed to trigger a snap from 200 to 100.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/workspace/snap_sizer.h"
#include <cmath>
#include "ash/screen_ash.h"
#include "ash/wm/window_resizer.h"
#include "ui/aura/window.h"
#include "ui/gfx/screen.h"
namespace ash {
namespace internal {
namespace {
// Percent of the screen (width) to give the window.
const float kPercents[] = { .5f, 2.0f / 3.0f, .8f };
// Windows are initially snapped to the percent at index 0. The index into
// |kPercents| is changed if any of the following happen:
// . The user stops moving the mouse for |kDelayBeforeIncreaseMS| and then moves
// the mouse again.
// . The mouse moves |kPixelsBeforeAdjust| horizontal pixels.
// . The mouse is against the edge of the screen and the mouse is moved
// |kMovesBeforeAdjust| times.
const int kDelayBeforeIncreaseMS = 500;
const int kMovesBeforeAdjust = 50;
const int kPixelsBeforeAdjust = 100;
} // namespace
SnapSizer::SnapSizer(aura::Window* window,
const gfx::Point& start,
Edge edge,
int grid_size)
: window_(window),
edge_(edge),
grid_size_(grid_size),
time_last_update_(base::TimeTicks::Now()),
percent_index_(0),
num_moves_since_adjust_(0),
last_adjust_x_(start.x()),
last_update_x_(start.x()) {
target_bounds_ = GetTargetBounds();
}
void SnapSizer::Update(const gfx::Point& location) {
// See description above for details on this behavior.
num_moves_since_adjust_++;
if ((base::TimeTicks::Now() - time_last_update_).InMilliseconds() >
kDelayBeforeIncreaseMS) {
ChangeBounds(location.x(),
CalculateIncrement(location.x(), last_update_x_));
} else {
bool along_edge = AlongEdge(location.x());
if (std::abs(location.x() - last_adjust_x_) >= kPixelsBeforeAdjust ||
(along_edge && num_moves_since_adjust_ >= kMovesBeforeAdjust)) {
ChangeBounds(location.x(),
CalculateIncrement(location.x(), last_adjust_x_));
}
}
last_update_x_ = location.x();
time_last_update_ = base::TimeTicks::Now();
}
int SnapSizer::CalculateIncrement(int x, int reference_x) const {
if (AlongEdge(x))
return 1;
if (x == reference_x)
return 0;
if (edge_ == LEFT_EDGE) {
if (x < reference_x)
return 1;
return -1;
}
// edge_ == RIGHT_EDGE.
if (x > reference_x)
return 1;
return -1;
}
void SnapSizer::ChangeBounds(int x, int delta) {
int index = std::min(static_cast<int>(arraysize(kPercents)) - 1,
std::max(percent_index_ + delta, 0));
if (index != percent_index_) {
percent_index_ = index;
target_bounds_ = GetTargetBounds();
}
num_moves_since_adjust_ = 0;
last_adjust_x_ = x;
}
gfx::Rect SnapSizer::GetTargetBounds() const {
gfx::Rect work_area(ScreenAsh::GetUnmaximizedWorkAreaBounds(window_));
int y = WindowResizer::AlignToGridRoundUp(work_area.y(), grid_size_);
int max_y =
WindowResizer::AlignToGridRoundDown(work_area.bottom(), grid_size_);
int width = static_cast<float>(work_area.width()) * kPercents[percent_index_];
if (edge_ == LEFT_EDGE) {
int x = WindowResizer::AlignToGridRoundUp(work_area.x(), grid_size_);
int mid_x = WindowResizer::AlignToGridRoundUp(
work_area.x() + width, grid_size_);
return gfx::Rect(x, y, mid_x - x, max_y - y);
}
int max_x =
WindowResizer::AlignToGridRoundDown(work_area.right(), grid_size_);
int x = WindowResizer::AlignToGridRoundUp(max_x - width, grid_size_);
return gfx::Rect(x , y, max_x - x, max_y - y);
}
bool SnapSizer::AlongEdge(int x) const {
// TODO: need to support multi-monitor.
gfx::Rect area(gfx::Screen::GetMonitorAreaNearestWindow(window_));
return (x <= area.x()) || (x >= area.right() - 1);
}
} // namespace internal
} // namespace ash
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief RX65N デジタル・ストレージ・オシロスコープ @n
マイコン内臓12ビットA/D変換を使って、波形を観測するガジェット
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#define CASH_KFONT
#include "common/renesas.hpp"
#include "common/cmt_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/sci_i2c_io.hpp"
#include "common/format.hpp"
#include "common/command.hpp"
#include "common/spi_io2.hpp"
#include "ff13c/mmc_io.hpp"
#include "common/sdc_man.hpp"
#include "common/tpu_io.hpp"
#include "common/qspi_io.hpp"
#include "graphics/font8x16.hpp"
#include "graphics/graphics.hpp"
#include "graphics/filer.hpp"
#include "graphics/kfont.hpp"
#include "graphics/font.hpp"
#include "chip/FT5206.hpp"
#include "capture.hpp"
#include "render_wave.hpp"
namespace {
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::cmt_io<device::CMT0, utils::null_task> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 512> RECV_BUFF;
typedef utils::fixed_fifo<char, 1024> SEND_BUFF;
typedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI;
SCI sci_;
// カード電源制御は使わないので、「device::NULL_PORT」を指定する。
// typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;
typedef device::NULL_PORT SDC_POWER;
#ifdef SDHI_IF
// RX65N Envision Kit の SDHI ポートは、候補3になっている
typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI;
SDHI sdh_;
#else
// Soft SDC 用 SPI 定義(SPI)
typedef device::PORT<device::PORT2, device::bitpos::B2> MISO; // DAT0
typedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; // CMD
typedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; // CLK
typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義
SPI spi_;
typedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; // DAT3 カード選択信号
typedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; // CD カード検出
typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; // ハードウェアー定義
MMC sdh_(spi_, 20000000);
#endif
typedef utils::sdc_man SDC;
SDC sdc_;
typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;
static const int16_t LCD_X = 480;
static const int16_t LCD_Y = 272;
static void* LCD_ORG = reinterpret_cast<void*>(0x00000100);
static const auto PIXT = graphics::pixel::TYPE::RGB565;
typedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIXT> GLCDC_IO;
GLCDC_IO glcdc_io_(nullptr, LCD_ORG);
typedef graphics::font8x16 AFONT;
AFONT afont_;
#ifdef CASH_KFONT
typedef graphics::kfont<16, 16, 64> KFONT;
#else
typedef graphics::kfont<16, 16> KFONT;
#endif
KFONT kfont_;
typedef graphics::font<AFONT, KFONT> FONT;
FONT font_(afont_, kfont_);
typedef device::drw2d_mgr<GLCDC_IO, FONT> DRW2D_MGR;
DRW2D_MGR drw2d_mgr_(glcdc_io_, font_);
typedef graphics::render<GLCDC_IO, FONT> RENDER;
RENDER render_(glcdc_io_, font_);
typedef utils::capture<2048> CAPTURE;
CAPTURE capture_;
// FT5206, SCI6 簡易 I2C 定義
typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
typedef utils::fixed_fifo<uint8_t, 64> RB6;
typedef utils::fixed_fifo<uint8_t, 64> SB6;
typedef device::sci_i2c_io<device::SCI6, RB6, SB6,
device::port_map::option::FIRST_I2C> FT5206_I2C;
FT5206_I2C ft5206_i2c_;
typedef chip::FT5206<FT5206_I2C> FT5206;
FT5206 ft5206_(ft5206_i2c_);
typedef utils::render_wave<RENDER, CAPTURE, FT5206> RENDER_WAVE;
RENDER_WAVE render_wave_(render_, capture_, ft5206_);
utils::command<256> cmd_;
utils::capture_trigger trigger_ = utils::capture_trigger::NONE;
bool check_mount_() {
return sdc_.get_mount();
}
void update_led_()
{
static uint8_t n = 0;
++n;
if(n >= 30) {
n = 0;
}
if(n < 10) {
LED::P = 0;
} else {
LED::P = 1;
}
}
void command_()
{
if(!cmd_.service()) {
return;
}
uint8_t cmdn = cmd_.get_words();
if(cmdn >= 1) {
bool f = false;
if(cmd_.cmp_word(0, "dir")) { // dir [xxx]
if(check_mount_()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
}
f = true;
} else if(cmd_.cmp_word(0, "cd")) { // cd [xxx]
if(check_mount_()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
}
f = true;
} else if(cmd_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
f = true;
} else if(cmd_.cmp_word(0, "cap")) { // capture
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
f = true;
} else if(cmd_.cmp_word(0, "help")) {
utils::format(" dir [path]\n");
utils::format(" cd [path]\n");
utils::format(" pwd\n");
utils::format(" cap single trigger\n");
f = true;
}
if(!f) {
char tmp[128];
if(cmd_.get_word(0, tmp, sizeof(tmp))) {
utils::format("Command error: '%s'\n") % tmp;
}
}
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdh_.disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdh_.disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdh_.disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
time_t t = 0;
/// rtc_.get_time(t);
return utils::str::get_fattime(t);
}
int fatfs_get_mount() {
return check_mount_();
}
int make_full_path(const char* src, char* dst, uint16_t len)
{
return sdc_.make_full_path(src, dst, len);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
{ // SD カード・クラスの初期化
sdh_.start();
sdc_.start();
}
{ // キャプチャー開始
// uint32_t freq = 2000000; // 2 MHz
uint32_t freq = 100000; // 100 KHz
if(!capture_.start(freq)) {
utils::format("Capture not start...\n");
}
}
utils::format("RTK5RX65N Start for Digital Storage Oscilloscope\n");
cmd_.set_prompt("# ");
{ // GLCDC の初期化
LCD_DISP::DIR = 1;
LCD_LIGHT::DIR = 1;
LCD_DISP::P = 0; // DISP Disable
LCD_LIGHT::P = 0; // BackLight Disable (No PWM)
if(glcdc_io_.start()) {
utils::format("Start GLCDC\n");
LCD_DISP::P = 1; // DISP Enable
LCD_LIGHT::P = 1; // BackLight Enable (No PWM)
if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {
utils::format("GLCDC ctrl fail...\n");
}
} else {
utils::format("GLCDC Fail\n");
}
}
{ // DRW2D 初期化
auto ver = drw2d_mgr_.get_version();
utils::format("DRW2D Version: %04X\n") % ver;
if(drw2d_mgr_.start()) {
utils:: format("Start DRW2D\n");
} else {
utils:: format("DRW2D Fail\n");
}
}
{ // FT5206 touch screen controller
FT5206::reset<FT5206_RESET>();
uint8_t intr_lvl = 1;
if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
utils::format("FT5206 I2C Start Fail...\n");
}
if(!ft5206_.start()) {
utils::format("FT5206 Start Fail...\n");
}
}
LED::DIR = 1;
{ // startup trigger...
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
}
// タッチパネルの安定待ち
#if 0
{
uint8_t nnn = 0;
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
// if(ft5206_.get_touch_num() == 0) {
// ++nnn;
/// if(nnn >= 60) break;
// } else {
// utils::format("%d\n") % static_cast<uint16_t>(ft5206_.get_touch_num());
// nnn = 0;
// }
}
}
#endif
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
sdc_.service(sdh_.service());
command_();
// タッチ操作による画面更新が必要か?
bool f = render_wave_.ui_service();
// 波形をキャプチャーしたら描画
if(f || (trigger_ != utils::capture_trigger::NONE
&& capture_.get_trigger() == utils::capture_trigger::NONE)) {
trigger_ = utils::capture_trigger::NONE;
render_wave_.update();
}
update_led_();
}
}
<commit_msg>Update: quit sdc_man class<commit_after>//=====================================================================//
/*! @file
@brief RX65N デジタル・ストレージ・オシロスコープ @n
マイコン内臓12ビットA/D変換を使って、波形を観測するガジェット
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#define CASH_KFONT
#include "common/renesas.hpp"
#include "common/cmt_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/sci_i2c_io.hpp"
#include "common/format.hpp"
#include "common/command.hpp"
#include "common/spi_io2.hpp"
#include "ff13c/mmc_io.hpp"
#include "common/tpu_io.hpp"
#include "common/qspi_io.hpp"
#include "graphics/font8x16.hpp"
#include "graphics/graphics.hpp"
#include "graphics/filer.hpp"
#include "graphics/kfont.hpp"
#include "graphics/font.hpp"
#include "chip/FT5206.hpp"
#include "capture.hpp"
#include "render_wave.hpp"
namespace {
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::cmt_io<device::CMT0, utils::null_task> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 512> RECV_BUFF;
typedef utils::fixed_fifo<char, 1024> SEND_BUFF;
typedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI;
SCI sci_;
// カード電源制御は使わないので、「device::NULL_PORT」を指定する。
// typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;
typedef device::NULL_PORT SDC_POWER;
#ifdef SDHI_IF
// RX65N Envision Kit の SDHI ポートは、候補3になっている
typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI;
SDHI sdh_;
#else
// Soft SDC 用 SPI 定義(SPI)
typedef device::PORT<device::PORT2, device::bitpos::B2> MISO; // DAT0
typedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; // CMD
typedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; // CLK
typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義
SPI spi_;
typedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; // DAT3 カード選択信号
typedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; // CD カード検出
typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; // ハードウェアー定義
MMC sdh_(spi_, 20000000);
#endif
typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;
static const int16_t LCD_X = 480;
static const int16_t LCD_Y = 272;
static void* LCD_ORG = reinterpret_cast<void*>(0x00000100);
static const auto PIXT = graphics::pixel::TYPE::RGB565;
typedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIXT> GLCDC_IO;
GLCDC_IO glcdc_io_(nullptr, LCD_ORG);
typedef graphics::font8x16 AFONT;
AFONT afont_;
#ifdef CASH_KFONT
typedef graphics::kfont<16, 16, 64> KFONT;
#else
typedef graphics::kfont<16, 16> KFONT;
#endif
KFONT kfont_;
typedef graphics::font<AFONT, KFONT> FONT;
FONT font_(afont_, kfont_);
typedef device::drw2d_mgr<GLCDC_IO, FONT> DRW2D_MGR;
DRW2D_MGR drw2d_mgr_(glcdc_io_, font_);
typedef graphics::render<GLCDC_IO, FONT> RENDER;
RENDER render_(glcdc_io_, font_);
typedef utils::capture<2048> CAPTURE;
CAPTURE capture_;
// FT5206, SCI6 簡易 I2C 定義
typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
typedef utils::fixed_fifo<uint8_t, 64> RB6;
typedef utils::fixed_fifo<uint8_t, 64> SB6;
typedef device::sci_i2c_io<device::SCI6, RB6, SB6,
device::port_map::option::FIRST_I2C> FT5206_I2C;
FT5206_I2C ft5206_i2c_;
typedef chip::FT5206<FT5206_I2C> FT5206;
FT5206 ft5206_(ft5206_i2c_);
typedef utils::render_wave<RENDER, CAPTURE, FT5206> RENDER_WAVE;
RENDER_WAVE render_wave_(render_, capture_, ft5206_);
utils::command<256> cmd_;
utils::capture_trigger trigger_ = utils::capture_trigger::NONE;
void update_led_()
{
static uint8_t n = 0;
++n;
if(n >= 30) {
n = 0;
}
if(n < 10) {
LED::P = 0;
} else {
LED::P = 1;
}
}
void command_()
{
if(!cmd_.service()) {
return;
}
uint8_t cmdn = cmd_.get_words();
if(cmdn >= 1) {
bool f = false;
if(cmd_.cmp_word(0, "dir")) { // dir [xxx]
if(sdh_.get_mount()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
utils::file_io::dir(tmp);
} else {
utils::file_io::dir("");
}
}
f = true;
} else if(cmd_.cmp_word(0, "cd")) { // cd [xxx]
if(sdh_.get_mount()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
utils::file_io::cd(tmp);
} else {
utils::file_io::cd("/");
}
}
f = true;
} else if(cmd_.cmp_word(0, "pwd")) { // pwd
char tmp[FF_MAX_LFN + 1];
if(!utils::file_io::pwd(tmp, sizeof(tmp))) {
utils::format("%s\n") % tmp;
}
f = true;
} else if(cmd_.cmp_word(0, "cap")) { // capture
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
f = true;
} else if(cmd_.cmp_word(0, "help")) {
utils::format(" dir [path]\n");
utils::format(" cd [path]\n");
utils::format(" pwd\n");
utils::format(" cap single trigger\n");
f = true;
}
if(!f) {
char tmp[128];
if(cmd_.get_word(0, tmp, sizeof(tmp))) {
utils::format("Command error: '%s'\n") % tmp;
}
}
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdh_.disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdh_.disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdh_.disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
time_t t = 0;
/// rtc_.get_time(t);
return utils::str::get_fattime(t);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
{ // SD カード・クラスの初期化
sdh_.start();
}
{ // キャプチャー開始
// uint32_t freq = 2000000; // 2 MHz
uint32_t freq = 100000; // 100 KHz
if(!capture_.start(freq)) {
utils::format("Capture not start...\n");
}
}
utils::format("RTK5RX65N Start for Digital Storage Oscilloscope\n");
cmd_.set_prompt("# ");
{ // GLCDC の初期化
LCD_DISP::DIR = 1;
LCD_LIGHT::DIR = 1;
LCD_DISP::P = 0; // DISP Disable
LCD_LIGHT::P = 0; // BackLight Disable (No PWM)
if(glcdc_io_.start()) {
utils::format("Start GLCDC\n");
LCD_DISP::P = 1; // DISP Enable
LCD_LIGHT::P = 1; // BackLight Enable (No PWM)
if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {
utils::format("GLCDC ctrl fail...\n");
}
} else {
utils::format("GLCDC Fail\n");
}
}
{ // DRW2D 初期化
auto ver = drw2d_mgr_.get_version();
utils::format("DRW2D Version: %04X\n") % ver;
if(drw2d_mgr_.start()) {
utils:: format("Start DRW2D\n");
} else {
utils:: format("DRW2D Fail\n");
}
}
{ // FT5206 touch screen controller
FT5206::reset<FT5206_RESET>();
uint8_t intr_lvl = 1;
if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
utils::format("FT5206 I2C Start Fail...\n");
}
if(!ft5206_.start()) {
utils::format("FT5206 Start Fail...\n");
}
}
LED::DIR = 1;
{ // startup trigger...
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
}
// タッチパネルの安定待ち
#if 0
{
uint8_t nnn = 0;
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
// if(ft5206_.get_touch_num() == 0) {
// ++nnn;
/// if(nnn >= 60) break;
// } else {
// utils::format("%d\n") % static_cast<uint16_t>(ft5206_.get_touch_num());
// nnn = 0;
// }
}
}
#endif
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
sdh_.service();
command_();
// タッチ操作による画面更新が必要か?
bool f = render_wave_.ui_service();
// 波形をキャプチャーしたら描画
if(f || (trigger_ != utils::capture_trigger::NONE
&& capture_.get_trigger() == utils::capture_trigger::NONE)) {
trigger_ = utils::capture_trigger::NONE;
render_wave_.update();
}
update_led_();
}
}
<|endoftext|> |
<commit_before>#include <cerrno>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include "lib/picojson.h"
#include "convert.hpp"
#include "definitions.hpp"
#include "error.hpp"
#include "llvm_asm_loader.hpp"
#include "process.hpp"
#include "vmemory.hpp"
using namespace processwarp;
static const std::string pool_path("/tmp/");
/**
* Load program from LLVM-IR and write dump file.
*/
class Loader : public ProcessDelegate, public VMemoryDelegate {
public:
/// Virtual memory for this loader.
VMemory vmemory;
/// Assigned process-id.
vpid_t in_pid;
///
std::string in_name;
///
dev_id_t in_dst_device;
///
dev_id_t in_src_device;
///
std::string in_src_account;
///
std::string in_type;
///
vtid_t out_root_tid;
/**
* Constructor, initialize virtual-memory instance.
*/
Loader() :
vmemory(*this, DEV_SERVER) {
}
/**
*/
std::unique_ptr<VMemory::Accessor> assign_accessor(const vpid_t& pid) override {
assert(!in_pid.empty());
return std::move(vmemory.get_accessor(Convert::vpid2str(pid)));
}
/**
*/
void on_change_thread_set(Process& proc) override {
}
// Call when send memory data to other device.
void send_memory_data(const std::string& name,
const dev_id_t& dev_id,
const std::string& data) override {
print_debug("send memory data (%s@%s):%s\n", name.c_str(), dev_id.c_str(), data.c_str());
assert(false);
}
/**
* Call when memory is update by other node.
* Should not call.
*/
void on_recv_update(const std::string& name, vaddr_t addr) override {
assert(false);
}
/**
*
*/
void load(const std::vector<std::string>& args) {
// Setup virtual-memory.
vmemory.set_loading(Convert::vpid2str(in_pid), true);
// Setup virtual machine.
// Library is empty because don't use in loader.
std::vector<void*> libs;
std::map<std::string, std::string> lib_filter;
std::map<std::string, std::pair<builtin_func_t, BuiltinFuncParam>> builtin_funcs;
std::unique_ptr<Process> proc(Process::alloc(*this, in_pid, JOIN_WAIT_ROOT,
libs, lib_filter, builtin_funcs));
proc->setup();
// Load program from LLVM file.
LlvmAsmLoader loader(*proc);
if (in_type == "IR") {
loader.load_ir_file(pool_path + Convert::vpid2str(in_pid) + ".llvm");
} else if(in_type == "BC") {
loader.load_bc_file(pool_path + Convert::vpid2str(in_pid) + ".llvm");
} else {
throw_error(Error::SERVER_SYS);
}
std::map<std::string, std::string> envs;
// Run virtual machine for bind argument and environment variables.
proc->run(args, envs);
proc->get_thread(proc->root_tid).write();
// Copy output information.
out_root_tid = proc->root_tid;
// Write out data to memory.
proc->proc_memory->write_out();
// Dump and write to file.
picojson::object body;
body.insert(std::make_pair("pid", Convert::vpid2json(in_pid)));
picojson::array js_machine;
{
picojson::object packet;
packet.insert(std::make_pair("cmd", picojson::value(std::string("warp"))));
packet.insert(std::make_pair("pid", Convert::vpid2json(in_pid)));
packet.insert(std::make_pair("root_tid", Convert::vtid2json(proc->root_tid)));
packet.insert(std::make_pair("proc_addr", Convert::vaddr2json(proc->addr)));
packet.insert(std::make_pair("master_device", Convert::devid2json(DEV_SERVER)));
packet.insert(std::make_pair("name", picojson::value(in_name)));
packet.insert(std::make_pair("tid", Convert::vtid2json(proc->root_tid)));
packet.insert(std::make_pair("dst_device", Convert::devid2json(in_dst_device)));
packet.insert(std::make_pair("src_device", Convert::devid2json(in_src_device)));
packet.insert(std::make_pair("src_account", picojson::value(in_src_account)));
js_machine.push_back(picojson::value(picojson::value(packet).serialize()));
}
body.insert(std::make_pair("machine_data", picojson::value(js_machine)));
picojson::array js_memory;
for (auto& it : vmemory.get_space(Convert::vpid2str(in_pid)).pages) {
// Don't export builtin variables.
if (proc->builtin_addrs.find(it.first) != proc->builtin_addrs.end()) continue;
picojson::object packet;
packet.insert(std::make_pair("cmd", picojson::value(std::string("give"))));
packet.insert(std::make_pair("addr", Convert::vaddr2json(it.first)));
packet.insert(std::make_pair("value", Convert::bin2json(it.second.value.get(),
it.second.size)));
packet.insert(std::make_pair("src", Convert::devid2json(DEV_SERVER)));
packet.insert(std::make_pair("dst", Convert::devid2json(in_dst_device)));
packet.insert(std::make_pair("hint", picojson::value(picojson::array())));
js_memory.push_back(picojson::value(picojson::value(packet).serialize()));
}
body.insert(std::make_pair("memory_data", picojson::value(js_memory)));
std::ofstream ofs(pool_path + Convert::vpid2str(in_pid) + ".out");
ofs << picojson::value(body).serialize();
}
};
int main(int argc, char* argv[]) {
// Read stdin and separate by '\0'.
std::string line;
picojson::object result;
while(std::getline(std::cin, line, '\0')) {
// Convert json string to picojson instance.
picojson::value v;
std::istringstream is(line);
std::string err = picojson::parse(v, is);
if (!err.empty()) {
std::cerr << err << std::endl;
exit(EXIT_FAILURE);
}
result = v.get<picojson::object>();
try {
// Make loader.
Loader loader;
// Read information from json.
loader.in_pid = Convert::json2vpid(result.at("pid"));
loader.in_name = result.at("name").get<std::string>();
loader.in_dst_device = Convert::json2devid(result.at("dst_device"));
loader.in_src_device = Convert::json2devid(result.at("src_device"));
loader.in_src_account = result.at("src_account").get<std::string>();
loader.in_type = result.at("type").get<std::string>();
// Convert arguments.
std::vector<std::string> args;
for (auto& it : result.at("args").get<picojson::array>()) {
args.push_back(it.get<std::string>());
}
// Load.
loader.load(args);
// Show result.
result.insert(std::make_pair("result", picojson::value(0.0)));
result.insert(std::make_pair("root_tid", Convert::vtid2json(loader.out_root_tid)));
std::cout << picojson::value(result).serialize() << '\0';
} catch(const Error& ex) {
// Show error information.
result.insert(std::make_pair("result", picojson::value(-1.0)));
result.insert(std::make_pair("reason", picojson::value(std::to_string(ex.reason))));
result.insert(std::make_pair("message", picojson::value(ex.mesg)));
result.insert(std::make_pair("llvm_version",
picojson::value(std::string(LLVM_VERSION_STRING))));
std::cout << picojson::value(result).serialize() << '\0';
} catch(const std::exception& ex) {
// Show error information.
result.insert(std::make_pair("result", picojson::value(-1.0)));
result.insert(std::make_pair("reason", picojson::value(std::to_string(-1))));
result.insert(std::make_pair("message", picojson::value(std::string(ex.what()))));
result.insert(std::make_pair("llvm_version",
picojson::value(std::string(LLVM_VERSION_STRING))));
std::cout << picojson::value(result).serialize() << '\0';
} catch(...) {
int errsv = errno;
// Show error information.
result.insert(std::make_pair("result", picojson::value(-1.0)));
result.insert(std::make_pair("reason", picojson::value(std::to_string(-2))));
result.insert(std::make_pair("message", picojson::value(std::string(std::strerror(errsv)))));
result.insert(std::make_pair("llvm_version",
picojson::value(std::string(LLVM_VERSION_STRING))));
std::cout << picojson::value(result).serialize() << '\0';
}
}
return 0;
}
<commit_msg>fix wrong type string<commit_after>#include <cerrno>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include "lib/picojson.h"
#include "convert.hpp"
#include "definitions.hpp"
#include "error.hpp"
#include "llvm_asm_loader.hpp"
#include "process.hpp"
#include "vmemory.hpp"
using namespace processwarp;
static const std::string pool_path("/tmp/");
/**
* Load program from LLVM-IR and write dump file.
*/
class Loader : public ProcessDelegate, public VMemoryDelegate {
public:
/// Virtual memory for this loader.
VMemory vmemory;
/// Assigned process-id.
vpid_t in_pid;
///
std::string in_name;
///
dev_id_t in_dst_device;
///
dev_id_t in_src_device;
///
std::string in_src_account;
///
std::string in_type;
///
vtid_t out_root_tid;
/**
* Constructor, initialize virtual-memory instance.
*/
Loader() :
vmemory(*this, DEV_SERVER) {
}
/**
*/
std::unique_ptr<VMemory::Accessor> assign_accessor(const vpid_t& pid) override {
assert(!in_pid.empty());
return std::move(vmemory.get_accessor(Convert::vpid2str(pid)));
}
/**
*/
void on_change_thread_set(Process& proc) override {
}
// Call when send memory data to other device.
void send_memory_data(const std::string& name,
const dev_id_t& dev_id,
const std::string& data) override {
print_debug("send memory data (%s@%s):%s\n", name.c_str(), dev_id.c_str(), data.c_str());
assert(false);
}
/**
* Call when memory is update by other node.
* Should not call.
*/
void on_recv_update(const std::string& name, vaddr_t addr) override {
assert(false);
}
/**
*
*/
void load(const std::vector<std::string>& args) {
// Setup virtual-memory.
vmemory.set_loading(Convert::vpid2str(in_pid), true);
// Setup virtual machine.
// Library is empty because don't use in loader.
std::vector<void*> libs;
std::map<std::string, std::string> lib_filter;
std::map<std::string, std::pair<builtin_func_t, BuiltinFuncParam>> builtin_funcs;
std::unique_ptr<Process> proc(Process::alloc(*this, in_pid, JOIN_WAIT_ROOT,
libs, lib_filter, builtin_funcs));
proc->setup();
// Load program from LLVM file.
LlvmAsmLoader loader(*proc);
if (in_type == "LL") {
loader.load_ir_file(pool_path + Convert::vpid2str(in_pid) + ".llvm");
} else if(in_type == "BC") {
loader.load_bc_file(pool_path + Convert::vpid2str(in_pid) + ".llvm");
} else {
throw_error(Error::SERVER_SYS);
}
std::map<std::string, std::string> envs;
// Run virtual machine for bind argument and environment variables.
proc->run(args, envs);
proc->get_thread(proc->root_tid).write();
// Copy output information.
out_root_tid = proc->root_tid;
// Write out data to memory.
proc->proc_memory->write_out();
// Dump and write to file.
picojson::object body;
body.insert(std::make_pair("pid", Convert::vpid2json(in_pid)));
picojson::array js_machine;
{
picojson::object packet;
packet.insert(std::make_pair("cmd", picojson::value(std::string("warp"))));
packet.insert(std::make_pair("pid", Convert::vpid2json(in_pid)));
packet.insert(std::make_pair("root_tid", Convert::vtid2json(proc->root_tid)));
packet.insert(std::make_pair("proc_addr", Convert::vaddr2json(proc->addr)));
packet.insert(std::make_pair("master_device", Convert::devid2json(DEV_SERVER)));
packet.insert(std::make_pair("name", picojson::value(in_name)));
packet.insert(std::make_pair("tid", Convert::vtid2json(proc->root_tid)));
packet.insert(std::make_pair("dst_device", Convert::devid2json(in_dst_device)));
packet.insert(std::make_pair("src_device", Convert::devid2json(in_src_device)));
packet.insert(std::make_pair("src_account", picojson::value(in_src_account)));
js_machine.push_back(picojson::value(picojson::value(packet).serialize()));
}
body.insert(std::make_pair("machine_data", picojson::value(js_machine)));
picojson::array js_memory;
for (auto& it : vmemory.get_space(Convert::vpid2str(in_pid)).pages) {
// Don't export builtin variables.
if (proc->builtin_addrs.find(it.first) != proc->builtin_addrs.end()) continue;
picojson::object packet;
packet.insert(std::make_pair("cmd", picojson::value(std::string("give"))));
packet.insert(std::make_pair("addr", Convert::vaddr2json(it.first)));
packet.insert(std::make_pair("value", Convert::bin2json(it.second.value.get(),
it.second.size)));
packet.insert(std::make_pair("src", Convert::devid2json(DEV_SERVER)));
packet.insert(std::make_pair("dst", Convert::devid2json(in_dst_device)));
packet.insert(std::make_pair("hint", picojson::value(picojson::array())));
js_memory.push_back(picojson::value(picojson::value(packet).serialize()));
}
body.insert(std::make_pair("memory_data", picojson::value(js_memory)));
std::ofstream ofs(pool_path + Convert::vpid2str(in_pid) + ".out");
ofs << picojson::value(body).serialize();
}
};
int main(int argc, char* argv[]) {
// Read stdin and separate by '\0'.
std::string line;
picojson::object result;
while(std::getline(std::cin, line, '\0')) {
// Convert json string to picojson instance.
picojson::value v;
std::istringstream is(line);
std::string err = picojson::parse(v, is);
if (!err.empty()) {
std::cerr << err << std::endl;
exit(EXIT_FAILURE);
}
result = v.get<picojson::object>();
try {
// Make loader.
Loader loader;
// Read information from json.
loader.in_pid = Convert::json2vpid(result.at("pid"));
loader.in_name = result.at("name").get<std::string>();
loader.in_dst_device = Convert::json2devid(result.at("dst_device"));
loader.in_src_device = Convert::json2devid(result.at("src_device"));
loader.in_src_account = result.at("src_account").get<std::string>();
loader.in_type = result.at("type").get<std::string>();
// Convert arguments.
std::vector<std::string> args;
for (auto& it : result.at("args").get<picojson::array>()) {
args.push_back(it.get<std::string>());
}
// Load.
loader.load(args);
// Show result.
result.insert(std::make_pair("result", picojson::value(0.0)));
result.insert(std::make_pair("root_tid", Convert::vtid2json(loader.out_root_tid)));
std::cout << picojson::value(result).serialize() << '\0';
} catch(const Error& ex) {
// Show error information.
result.insert(std::make_pair("result", picojson::value(-1.0)));
result.insert(std::make_pair("reason", picojson::value(std::to_string(ex.reason))));
result.insert(std::make_pair("message", picojson::value(ex.mesg)));
result.insert(std::make_pair("llvm_version",
picojson::value(std::string(LLVM_VERSION_STRING))));
std::cout << picojson::value(result).serialize() << '\0';
} catch(const std::exception& ex) {
// Show error information.
result.insert(std::make_pair("result", picojson::value(-1.0)));
result.insert(std::make_pair("reason", picojson::value(std::to_string(-1))));
result.insert(std::make_pair("message", picojson::value(std::string(ex.what()))));
result.insert(std::make_pair("llvm_version",
picojson::value(std::string(LLVM_VERSION_STRING))));
std::cout << picojson::value(result).serialize() << '\0';
} catch(...) {
int errsv = errno;
// Show error information.
result.insert(std::make_pair("result", picojson::value(-1.0)));
result.insert(std::make_pair("reason", picojson::value(std::to_string(-2))));
result.insert(std::make_pair("message", picojson::value(std::string(std::strerror(errsv)))));
result.insert(std::make_pair("llvm_version",
picojson::value(std::string(LLVM_VERSION_STRING))));
std::cout << picojson::value(result).serialize() << '\0';
}
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 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.
==============================================================================*/
// Op that looks up items from a sparse tensor in an embedding matrix.
// The sparse lookup tensor is represented by three individual tensors: lookup,
// indices, and dense_shape. The representation assume that the corresponding
// dense tensor would satisfy:
// * dense.shape = dense_shape
// * dense[tuple(indices[i])] = lookup[i]
//
// By convention, indices should be sorted.
//
// Options:
// combiner: The reduction op (SUM, MEAN, SQRTN).
// * SUM computes the weighted sum of the embedding results.
// * MEAN is the weighted sum divided by the total weight.
// * SQRTN is the weighted sum divided by the square root of the sum of the
// squares of the weights.
//
// Input:
// Tensor[0]: Ids to lookup, dim.size == 1, int32.
// Tensor[1]: Indices, int32.
// Tensor[2]: Dense shape, int32.
// Tensor[3]: Weights to use for aggregation, float.
// Tensor[4]: Params, a matrix of multi-dimensional items,
// dim.size >= 2, float.
//
// Output:
// A (dense) tensor representing the combined embeddings for the sparse ids.
// For each row in the sparse tensor represented by (lookup, indices, shape)
// the op looks up the embeddings for all ids in that row, multiplies them by
// the corresponding weight, and combines these embeddings as specified in the
// last dimension.
//
// Output.dim = [l0, ... , ln-1, e1, ..., em]
// Where dense_shape == [l0, ..., ln] and Tensor[4].dim == [e0, e1, ..., em]
//
// For instance, if params is a 10x20 matrix and ids, weights are:
//
// [0, 0]: id 1, weight 2.0
// [0, 1]: id 3, weight 0.5
// [1, 0]: id 0, weight 1.0
// [2, 3]: id 1, weight 3.0
//
// with combiner=MEAN, then the output will be a (3, 20) tensor where:
//
// output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
// output[1, :] = (params[0, :] * 1.0) / 1.0
// output[2, :] = (params[1, :] * 3.0) / 3.0
//
// When indices are out of bound, the op will not succeed.
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/tensor_utils.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace {
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 5);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* ids;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &ids));
TF_LITE_ENSURE_EQ(context, NumDimensions(ids), 1);
TF_LITE_ENSURE_EQ(context, ids->type, kTfLiteInt32);
const TfLiteTensor* indices;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &indices));
TF_LITE_ENSURE_EQ(context, NumDimensions(indices), 2);
TF_LITE_ENSURE_EQ(context, indices->type, kTfLiteInt32);
const TfLiteTensor* shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &shape));
TF_LITE_ENSURE_EQ(context, NumDimensions(shape), 1);
TF_LITE_ENSURE_EQ(context, shape->type, kTfLiteInt32);
const TfLiteTensor* weights;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 3, &weights));
TF_LITE_ENSURE_EQ(context, NumDimensions(weights), 1);
TF_LITE_ENSURE_EQ(context, weights->type, kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),
SizeOfDimension(ids, 0));
TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),
SizeOfDimension(weights, 0));
const TfLiteTensor* value;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 4, &value));
TF_LITE_ENSURE(context, NumDimensions(value) >= 2);
// Mark the output as a dynamic tensor.
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);
output->allocation_type = kTfLiteDynamic;
return kTfLiteOk;
}
void FinalizeAggregation(TfLiteCombinerType combiner, int num_elements,
float current_total_weight,
float current_squares_weight, int embedding_size,
float* output) {
if (combiner != kTfLiteCombinerTypeSum && num_elements > 0) {
float multiplier = 1.0;
switch (combiner) {
case kTfLiteCombinerTypeMean:
multiplier = current_total_weight;
break;
case kTfLiteCombinerTypeSqrtn:
multiplier = std::sqrt(current_squares_weight);
break;
default:
break;
}
for (int k = 0; k < embedding_size; k++) {
output[k] /= multiplier;
}
}
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteEmbeddingLookupSparseParams*>(node->builtin_data);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const TfLiteTensor* ids;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &ids));
const TfLiteTensor* indices;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &indices));
const TfLiteTensor* dense_shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &dense_shape));
const TfLiteTensor* weights;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 3, &weights));
const TfLiteTensor* value;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 4, &value));
const int lookup_rank = SizeOfDimension(indices, 1);
const int embedding_rank = NumDimensions(value);
const int num_lookups = SizeOfDimension(ids, 0);
const int num_rows = SizeOfDimension(value, 0);
// The last dimension gets replaced by the embedding.
const int output_rank = (lookup_rank - 1) + (embedding_rank - 1);
// Make sure that the actual dense shape of the sparse tensor represented by
// (loopkup, indices, dense_shape) is consistent.
TF_LITE_ENSURE_EQ(context, SizeOfDimension(dense_shape, 0), lookup_rank);
// Resize output tensor.
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank);
TF_LITE_ENSURE(context, output_shape != nullptr);
int k = 0;
int embedding_size = 1;
int lookup_size = 1;
for (int i = 0; i < lookup_rank - 1; i++, k++) {
const int dim = dense_shape->data.i32[i];
lookup_size *= dim;
output_shape->data[k] = dim;
}
for (int i = 1; i < embedding_rank; i++, k++) {
const int dim = SizeOfDimension(value, i);
embedding_size *= dim;
output_shape->data[k] = dim;
}
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_shape));
const int output_size = lookup_size * embedding_size;
TfLiteTensorRealloc(output_size * sizeof(float), output);
float* output_ptr = GetTensorData<float>(output);
const float* weights_ptr = GetTensorData<float>(weights);
const float* value_ptr = GetTensorData<float>(value);
std::fill_n(output_ptr, output_size, 0.0f);
// Keep track of the current bucket for aggregation/combination.
int current_output_offset = 0;
float current_total_weight = 0.0;
float current_squares_weight = 0.0;
int num_elements = 0;
for (int i = 0; i < num_lookups; i++) {
int idx = ids->data.i32[i];
if (idx >= num_rows || idx < 0) {
context->ReportError(context,
"Embedding Lookup Sparse: index out of bounds. "
"Got %d, and bounds are [0, %d]",
idx, num_rows - 1);
return kTfLiteError;
}
// Check where we need to aggregate.
const int example_indices_offset = i * lookup_rank;
int output_bucket = 0;
int stride = 1;
for (int k = (lookup_rank - 1) - 1; k >= 0; k--) {
output_bucket += indices->data.i32[example_indices_offset + k] * stride;
stride *= dense_shape->data.i32[k];
}
const int output_offset = output_bucket * embedding_size;
// If we are in a new aggregation bucket and the combiner is not the sum,
// go back and finalize the result of the previous bucket.
if (output_offset != current_output_offset) {
FinalizeAggregation(params->combiner, num_elements, current_total_weight,
current_squares_weight, embedding_size,
&output_ptr[current_output_offset]);
// Track next bucket.
num_elements = 0;
current_total_weight = 0.0;
current_squares_weight = 0.0;
current_output_offset = output_offset;
}
// Add element to aggregation.
++num_elements;
const int example_embedding_offset = idx * embedding_size;
const float w = weights_ptr[i];
current_squares_weight += w * w;
current_total_weight += w;
for (int k = 0; k < embedding_size; k++) {
output_ptr[current_output_offset + k] +=
value_ptr[example_embedding_offset + k] * w;
}
}
// Finalize last bucket.
FinalizeAggregation(params->combiner, num_elements, current_total_weight,
current_squares_weight, embedding_size,
&GetTensorData<float>(output)[current_output_offset]);
return kTfLiteOk;
}
} // namespace
TfLiteRegistration* Register_EMBEDDING_LOOKUP_SPARSE() {
static TfLiteRegistration r = {nullptr, nullptr, Prepare, Eval};
return &r;
}
} // namespace builtin
} // namespace ops
} // namespace tflite
<commit_msg>[lite] Check for overflow when creating required bytes.<commit_after>/* Copyright 2017 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.
==============================================================================*/
// Op that looks up items from a sparse tensor in an embedding matrix.
// The sparse lookup tensor is represented by three individual tensors: lookup,
// indices, and dense_shape. The representation assume that the corresponding
// dense tensor would satisfy:
// * dense.shape = dense_shape
// * dense[tuple(indices[i])] = lookup[i]
//
// By convention, indices should be sorted.
//
// Options:
// combiner: The reduction op (SUM, MEAN, SQRTN).
// * SUM computes the weighted sum of the embedding results.
// * MEAN is the weighted sum divided by the total weight.
// * SQRTN is the weighted sum divided by the square root of the sum of the
// squares of the weights.
//
// Input:
// Tensor[0]: Ids to lookup, dim.size == 1, int32.
// Tensor[1]: Indices, int32.
// Tensor[2]: Dense shape, int32.
// Tensor[3]: Weights to use for aggregation, float.
// Tensor[4]: Params, a matrix of multi-dimensional items,
// dim.size >= 2, float.
//
// Output:
// A (dense) tensor representing the combined embeddings for the sparse ids.
// For each row in the sparse tensor represented by (lookup, indices, shape)
// the op looks up the embeddings for all ids in that row, multiplies them by
// the corresponding weight, and combines these embeddings as specified in the
// last dimension.
//
// Output.dim = [l0, ... , ln-1, e1, ..., em]
// Where dense_shape == [l0, ..., ln] and Tensor[4].dim == [e0, e1, ..., em]
//
// For instance, if params is a 10x20 matrix and ids, weights are:
//
// [0, 0]: id 1, weight 2.0
// [0, 1]: id 3, weight 0.5
// [1, 0]: id 0, weight 1.0
// [2, 3]: id 1, weight 3.0
//
// with combiner=MEAN, then the output will be a (3, 20) tensor where:
//
// output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
// output[1, :] = (params[0, :] * 1.0) / 1.0
// output[2, :] = (params[1, :] * 3.0) / 3.0
//
// When indices are out of bound, the op will not succeed.
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/tensor_utils.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace {
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 5);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* ids;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &ids));
TF_LITE_ENSURE_EQ(context, NumDimensions(ids), 1);
TF_LITE_ENSURE_EQ(context, ids->type, kTfLiteInt32);
const TfLiteTensor* indices;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &indices));
TF_LITE_ENSURE_EQ(context, NumDimensions(indices), 2);
TF_LITE_ENSURE_EQ(context, indices->type, kTfLiteInt32);
const TfLiteTensor* shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &shape));
TF_LITE_ENSURE_EQ(context, NumDimensions(shape), 1);
TF_LITE_ENSURE_EQ(context, shape->type, kTfLiteInt32);
const TfLiteTensor* weights;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 3, &weights));
TF_LITE_ENSURE_EQ(context, NumDimensions(weights), 1);
TF_LITE_ENSURE_EQ(context, weights->type, kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),
SizeOfDimension(ids, 0));
TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),
SizeOfDimension(weights, 0));
const TfLiteTensor* value;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 4, &value));
TF_LITE_ENSURE(context, NumDimensions(value) >= 2);
// Mark the output as a dynamic tensor.
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);
output->allocation_type = kTfLiteDynamic;
return kTfLiteOk;
}
void FinalizeAggregation(TfLiteCombinerType combiner, int num_elements,
float current_total_weight,
float current_squares_weight, int embedding_size,
float* output) {
if (combiner != kTfLiteCombinerTypeSum && num_elements > 0) {
float multiplier = 1.0;
switch (combiner) {
case kTfLiteCombinerTypeMean:
multiplier = current_total_weight;
break;
case kTfLiteCombinerTypeSqrtn:
multiplier = std::sqrt(current_squares_weight);
break;
default:
break;
}
for (int k = 0; k < embedding_size; k++) {
output[k] /= multiplier;
}
}
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteEmbeddingLookupSparseParams*>(node->builtin_data);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const TfLiteTensor* ids;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &ids));
const TfLiteTensor* indices;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &indices));
const TfLiteTensor* dense_shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &dense_shape));
const TfLiteTensor* weights;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 3, &weights));
const TfLiteTensor* value;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 4, &value));
const int lookup_rank = SizeOfDimension(indices, 1);
const int embedding_rank = NumDimensions(value);
const int num_lookups = SizeOfDimension(ids, 0);
const int num_rows = SizeOfDimension(value, 0);
// The last dimension gets replaced by the embedding.
const int output_rank = (lookup_rank - 1) + (embedding_rank - 1);
// Make sure that the actual dense shape of the sparse tensor represented by
// (loopkup, indices, dense_shape) is consistent.
TF_LITE_ENSURE_EQ(context, SizeOfDimension(dense_shape, 0), lookup_rank);
// Resize output tensor.
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank);
TF_LITE_ENSURE(context, output_shape != nullptr);
int k = 0;
size_t embedding_size = 1;
size_t lookup_size = 1;
for (int i = 0; i < lookup_rank - 1; i++, k++) {
const size_t dim = dense_shape->data.i32[i];
TF_LITE_ENSURE_MSG(
context,
MultiplyAndCheckOverflow(lookup_size, dim, &lookup_size) == kTfLiteOk,
"Lookup size overflowed.");
output_shape->data[k] = dim;
}
for (int i = 1; i < embedding_rank; i++, k++) {
const size_t dim = SizeOfDimension(value, i);
TF_LITE_ENSURE_MSG(context,
MultiplyAndCheckOverflow(embedding_size, dim,
&embedding_size) == kTfLiteOk,
"Embedding size overflowed.");
output_shape->data[k] = dim;
}
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_shape));
const size_t output_size = lookup_size * embedding_size;
TfLiteTensorRealloc(output_size * sizeof(float), output);
float* output_ptr = GetTensorData<float>(output);
const float* weights_ptr = GetTensorData<float>(weights);
const float* value_ptr = GetTensorData<float>(value);
// Makes sure reallocation was successful.
TF_LITE_ENSURE(context, output_ptr != nullptr);
std::fill_n(output_ptr, output_size, 0.0f);
// Keep track of the current bucket for aggregation/combination.
int current_output_offset = 0;
float current_total_weight = 0.0;
float current_squares_weight = 0.0;
int num_elements = 0;
for (int i = 0; i < num_lookups; i++) {
int idx = ids->data.i32[i];
if (idx >= num_rows || idx < 0) {
context->ReportError(context,
"Embedding Lookup Sparse: index out of bounds. "
"Got %d, and bounds are [0, %d]",
idx, num_rows - 1);
return kTfLiteError;
}
// Check where we need to aggregate.
const int example_indices_offset = i * lookup_rank;
int output_bucket = 0;
int stride = 1;
for (int k = (lookup_rank - 1) - 1; k >= 0; k--) {
output_bucket += indices->data.i32[example_indices_offset + k] * stride;
stride *= dense_shape->data.i32[k];
}
const int output_offset = output_bucket * embedding_size;
// If we are in a new aggregation bucket and the combiner is not the sum,
// go back and finalize the result of the previous bucket.
if (output_offset != current_output_offset) {
FinalizeAggregation(params->combiner, num_elements, current_total_weight,
current_squares_weight, embedding_size,
&output_ptr[current_output_offset]);
// Track next bucket.
num_elements = 0;
current_total_weight = 0.0;
current_squares_weight = 0.0;
current_output_offset = output_offset;
}
// Add element to aggregation.
++num_elements;
const int example_embedding_offset = idx * embedding_size;
const float w = weights_ptr[i];
current_squares_weight += w * w;
current_total_weight += w;
for (int k = 0; k < embedding_size; k++) {
output_ptr[current_output_offset + k] +=
value_ptr[example_embedding_offset + k] * w;
}
}
// Finalize last bucket.
FinalizeAggregation(params->combiner, num_elements, current_total_weight,
current_squares_weight, embedding_size,
&GetTensorData<float>(output)[current_output_offset]);
return kTfLiteOk;
}
} // namespace
TfLiteRegistration* Register_EMBEDDING_LOOKUP_SPARSE() {
static TfLiteRegistration r = {nullptr, nullptr, Prepare, Eval};
return &r;
}
} // namespace builtin
} // namespace ops
} // namespace tflite
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include <memory>
#include <utility> // for std::move
namespace survive
{
template <class T> struct Maybe_Owned;
template <class T, class... Args>
Maybe_Owned<T> make_maybe_owned(Args&&... args) noexcept
{
return Maybe_Owned<T>(new T(std::forward<Args>(args)...), true);
}
template <class T>
struct Maybe_Owned
{
template <class... Args>
Maybe_Owned(Args&&... args) noexcept;
explicit Maybe_Owned(T&& t) noexcept;
/*!
* \brief Construct the maybe owned with a borrowed/unowned ptr.
*
* \note If you are using this constructor to initialize a maybe owned
* of type base with a new pointer to a derived instance, make sure to
* set the second parameter to true. Better yet use make_maybe_owned
* declared above!
*/
/* implicit */ Maybe_Owned(T* t = nullptr, bool owned = false) noexcept;
template <class R>
Maybe_Owned(std::unique_ptr<R>) noexcept;
template <class R>
Maybe_Owned(Maybe_Owned<R>&&) noexcept;
Maybe_Owned(Maybe_Owned const&) noexcept = delete;
template <class R>
Maybe_Owned& operator=(std::unique_ptr<R>) noexcept;
template <class R>
Maybe_Owned& operator=(Maybe_Owned<R>&&) noexcept;
Maybe_Owned& operator=(Maybe_Owned const&&) noexcept = delete;
~Maybe_Owned() noexcept;
void set_owned(T&& t) noexcept;
void set_owned(T const& t) noexcept;
void set_owned(T* t) noexcept;
void set_pointer(T* t, bool owned = false) noexcept;
template <class R, class... Args>
void emplace_owned(Args&&... args) noexcept;
T const* get() const noexcept;
T* get() noexcept;
T&& unwrap() noexcept;
T const* operator->() const noexcept;
T* operator->() noexcept;
T const& operator*() const noexcept;
T& operator*() noexcept;
operator bool() const noexcept;
bool is_owned() const noexcept;
bool is_pointer() const noexcept;
private:
bool owned_ = false;
T* ptr_ = nullptr;
};
template <class T>
template <class... Args>
Maybe_Owned<T>::Maybe_Owned(Args&&... args) noexcept
: owned_(true), ptr_(new T{std::forward<Args>(args)...}) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T&& t) noexcept
: owned_(true), ptr_(new T(std::move(t))) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T* t, bool o) noexcept : owned_(o), ptr_(t) {}
template <class T>
template <class R>
Maybe_Owned<T>::Maybe_Owned(std::unique_ptr<R> ptr) noexcept
: owned_(true), ptr_(ptr.release()) {}
template <class T>
Maybe_Owned<T>::~Maybe_Owned() noexcept
{
if(owned_) delete ptr_;
}
template <class T>
template <class R>
Maybe_Owned<T>::Maybe_Owned(Maybe_Owned<R>&& mo1) noexcept
: owned_(mo1.owned_), ptr_(mo1.ptr_)
{
mo1.owned_ = false;
// We don't need to null the pointer since setting the owned value to false
// should suffice in preventing this other maybe-owned from deleting its
// pointer. Nonetheless:
mo1.ptr_ = nullptr;
}
template <class T>
template <class R>
Maybe_Owned<T>& Maybe_Owned<T>::operator=(std::unique_ptr<R> ptr) noexcept
{
owned_ = true;
ptr_ = ptr.release();
}
template <class T>
template <class R>
Maybe_Owned<T>& Maybe_Owned<T>::operator=(Maybe_Owned<R>&& mo1) noexcept
{
owned_ = mo1.owned_;
ptr_ = mo1.ptr_;
mo1.owned_ = false;
mo1.ptr_ = nullptr;
}
template <class T>
void Maybe_Owned<T>::set_owned(T&& t) noexcept
{
owned_ = true;
ptr_ = new T(std::move(t));
}
template <class T>
void Maybe_Owned<T>::set_owned(T const& t) noexcept
{
owned_ = true;
ptr_ = new T(t);
}
template <class T>
void Maybe_Owned<T>::set_owned(T* t) noexcept
{
owned_ = true;
ptr_ = t;
}
template <class T>
void Maybe_Owned<T>::set_pointer(T* t, bool o) noexcept
{
owned_ = o;
ptr_ = t;
}
template <class T>
template <class R, class... Args>
void Maybe_Owned<T>::emplace_owned(Args&&... args) noexcept
{
owned_ = true;
ptr_ = new R(std::forward<Args>(args)...);
}
template <class T>
T const* Maybe_Owned<T>::get() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::get() noexcept
{
return ptr_;
}
template <class T>
T&& Maybe_Owned<T>::unwrap() noexcept
{
T&& old_t = std::move(*ptr_);
if(owned_)
{
delete ptr_;
}
ptr_ = nullptr;
owned_ = false;
return std::move(old_t);
}
template <class T>
T const* Maybe_Owned<T>::operator->() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::operator->() noexcept
{
return ptr_;
}
template <class T>
T const& Maybe_Owned<T>::operator*() const noexcept
{
return *ptr_;
}
template <class T>
T& Maybe_Owned<T>::operator*() noexcept
{
return *ptr_;
}
template <class T>
bool Maybe_Owned<T>::is_owned() const noexcept
{
return owned_;
}
template <class T>
bool Maybe_Owned<T>::is_pointer() const noexcept
{
return !owned_;
}
template <class T>
Maybe_Owned<T>::operator bool() const noexcept
{
return get();
}
}
<commit_msg>Shit those operator= functions should be returning dereferenced this.<commit_after>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include <memory>
#include <utility> // for std::move
namespace survive
{
template <class T> struct Maybe_Owned;
template <class T, class... Args>
Maybe_Owned<T> make_maybe_owned(Args&&... args) noexcept
{
return Maybe_Owned<T>(new T(std::forward<Args>(args)...), true);
}
template <class T>
struct Maybe_Owned
{
template <class... Args>
Maybe_Owned(Args&&... args) noexcept;
explicit Maybe_Owned(T&& t) noexcept;
/*!
* \brief Construct the maybe owned with a borrowed/unowned ptr.
*
* \note If you are using this constructor to initialize a maybe owned
* of type base with a new pointer to a derived instance, make sure to
* set the second parameter to true. Better yet use make_maybe_owned
* declared above!
*/
/* implicit */ Maybe_Owned(T* t = nullptr, bool owned = false) noexcept;
template <class R>
Maybe_Owned(std::unique_ptr<R>) noexcept;
template <class R>
Maybe_Owned(Maybe_Owned<R>&&) noexcept;
Maybe_Owned(Maybe_Owned const&) noexcept = delete;
template <class R>
Maybe_Owned& operator=(std::unique_ptr<R>) noexcept;
template <class R>
Maybe_Owned& operator=(Maybe_Owned<R>&&) noexcept;
Maybe_Owned& operator=(Maybe_Owned const&&) noexcept = delete;
~Maybe_Owned() noexcept;
void set_owned(T&& t) noexcept;
void set_owned(T const& t) noexcept;
void set_owned(T* t) noexcept;
void set_pointer(T* t, bool owned = false) noexcept;
template <class R, class... Args>
void emplace_owned(Args&&... args) noexcept;
T const* get() const noexcept;
T* get() noexcept;
T&& unwrap() noexcept;
T const* operator->() const noexcept;
T* operator->() noexcept;
T const& operator*() const noexcept;
T& operator*() noexcept;
operator bool() const noexcept;
bool is_owned() const noexcept;
bool is_pointer() const noexcept;
private:
bool owned_ = false;
T* ptr_ = nullptr;
};
template <class T>
template <class... Args>
Maybe_Owned<T>::Maybe_Owned(Args&&... args) noexcept
: owned_(true), ptr_(new T{std::forward<Args>(args)...}) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T&& t) noexcept
: owned_(true), ptr_(new T(std::move(t))) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T* t, bool o) noexcept : owned_(o), ptr_(t) {}
template <class T>
template <class R>
Maybe_Owned<T>::Maybe_Owned(std::unique_ptr<R> ptr) noexcept
: owned_(true), ptr_(ptr.release()) {}
template <class T>
Maybe_Owned<T>::~Maybe_Owned() noexcept
{
if(owned_) delete ptr_;
}
template <class T>
template <class R>
Maybe_Owned<T>::Maybe_Owned(Maybe_Owned<R>&& mo1) noexcept
: owned_(mo1.owned_), ptr_(mo1.ptr_)
{
mo1.owned_ = false;
// We don't need to null the pointer since setting the owned value to false
// should suffice in preventing this other maybe-owned from deleting its
// pointer. Nonetheless:
mo1.ptr_ = nullptr;
}
template <class T>
template <class R>
Maybe_Owned<T>& Maybe_Owned<T>::operator=(std::unique_ptr<R> ptr) noexcept
{
owned_ = true;
ptr_ = ptr.release();
return *this;
}
template <class T>
template <class R>
Maybe_Owned<T>& Maybe_Owned<T>::operator=(Maybe_Owned<R>&& mo1) noexcept
{
owned_ = mo1.owned_;
ptr_ = mo1.ptr_;
mo1.owned_ = false;
mo1.ptr_ = nullptr;
return *this;
}
template <class T>
void Maybe_Owned<T>::set_owned(T&& t) noexcept
{
owned_ = true;
ptr_ = new T(std::move(t));
}
template <class T>
void Maybe_Owned<T>::set_owned(T const& t) noexcept
{
owned_ = true;
ptr_ = new T(t);
}
template <class T>
void Maybe_Owned<T>::set_owned(T* t) noexcept
{
owned_ = true;
ptr_ = t;
}
template <class T>
void Maybe_Owned<T>::set_pointer(T* t, bool o) noexcept
{
owned_ = o;
ptr_ = t;
}
template <class T>
template <class R, class... Args>
void Maybe_Owned<T>::emplace_owned(Args&&... args) noexcept
{
owned_ = true;
ptr_ = new R(std::forward<Args>(args)...);
}
template <class T>
T const* Maybe_Owned<T>::get() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::get() noexcept
{
return ptr_;
}
template <class T>
T&& Maybe_Owned<T>::unwrap() noexcept
{
T&& old_t = std::move(*ptr_);
if(owned_)
{
delete ptr_;
}
ptr_ = nullptr;
owned_ = false;
return std::move(old_t);
}
template <class T>
T const* Maybe_Owned<T>::operator->() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::operator->() noexcept
{
return ptr_;
}
template <class T>
T const& Maybe_Owned<T>::operator*() const noexcept
{
return *ptr_;
}
template <class T>
T& Maybe_Owned<T>::operator*() noexcept
{
return *ptr_;
}
template <class T>
bool Maybe_Owned<T>::is_owned() const noexcept
{
return owned_;
}
template <class T>
bool Maybe_Owned<T>::is_pointer() const noexcept
{
return !owned_;
}
template <class T>
Maybe_Owned<T>::operator bool() const noexcept
{
return get();
}
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2013 Patrick Van Oosterwijck
//
// 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 <node.h>
#include <nan.h>
#include <openssl/evp.h>
using namespace v8;
using namespace node;
// Authentication tag length
#define AUTH_TAG_LEN 16
// Perform GCM mode AES-128 encryption using the provided key, IV, plaintext
// and auth_data buffers, and return an object containing "ciphertext"
// and "auth_tag" buffers.
NAN_METHOD(GcmEncrypt) {
NanScope();
// We want 4 buffer arguments, key needs to be 16 bytes and IV needs to be
// 12 bytes
if (args.Length() < 4 || !Buffer::HasInstance(args[0]) ||
!Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) ||
!Buffer::HasInstance(args[3]) || Buffer::Length(args[0]) != 16 ||
Buffer::Length(args[1]) != 12) {
return NanThrowError("encrypt requires a 16-byte key Buffer, a 12-byte " \
"IV Buffer, a plaintext Buffer and an auth_data " \
"Buffer parameter");
}
// Make a buffer for the ciphertext that is the same size as the
// plaintext, but padded to 16 byte increments
size_t plaintext_len = Buffer::Length(args[2]);
size_t ciphertext_len = (((plaintext_len - 1) / 16) + 1) * 16;
unsigned char *ciphertext = new unsigned char[ciphertext_len];
// Make a authentication tag buffer
unsigned char *auth_tag = new unsigned char[AUTH_TAG_LEN];
// Init OpenSSL interace with 128-bit AES GCM cipher and give it the
// key and IV
int outl;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL,
(unsigned char *)Buffer::Data(args[0]),
(unsigned char *)Buffer::Data(args[1]));
// Pass additional authenticated data
// There is some extra complication here because Buffer::Data seems to
// return NULL for empty buffers, and NULL makes update not work as we
// expect it to. So we force a valid non-NULL pointer for empty buffers.
EVP_EncryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ?
(unsigned char *)Buffer::Data(args[3]) : auth_tag,
Buffer::Length(args[3]));
// Encrypt plaintext
EVP_EncryptUpdate(ctx, ciphertext, &outl,
(unsigned char *)Buffer::Data(args[2]),
Buffer::Length(args[2]));
// Finalize
EVP_EncryptFinal_ex(ctx, ciphertext + outl, &outl);
// Get the authentication tag
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, AUTH_TAG_LEN, auth_tag);
// Free the OpenSSL interface structure
EVP_CIPHER_CTX_free(ctx);
// Create the return buffers and object
// We strip padding from the ciphertext
Local<Object> ciphertext_buf = NanBufferUse((char*)ciphertext,
plaintext_len);
Local<Object> auth_tag_buf = NanBufferUse((char*)auth_tag, AUTH_TAG_LEN);
Local<Object> return_obj = NanNew<Object>();
return_obj->Set(NanNew<String>("ciphertext"), ciphertext_buf);
return_obj->Set(NanNew<String>("auth_tag"), auth_tag_buf);
// Return it
NanReturnValue(return_obj);
}
// Perform GCM mode AES-128 decryption using the provided key, IV, ciphertext,
// auth_data and auth_tag buffers, and return an object containing a "plaintext"
// buffer and an "auth_ok" boolean.
NAN_METHOD(GcmDecrypt) {
NanScope();
// We want 5 buffer arguments, key needs to be 16 bytes, IV needs to be
// 12 bytes, auth_tag needs to be 16 bytes
if (args.Length() < 5 || !Buffer::HasInstance(args[0]) ||
!Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) ||
!Buffer::HasInstance(args[3]) || !Buffer::HasInstance(args[4]) ||
Buffer::Length(args[0]) != 16 || Buffer::Length(args[1]) != 12 ||
Buffer::Length(args[4]) != 16) {
return NanThrowError("decrypt requires a 16-byte key Buffer, a 12-byte " \
"IV Buffer, a ciphertext Buffer, an auth_data " \
"Buffer and a 16-byte auth_tag Buffer parameter");
}
// Make a buffer for the plaintext that is the same size as the
// ciphertext, but padded to 16 byte increments
size_t ciphertext_len = Buffer::Length(args[2]);
size_t plaintext_len = (((ciphertext_len - 1) / 16) + 1) * 16;
unsigned char *plaintext = new unsigned char[plaintext_len];
// Init OpenSSL interace with 128-bit AES GCM cipher and give it the
// key and IV
int outl;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL,
(unsigned char *)Buffer::Data(args[0]),
(unsigned char *)Buffer::Data(args[1]));
// Set the input reference authentication tag
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AUTH_TAG_LEN,
Buffer::Data(args[4]));
// Example showed we needed to do init again
EVP_DecryptInit_ex(ctx, NULL, NULL,
(unsigned char *)Buffer::Data(args[0]),
(unsigned char *)Buffer::Data(args[1]));
// Pass additional authenticated data
// There is some extra complication here because Buffer::Data seems to
// return NULL for empty buffers, and NULL makes update not work as we
// expect it to. So we force a valid non-NULL pointer for empty buffers.
EVP_DecryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ?
(unsigned char *)Buffer::Data(args[3]) : plaintext,
Buffer::Length(args[3]));
// Decrypt ciphertext
EVP_DecryptUpdate(ctx, plaintext, &outl,
(unsigned char *)Buffer::Data(args[2]),
Buffer::Length(args[2]));
// Finalize
bool auth_ok = EVP_DecryptFinal_ex(ctx, plaintext + outl, &outl);
// Free the OpenSSL interface structure
EVP_CIPHER_CTX_free(ctx);
// Create the return buffer and object
// We strip padding from the plaintext
Local<Object> plaintext_buf = NanBufferUse((char*)plaintext,
ciphertext_len);
Local<Object> return_obj = NanNew<Object>();
return_obj->Set(NanNew<String>("plaintext"), plaintext_buf);
return_obj->Set(NanNew<String>("auth_ok"), NanNew<Boolean>(auth_ok));
// Return it
NanReturnValue(return_obj);
}
// Module init function
#if NODE_MODULE_VERSION >= 0x000E
void Init (Handle<Object> exports, Handle<Value> module, void *) {
#else
#if NODE_MODULE_VERSION >= 0x000B
void Init (Handle<Object> exports, Handle<Value> module) {
#else
void Init (Handle<Object> exports) {
#endif
#endif
exports->Set(NanNew<String>("encrypt"),
NanNew<FunctionTemplate>(GcmEncrypt)->GetFunction());
exports->Set(NanNew<String>("decrypt"),
NanNew<FunctionTemplate>(GcmDecrypt)->GetFunction());
}
NODE_MODULE(node_aes_gcm, Init)
<commit_msg>Fix error when ciphertext is empty.<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2013 Patrick Van Oosterwijck
//
// 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 <node.h>
#include <nan.h>
#include <openssl/evp.h>
using namespace v8;
using namespace node;
// Authentication tag length
#define AUTH_TAG_LEN 16
// Perform GCM mode AES-128 encryption using the provided key, IV, plaintext
// and auth_data buffers, and return an object containing "ciphertext"
// and "auth_tag" buffers.
NAN_METHOD(GcmEncrypt) {
NanScope();
// We want 4 buffer arguments, key needs to be 16 bytes and IV needs to be
// 12 bytes
if (args.Length() < 4 || !Buffer::HasInstance(args[0]) ||
!Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) ||
!Buffer::HasInstance(args[3]) || Buffer::Length(args[0]) != 16 ||
Buffer::Length(args[1]) != 12) {
return NanThrowError("encrypt requires a 16-byte key Buffer, a 12-byte " \
"IV Buffer, a plaintext Buffer and an auth_data " \
"Buffer parameter");
}
// Make a buffer for the ciphertext that is the same size as the
// plaintext, but padded to 16 byte increments
size_t plaintext_len = Buffer::Length(args[2]);
size_t ciphertext_len = (((plaintext_len - 1) / 16) + 1) * 16;
unsigned char *ciphertext = new unsigned char[ciphertext_len];
// Make a authentication tag buffer
unsigned char *auth_tag = new unsigned char[AUTH_TAG_LEN];
// Init OpenSSL interace with 128-bit AES GCM cipher and give it the
// key and IV
int outl;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL,
(unsigned char *)Buffer::Data(args[0]),
(unsigned char *)Buffer::Data(args[1]));
// Pass additional authenticated data
// There is some extra complication here because Buffer::Data seems to
// return NULL for empty buffers, and NULL makes update not work as we
// expect it to. So we force a valid non-NULL pointer for empty buffers.
EVP_EncryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ?
(unsigned char *)Buffer::Data(args[3]) : auth_tag,
Buffer::Length(args[3]));
// Encrypt plaintext
EVP_EncryptUpdate(ctx, ciphertext, &outl,
(unsigned char *)Buffer::Data(args[2]),
Buffer::Length(args[2]));
// Finalize
EVP_EncryptFinal_ex(ctx, ciphertext + outl, &outl);
// Get the authentication tag
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, AUTH_TAG_LEN, auth_tag);
// Free the OpenSSL interface structure
EVP_CIPHER_CTX_free(ctx);
// Create the return buffers and object
// We strip padding from the ciphertext
Local<Object> ciphertext_buf = NanBufferUse((char*)ciphertext,
plaintext_len);
Local<Object> auth_tag_buf = NanBufferUse((char*)auth_tag, AUTH_TAG_LEN);
Local<Object> return_obj = NanNew<Object>();
return_obj->Set(NanNew<String>("ciphertext"), ciphertext_buf);
return_obj->Set(NanNew<String>("auth_tag"), auth_tag_buf);
// Return it
NanReturnValue(return_obj);
}
// Perform GCM mode AES-128 decryption using the provided key, IV, ciphertext,
// auth_data and auth_tag buffers, and return an object containing a "plaintext"
// buffer and an "auth_ok" boolean.
NAN_METHOD(GcmDecrypt) {
NanScope();
// We want 5 buffer arguments, key needs to be 16 bytes, IV needs to be
// 12 bytes, auth_tag needs to be 16 bytes
if (args.Length() < 5 || !Buffer::HasInstance(args[0]) ||
!Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) ||
!Buffer::HasInstance(args[3]) || !Buffer::HasInstance(args[4]) ||
Buffer::Length(args[0]) != 16 || Buffer::Length(args[1]) != 12 ||
Buffer::Length(args[4]) != 16) {
return NanThrowError("decrypt requires a 16-byte key Buffer, a 12-byte " \
"IV Buffer, a ciphertext Buffer, an auth_data " \
"Buffer and a 16-byte auth_tag Buffer parameter");
}
// Make a buffer for the plaintext that is the same size as the
// ciphertext, but padded to 16 byte increments
size_t ciphertext_len = Buffer::Length(args[2]);
size_t plaintext_len = (((ciphertext_len - 1) / 16) + 1) * 16;
unsigned char *plaintext = new unsigned char[plaintext_len];
// Init OpenSSL interace with 128-bit AES GCM cipher and give it the
// key and IV
int outl;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL,
(unsigned char *)Buffer::Data(args[0]),
(unsigned char *)Buffer::Data(args[1]));
// Set the input reference authentication tag
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AUTH_TAG_LEN,
Buffer::Data(args[4]));
// Example showed we needed to do init again
EVP_DecryptInit_ex(ctx, NULL, NULL,
(unsigned char *)Buffer::Data(args[0]),
(unsigned char *)Buffer::Data(args[1]));
// Pass additional authenticated data
// There is some extra complication here because Buffer::Data seems to
// return NULL for empty buffers, and NULL makes update not work as we
// expect it to. So we force a valid non-NULL pointer for empty buffers.
EVP_DecryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ?
(unsigned char *)Buffer::Data(args[3]) : plaintext,
Buffer::Length(args[3]));
// Decrypt ciphertext
EVP_DecryptUpdate(ctx, plaintext, &outl,
Buffer::Length(args[2]) ?
(unsigned char *)Buffer::Data(args[2]) : plaintext,
Buffer::Length(args[2]));
// Finalize
bool auth_ok = EVP_DecryptFinal_ex(ctx, plaintext + outl, &outl);
// Free the OpenSSL interface structure
EVP_CIPHER_CTX_free(ctx);
// Create the return buffer and object
// We strip padding from the plaintext
Local<Object> plaintext_buf = NanBufferUse((char*)plaintext,
ciphertext_len);
Local<Object> return_obj = NanNew<Object>();
return_obj->Set(NanNew<String>("plaintext"), plaintext_buf);
return_obj->Set(NanNew<String>("auth_ok"), NanNew<Boolean>(auth_ok));
// Return it
NanReturnValue(return_obj);
}
// Module init function
#if NODE_MODULE_VERSION >= 0x000E
void Init (Handle<Object> exports, Handle<Value> module, void *) {
#else
#if NODE_MODULE_VERSION >= 0x000B
void Init (Handle<Object> exports, Handle<Value> module) {
#else
void Init (Handle<Object> exports) {
#endif
#endif
exports->Set(NanNew<String>("encrypt"),
NanNew<FunctionTemplate>(GcmEncrypt)->GetFunction());
exports->Set(NanNew<String>("decrypt"),
NanNew<FunctionTemplate>(GcmDecrypt)->GetFunction());
}
NODE_MODULE(node_aes_gcm, Init)
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/**
** \file object/lobby.cc
** \brief Creation of the Urbi object lobby.
*/
#include <libport/cassert>
#include <kernel/uconnection.hh>
#include <kernel/ughostconnection.hh>
#include <kernel/userver.hh>
#include <urbi/object/lobby.hh>
#include <urbi/object/object.hh>
#include <urbi/object/string.hh>
#include <object/symbols.hh>
#include <urbi/object/tag.hh>
#include <urbi/runner/raise.hh>
#include <runner/runner.hh>
#include <runner/shell.hh>
namespace urbi
{
namespace object
{
Lobby::Lobby(connection_type* c)
: connection_(c)
{
// Only the Lobby prototype is expected to have a null connection.
aver(!proto || c);
proto_add(proto ? rObject(proto) : Object::proto);
if (c)
{
// Initialize the connection tag used to reference local
// variables.
slot_set(SYMBOL(connectionTag), new Tag());
tag_get()->name_set(libport::Symbol::fresh_string("Lobby"));
}
}
Lobby::Lobby(rLobby)
: connection_(0)
{
RAISE("`Lobby' objects cannot be cloned");
}
URBI_CXX_OBJECT_INIT(Lobby)
: connection_(0)
{
bind(SYMBOL(send),
static_cast<void (Lobby::*)(const std::string&)>(&Lobby::send));
bind(SYMBOL(send),
static_cast<void (Lobby::*)(const std::string&, const std::string&)>
(&Lobby::send));
#define DECLARE(Name) \
bind(SYMBOL_(Name), &Lobby::Name)
DECLARE(binaryMode);
DECLARE(bytesSent);
DECLARE(bytesReceived);
DECLARE(create);
DECLARE(lobby);
DECLARE(quit);
DECLARE(receive);
DECLARE(write);
#undef DECLARE
bind(SYMBOL(instances), &Lobby::instances_get);
}
size_t
Lobby::bytesSent() const
{
if (!connection_)
RAISE("Lobby is not connected");
return connection_->bytes_sent();
}
size_t
Lobby::bytesReceived() const
{
if (!connection_)
RAISE("Lobby is not connected");
return connection_->bytes_received();
}
rLobby
Lobby::create()
{
return
(new kernel::UGhostConnection(*kernel::urbiserver, true))
->lobby_get();
}
Lobby::connection_type&
Lobby::connection_get()
{
return *connection_;
}
const Lobby::connection_type&
Lobby::connection_get() const
{
return *connection_;
}
void
Lobby::disconnect()
{
connection_ = 0;
call(SYMBOL(handleDisconnect));
}
rLobby
Lobby::lobby()
{
// Don't return "this", as any "Lobby.lobby" must return the
// lobby of the connection, not the target of the ".lobby" call.
return ::kernel::runner().lobby_get();
}
#define REQUIRE_DERIVATIVE_AND_CONNECTION() \
do { \
if (proto == this) \
RAISE("must be called on Lobby derivative"); \
if (!connection_) \
return; \
} while (false)
void
Lobby::quit()
{
REQUIRE_DERIVATIVE_AND_CONNECTION();
connection_->close();
}
void
Lobby::send(const std::string& data)
{
send(data, "");
}
void
Lobby::send(const std::string& data, const std::string& tag)
{
REQUIRE_DERIVATIVE_AND_CONNECTION();
connection_->send((data + "\n").c_str(), data.length() + 1, tag.c_str());
}
void
Lobby::write(const std::string& data)
{
REQUIRE_DERIVATIVE_AND_CONNECTION();
connection_->send_queue(data.c_str(), data.size());
connection_->flush();
}
void
Lobby::receive(const std::string& s)
{
connection_->received(s);
}
void
Lobby::binaryMode(bool m, const std::string& tag)
{
runner::Shell& s = dynamic_cast<runner::Shell&>(::kernel::runner());
s.setSerializationMode(m, tag);
}
} // namespace object
}
<commit_msg>Lobby: Use C++ wrappers.<commit_after>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/**
** \file object/lobby.cc
** \brief Creation of the Urbi object lobby.
*/
#include <libport/cassert>
#include <kernel/uconnection.hh>
#include <kernel/ughostconnection.hh>
#include <kernel/userver.hh>
#include <urbi/object/lobby.hh>
#include <urbi/object/object.hh>
#include <urbi/object/string.hh>
#include <object/symbols.hh>
#include <urbi/object/tag.hh>
#include <urbi/runner/raise.hh>
#include <runner/runner.hh>
#include <runner/shell.hh>
namespace urbi
{
namespace object
{
Lobby::Lobby(connection_type* c)
: connection_(c)
{
// Only the Lobby prototype is expected to have a null connection.
aver(!proto || c);
proto_add(proto ? rObject(proto) : Object::proto);
if (c)
{
// Initialize the connection tag used to reference local
// variables.
slot_set(SYMBOL(connectionTag), new Tag());
tag_get()->name_set(libport::Symbol::fresh_string("Lobby"));
}
}
Lobby::Lobby(rLobby)
: connection_(0)
{
RAISE("`Lobby' objects cannot be cloned");
}
URBI_CXX_OBJECT_INIT(Lobby)
: connection_(0)
{
bind(SYMBOL(send),
static_cast<void (Lobby::*)(const std::string&)>(&Lobby::send));
bind(SYMBOL(send),
static_cast<void (Lobby::*)(const std::string&, const std::string&)>
(&Lobby::send));
#define DECLARE(Name) \
bind(SYMBOL_(Name), &Lobby::Name)
DECLARE(binaryMode);
DECLARE(bytesSent);
DECLARE(bytesReceived);
DECLARE(create);
DECLARE(lobby);
DECLARE(quit);
DECLARE(receive);
DECLARE(write);
#undef DECLARE
bind(SYMBOL(instances), &Lobby::instances_get);
}
size_t
Lobby::bytesSent() const
{
if (!connection_)
RAISE("Lobby is not connected");
return connection_->bytes_sent();
}
size_t
Lobby::bytesReceived() const
{
if (!connection_)
RAISE("Lobby is not connected");
return connection_->bytes_received();
}
rLobby
Lobby::create()
{
return
(new kernel::UGhostConnection(*kernel::urbiserver, true))
->lobby_get();
}
Lobby::connection_type&
Lobby::connection_get()
{
return *connection_;
}
const Lobby::connection_type&
Lobby::connection_get() const
{
return *connection_;
}
void
Lobby::disconnect()
{
connection_ = 0;
call(SYMBOL(handleDisconnect));
}
rLobby
Lobby::lobby()
{
// Don't return "this", as any "Lobby.lobby" must return the
// lobby of the connection, not the target of the ".lobby" call.
return ::kernel::runner().lobby_get();
}
#define REQUIRE_DERIVATIVE_AND_CONNECTION() \
do { \
if (proto == this) \
RAISE("must be called on Lobby derivative"); \
if (!connection_) \
return; \
} while (false)
void
Lobby::quit()
{
REQUIRE_DERIVATIVE_AND_CONNECTION();
connection_->close();
}
void
Lobby::send(const std::string& data)
{
send(data, "");
}
void
Lobby::send(const std::string& data, const std::string& tag)
{
REQUIRE_DERIVATIVE_AND_CONNECTION();
connection_->send(data + "\n", tag.c_str());
}
void
Lobby::write(const std::string& data)
{
REQUIRE_DERIVATIVE_AND_CONNECTION();
connection_->send_queue(data.c_str(), data.size());
connection_->flush();
}
void
Lobby::receive(const std::string& s)
{
connection_->received(s);
}
void
Lobby::binaryMode(bool m, const std::string& tag)
{
runner::Shell& s = dynamic_cast<runner::Shell&>(::kernel::runner());
s.setSerializationMode(m, tag);
}
} // namespace object
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cow_wrapper.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: thb $ $Date: 2006-01-25 16:14:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_O3TL_COW_WRAPPER_HXX
#define INCLUDED_O3TL_COW_WRAPPER_HXX
#include <osl/interlck.h>
#include <algorithm>
#include <boost/utility.hpp>
#include <boost/checked_delete.hpp>
namespace o3tl
{
/** Copy-on-write wrapper.
This template provides copy-on-write semantics for the wrapped
type: when copying, the operation is performed shallow,
i.e. different cow_wrapper objects share the same underlying
instance. Only when accessing the underlying object via
non-const methods, a unique copy is provided.
The type parameter <code>T</code> must satisfy the following
requirements: it must be default-constructible, copyable (it
need not be assignable), and be of non-reference type. Note
that, despite the fact that this template provides access to
the wrapped type via pointer-like methods
(<code>operator->()</code> and <code>operator*()</code>), it does
<em>not</em> work like e.g. the boost pointer wrappers
(shared_ptr, scoped_ptr, etc.). Internally, the cow_wrapper
holds a by-value instance of the wrapped object. This is to
avoid one additional heap allocation, and providing access via
<code>operator->()</code>/<code>operator*()</code> is because
<code>operator.()</code> cannot be overridden.
Regarding thread safety: this wrapper is <em>not</em>
thread-safe per se, because cow_wrapper has no way of
syncronizing the potentially many different cow_wrapper
instances, that reference a single shared value_type
instance. Accessing a thread-safe pointee through multiple
cow_wrapper instances might be thread-safe, if the individual
pointee methods are thread-safe, <em>including</em> pointee's
copy constructor. Any wrapped object that needs external
synchronisation (e.g. via an external mutex, which arbitrates
access to object methods, and can be held across multiple
object method calls) cannot easily be dealt with in a
thread-safe way, because, as noted, objects are shared behind
the client's back.
@attention if one wants to use the pimpl idiom together with
cow_wrapper (i.e. put an opaque type into the cow_wrapper),
then <em>all<em> methods in the surrounding class needs to be
non-inline (<em>including</em> destructor, copy constructor
and assignment operator).
@example
<pre>
class cow_wrapper_client_impl;
class cow_wrapper_client
{
public:
cow_wrapper_client();
cow_wrapper_client( const cow_wrapper_client& );
~cow_wrapper_client();
cow_wrapper_client& operator=( const cow_wrapper_client& );
void modify( int nVal );
int queryUnmodified() const;
private:
otl::cow_wrapper< cow_wrapper_client_impl > maImpl;
};
</pre>
and the implementation file would look like this:
<pre>
class cow_wrapper_client_impl
{
public:
void setValue( int nVal ) { mnValue = nVal; }
int getValue() const { return mnValue; }
private:
int mnValue;
}
cow_wrapper_client::cow_wrapper_client() :
maImpl()
{
}
cow_wrapper_client::cow_wrapper_client( const cow_wrapper_client& rSrc ) :
maImpl( rSrc.maImpl )
{
}
cow_wrapper_client::~cow_wrapper_client()
{
}
cow_wrapper_client& cow_wrapper_client::operator=( const cow_wrapper_client& rSrc )
{
maImpl = rSrc.maImpl;
}
void cow_wrapper_client::modify( int nVal )
{
maImpl->setValue( nVal );
}
void cow_wrapper_client::queryUnmodified() const
{
return maImpl->getValue();
}
</pre>
*/
template<typename T> class cow_wrapper
{
/** shared value object - gets copied before cow_wrapper hands
out a non-const reference to it
*/
struct impl_t : private boost::noncopyable
{
impl_t() :
m_value(),
m_ref_count(1)
{
}
explicit impl_t( const T& v ) :
m_value(v),
m_ref_count(1)
{
}
T m_value;
oslInterlockedCount m_ref_count;
};
void release()
{
if( osl_decrementInterlockedCount(&m_pimpl->m_ref_count) == 0 )
boost::checked_delete(m_pimpl), m_pimpl=0;
}
public:
typedef T element_type;
typedef T value_type;
typedef T* pointer;
/** Default-construct wrapped type instance
*/
cow_wrapper() :
m_pimpl( new impl_t() )
{
}
/** Copy-construct wrapped type instance from given object
*/
explicit cow_wrapper( const value_type& r ) :
m_pimpl( new impl_t(r) )
{
}
/** Shallow-copy given cow_wrapper
*/
explicit cow_wrapper( const cow_wrapper& rSrc ) : // nothrow
m_pimpl( rSrc.m_pimpl )
{
osl_incrementInterlockedCount( &m_pimpl->m_ref_count );
}
~cow_wrapper() // nothrow, if ~T does not throw
{
release();
}
/// now sharing rSrc cow_wrapper instance with us
cow_wrapper& operator=( const cow_wrapper& rSrc ) // nothrow
{
// this already guards against self-assignment
osl_incrementInterlockedCount( &rSrc.m_pimpl->m_ref_count );
release();
m_pimpl = rSrc.m_pimpl;
return *this;
}
/// unshare with any other cow_wrapper instance
value_type& make_unique()
{
if( m_pimpl->m_ref_count > 1 )
{
impl_t* pimpl = new impl_t(m_pimpl->m_value);
release();
m_pimpl = pimpl;
}
return m_pimpl->m_value;
}
/// true, if not shared with any other cow_wrapper instance
bool is_unique() const // nothrow
{
return m_pimpl->m_ref_count == 1;
}
/// return number of shared instances (1 for unique object)
oslInterlockedCount use_count() const // nothrow
{
return m_pimpl->m_ref_count;
}
void swap(cow_wrapper& r) // never throws
{
std::swap(m_pimpl, r.m_pimpl);
}
pointer operator->() { return &make_unique(); }
value_type& operator*() { return make_unique(); }
const pointer operator->() const { return &m_pimpl->m_value; }
const value_type& operator*() const { return m_pimpl->m_value; }
pointer get() { return &make_unique(); }
const pointer get() const { return &m_pimpl->m_value; }
/// true, if both cow_wrapper internally share the same object
bool same_object( const cow_wrapper& rOther ) const
{
return rOther.m_pimpl == m_pimpl;
}
private:
impl_t* m_pimpl;
};
template<class A, class B> inline bool operator==( const cow_wrapper<A>& a,
const cow_wrapper<B>& b )
{
return *a == *b;
}
template<class A, class B> inline bool operator!=( const cow_wrapper<A>& a,
const cow_wrapper<B>& b )
{
return *a != *b;
}
template<class A, class B> inline bool operator<( const cow_wrapper<A>& a,
const cow_wrapper<B>& b )
{
return *a < *b;
}
template<class T> inline void swap( cow_wrapper<T>& a,
cow_wrapper<T>& b )
{
a.swap(b);
}
// to enable boost::mem_fn on cow_wrapper
template<class T> inline T * get_pointer( const cow_wrapper<T>& r )
{
return r.get();
}
}
#endif /* INCLUDED_O3TL_COW_WRAPPER_HXX */
<commit_msg>#128078# Removed unused typedef; corrected example code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cow_wrapper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: thb $ $Date: 2006-03-17 16:50:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_O3TL_COW_WRAPPER_HXX
#define INCLUDED_O3TL_COW_WRAPPER_HXX
#include <osl/interlck.h>
#include <algorithm>
#include <boost/utility.hpp>
#include <boost/checked_delete.hpp>
namespace o3tl
{
/** Copy-on-write wrapper.
This template provides copy-on-write semantics for the wrapped
type: when copying, the operation is performed shallow,
i.e. different cow_wrapper objects share the same underlying
instance. Only when accessing the underlying object via
non-const methods, a unique copy is provided.
The type parameter <code>T</code> must satisfy the following
requirements: it must be default-constructible, copyable (it
need not be assignable), and be of non-reference type. Note
that, despite the fact that this template provides access to
the wrapped type via pointer-like methods
(<code>operator->()</code> and <code>operator*()</code>), it does
<em>not</em> work like e.g. the boost pointer wrappers
(shared_ptr, scoped_ptr, etc.). Internally, the cow_wrapper
holds a by-value instance of the wrapped object. This is to
avoid one additional heap allocation, and providing access via
<code>operator->()</code>/<code>operator*()</code> is because
<code>operator.()</code> cannot be overridden.
Regarding thread safety: this wrapper is <em>not</em>
thread-safe per se, because cow_wrapper has no way of
syncronizing the potentially many different cow_wrapper
instances, that reference a single shared value_type
instance. Accessing a thread-safe pointee through multiple
cow_wrapper instances might be thread-safe, if the individual
pointee methods are thread-safe, <em>including</em> pointee's
copy constructor. Any wrapped object that needs external
synchronisation (e.g. via an external mutex, which arbitrates
access to object methods, and can be held across multiple
object method calls) cannot easily be dealt with in a
thread-safe way, because, as noted, objects are shared behind
the client's back.
@attention if one wants to use the pimpl idiom together with
cow_wrapper (i.e. put an opaque type into the cow_wrapper),
then <em>all<em> methods in the surrounding class needs to be
non-inline (<em>including</em> destructor, copy constructor
and assignment operator).
@example
<pre>
class cow_wrapper_client_impl;
class cow_wrapper_client
{
public:
cow_wrapper_client();
cow_wrapper_client( const cow_wrapper_client& );
~cow_wrapper_client();
cow_wrapper_client& operator=( const cow_wrapper_client& );
void modify( int nVal );
int queryUnmodified() const;
private:
otl::cow_wrapper< cow_wrapper_client_impl > maImpl;
};
</pre>
and the implementation file would look like this:
<pre>
class cow_wrapper_client_impl
{
public:
void setValue( int nVal ) { mnValue = nVal; }
int getValue() const { return mnValue; }
private:
int mnValue;
}
cow_wrapper_client::cow_wrapper_client() :
maImpl()
{
}
cow_wrapper_client::cow_wrapper_client( const cow_wrapper_client& rSrc ) :
maImpl( rSrc.maImpl )
{
}
cow_wrapper_client::~cow_wrapper_client()
{
}
cow_wrapper_client& cow_wrapper_client::operator=( const cow_wrapper_client& rSrc )
{
maImpl = rSrc.maImpl;
return *this;
}
void cow_wrapper_client::modify( int nVal )
{
maImpl->setValue( nVal );
}
void cow_wrapper_client::queryUnmodified() const
{
return maImpl->getValue();
}
</pre>
*/
template<typename T> class cow_wrapper
{
/** shared value object - gets copied before cow_wrapper hands
out a non-const reference to it
*/
struct impl_t : private boost::noncopyable
{
impl_t() :
m_value(),
m_ref_count(1)
{
}
explicit impl_t( const T& v ) :
m_value(v),
m_ref_count(1)
{
}
T m_value;
oslInterlockedCount m_ref_count;
};
void release()
{
if( osl_decrementInterlockedCount(&m_pimpl->m_ref_count) == 0 )
boost::checked_delete(m_pimpl), m_pimpl=0;
}
public:
typedef T value_type;
typedef T* pointer;
/** Default-construct wrapped type instance
*/
cow_wrapper() :
m_pimpl( new impl_t() )
{
}
/** Copy-construct wrapped type instance from given object
*/
explicit cow_wrapper( const value_type& r ) :
m_pimpl( new impl_t(r) )
{
}
/** Shallow-copy given cow_wrapper
*/
explicit cow_wrapper( const cow_wrapper& rSrc ) : // nothrow
m_pimpl( rSrc.m_pimpl )
{
osl_incrementInterlockedCount( &m_pimpl->m_ref_count );
}
~cow_wrapper() // nothrow, if ~T does not throw
{
release();
}
/// now sharing rSrc cow_wrapper instance with us
cow_wrapper& operator=( const cow_wrapper& rSrc ) // nothrow
{
// this already guards against self-assignment
osl_incrementInterlockedCount( &rSrc.m_pimpl->m_ref_count );
release();
m_pimpl = rSrc.m_pimpl;
return *this;
}
/// unshare with any other cow_wrapper instance
value_type& make_unique()
{
if( m_pimpl->m_ref_count > 1 )
{
impl_t* pimpl = new impl_t(m_pimpl->m_value);
release();
m_pimpl = pimpl;
}
return m_pimpl->m_value;
}
/// true, if not shared with any other cow_wrapper instance
bool is_unique() const // nothrow
{
return m_pimpl->m_ref_count == 1;
}
/// return number of shared instances (1 for unique object)
oslInterlockedCount use_count() const // nothrow
{
return m_pimpl->m_ref_count;
}
void swap(cow_wrapper& r) // never throws
{
std::swap(m_pimpl, r.m_pimpl);
}
pointer operator->() { return &make_unique(); }
value_type& operator*() { return make_unique(); }
const pointer operator->() const { return &m_pimpl->m_value; }
const value_type& operator*() const { return m_pimpl->m_value; }
pointer get() { return &make_unique(); }
const pointer get() const { return &m_pimpl->m_value; }
/// true, if both cow_wrapper internally share the same object
bool same_object( const cow_wrapper& rOther ) const
{
return rOther.m_pimpl == m_pimpl;
}
private:
impl_t* m_pimpl;
};
template<class A, class B> inline bool operator==( const cow_wrapper<A>& a,
const cow_wrapper<B>& b )
{
return *a == *b;
}
template<class A, class B> inline bool operator!=( const cow_wrapper<A>& a,
const cow_wrapper<B>& b )
{
return *a != *b;
}
template<class A, class B> inline bool operator<( const cow_wrapper<A>& a,
const cow_wrapper<B>& b )
{
return *a < *b;
}
template<class T> inline void swap( cow_wrapper<T>& a,
cow_wrapper<T>& b )
{
a.swap(b);
}
// to enable boost::mem_fn on cow_wrapper
template<class T> inline T * get_pointer( const cow_wrapper<T>& r )
{
return r.get();
}
}
#endif /* INCLUDED_O3TL_COW_WRAPPER_HXX */
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2016 - 2017)
// Rene Milk (2016 - 2017)
#ifndef DUNE_GDT_LOCAL_DOF_VECTOR_HH
#define DUNE_GDT_LOCAL_DOF_VECTOR_HH
#include <dune/xt/common/vector.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/bound-object.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
namespace Dune {
namespace GDT {
namespace internal {
// forward, required for the default in the declaration of ConstLocalDofVector
template <class Vector, class GridView>
class ConstLocalDofVectorTraits;
} // namespace internal
// forwards, required for the traits
template <class Vector, class GridView, class Traits = internal::ConstLocalDofVectorTraits<Vector, GridView>>
class ConstLocalDofVector;
template <class Vector, class GridView>
class LocalDofVector;
namespace internal {
template <class Vector, class GridView>
class ConstLocalDofVectorTraits
{
static_assert(XT::LA::is_vector<Vector>::value, "");
public:
using derived_type = ConstLocalDofVector<Vector, GridView>;
using ScalarType = typename Vector::ScalarType;
using RealType = typename Vector::RealType;
};
template <class Vector, class GridView>
class LocalDofVectorTraits
{
static_assert(XT::LA::is_vector<Vector>::value, "");
public:
using derived_type = LocalDofVector<Vector, GridView>;
using ScalarType = typename Vector::ScalarType;
using RealType = typename Vector::RealType;
};
} // namespace internal
/**
* \note Since all implementations of XT::LA::VectorInterface are assumed to be thread safe, no special care needs to be
* taken here.
*/
template <class Vector, class GridView, class Traits>
class ConstLocalDofVector : public XT::LA::VectorInterface<Traits>,
public XT::Grid::ElementBoundObject<XT::Grid::extract_entity_t<GridView>>
{
using ThisType = ConstLocalDofVector<Vector, GridView, Traits>;
using BaseType = XT::LA::VectorInterface<Traits>;
public:
using typename BaseType::ScalarType;
using VectorType = Vector;
using MapperType = MapperInterface<GridView>;
using typename XT::Grid::ElementBoundObject<XT::Grid::extract_entity_t<GridView>>::ElementType;
ConstLocalDofVector(const MapperType& mapper, const VectorType& global_vector)
: mapper_(mapper)
, global_vector_(global_vector)
, global_DoF_indices_(mapper_.max_local_size())
, size_(0)
{
}
ConstLocalDofVector(const ThisType& other) = default;
ConstLocalDofVector(ThisType&& source) = default;
protected:
void post_bind(const ElementType& ele)
{
mapper_.global_indices(ele, global_DoF_indices_);
size_ = mapper_.local_size(ele);
DUNE_THROW_IF(global_DoF_indices_.size() < size_,
Exceptions::dof_vector_error,
"This must not happen, the mapper is broken!");
}
public:
size_t size() const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
return size_;
}
void add_to_entry(const size_t /*ii*/, const ScalarType& /*value*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
}
void set_entry(const size_t /*ii*/, const ScalarType& /*value*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
}
ScalarType get_entry(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_.get_entry(global_DoF_indices_[ii]);
}
protected:
ScalarType& get_unchecked_ref(const size_t /*ii*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
return dummy_scalar_to_silence_the_warning_;
}
const ScalarType& get_unchecked_ref(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
// This is not optimal, but global_vector_.get_unchecked_ref is protected.
return global_vector_[global_DoF_indices_[ii]];
}
public:
ScalarType& operator[](const size_t /*ii*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
return dummy_scalar_to_silence_the_warning_;
}
const ScalarType& operator[](const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
protected:
friend BaseType; // To allow access to get_unchecked_ref().
const MapperType& mapper_;
private:
const VectorType& global_vector_;
protected:
DynamicVector<size_t> global_DoF_indices_;
size_t size_;
private:
ScalarType dummy_scalar_to_silence_the_warning_;
}; // class ConstLocalDofVector
template <class Vector, class GridView>
class LocalDofVector : public ConstLocalDofVector<Vector, GridView, internal::LocalDofVectorTraits<Vector, GridView>>
{
using ThisType = LocalDofVector<Vector, GridView>;
using BaseType = ConstLocalDofVector<Vector, GridView, internal::LocalDofVectorTraits<Vector, GridView>>;
public:
using typename BaseType::ScalarType;
using VectorType = Vector;
using MapperType = MapperInterface<GridView>;
LocalDofVector(const MapperType& mapper, VectorType& global_vector)
: BaseType(mapper, global_vector)
, global_vector_(global_vector)
{
}
LocalDofVector(const ThisType&) = default;
LocalDofVector(ThisType&&) = default;
void add_to_entry(const size_t ii, const ScalarType& value)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
global_vector_.add_to_entry(global_DoF_indices_[ii], value);
}
void set_entry(const size_t ii, const ScalarType& value)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
global_vector_.set_entry(global_DoF_indices_[ii], value);
}
ScalarType get_entry(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_.get_entry(global_DoF_indices_[ii]);
}
protected:
ScalarType& get_unchecked_ref(const size_t ii)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
const ScalarType& get_unchecked_ref(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
public:
ScalarType& operator[](const size_t ii)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
const ScalarType& operator[](const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
private:
// To allow access to get_unchecked_ref().
friend XT::LA::VectorInterface<internal::LocalDofVectorTraits<Vector, GridView>>;
using BaseType::mapper_;
VectorType& global_vector_;
using BaseType::global_DoF_indices_;
using BaseType::size_;
}; // class LocalDofVector
} // namespace GDT
namespace XT {
namespace Common {
template <class Vector, class GridView, class Traits>
struct VectorAbstraction<GDT::ConstLocalDofVector<Vector, GridView, Traits>>
: public LA::internal::VectorAbstractionBase<GDT::ConstLocalDofVector<Vector, GridView, Traits>>
{
};
template <class Vector, class GridView>
struct VectorAbstraction<GDT::LocalDofVector<Vector, GridView>>
: public LA::internal::VectorAbstractionBase<GDT::LocalDofVector<Vector, GridView>>
{
};
} // namespace Common
} // namespace XT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_DOF_VECTOR_HH
<commit_msg>[local.dof-vector] mark method with override final<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2016 - 2017)
// Rene Milk (2016 - 2017)
#ifndef DUNE_GDT_LOCAL_DOF_VECTOR_HH
#define DUNE_GDT_LOCAL_DOF_VECTOR_HH
#include <dune/xt/common/vector.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/bound-object.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
namespace Dune {
namespace GDT {
namespace internal {
// forward, required for the default in the declaration of ConstLocalDofVector
template <class Vector, class GridView>
class ConstLocalDofVectorTraits;
} // namespace internal
// forwards, required for the traits
template <class Vector, class GridView, class Traits = internal::ConstLocalDofVectorTraits<Vector, GridView>>
class ConstLocalDofVector;
template <class Vector, class GridView>
class LocalDofVector;
namespace internal {
template <class Vector, class GridView>
class ConstLocalDofVectorTraits
{
static_assert(XT::LA::is_vector<Vector>::value, "");
public:
using derived_type = ConstLocalDofVector<Vector, GridView>;
using ScalarType = typename Vector::ScalarType;
using RealType = typename Vector::RealType;
};
template <class Vector, class GridView>
class LocalDofVectorTraits
{
static_assert(XT::LA::is_vector<Vector>::value, "");
public:
using derived_type = LocalDofVector<Vector, GridView>;
using ScalarType = typename Vector::ScalarType;
using RealType = typename Vector::RealType;
};
} // namespace internal
/**
* \note Since all implementations of XT::LA::VectorInterface are assumed to be thread safe, no special care needs to be
* taken here.
*/
template <class Vector, class GridView, class Traits>
class ConstLocalDofVector : public XT::LA::VectorInterface<Traits>,
public XT::Grid::ElementBoundObject<XT::Grid::extract_entity_t<GridView>>
{
using ThisType = ConstLocalDofVector<Vector, GridView, Traits>;
using BaseType = XT::LA::VectorInterface<Traits>;
public:
using typename BaseType::ScalarType;
using VectorType = Vector;
using MapperType = MapperInterface<GridView>;
using typename XT::Grid::ElementBoundObject<XT::Grid::extract_entity_t<GridView>>::ElementType;
ConstLocalDofVector(const MapperType& mapper, const VectorType& global_vector)
: mapper_(mapper)
, global_vector_(global_vector)
, global_DoF_indices_(mapper_.max_local_size())
, size_(0)
{
}
ConstLocalDofVector(const ThisType& other) = default;
ConstLocalDofVector(ThisType&& source) = default;
protected:
void post_bind(const ElementType& ele) override final
{
mapper_.global_indices(ele, global_DoF_indices_);
size_ = mapper_.local_size(ele);
DUNE_THROW_IF(global_DoF_indices_.size() < size_,
Exceptions::dof_vector_error,
"This must not happen, the mapper is broken!");
}
public:
size_t size() const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
return size_;
}
void add_to_entry(const size_t /*ii*/, const ScalarType& /*value*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
}
void set_entry(const size_t /*ii*/, const ScalarType& /*value*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
}
ScalarType get_entry(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_.get_entry(global_DoF_indices_[ii]);
}
protected:
ScalarType& get_unchecked_ref(const size_t /*ii*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
return dummy_scalar_to_silence_the_warning_;
}
const ScalarType& get_unchecked_ref(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
// This is not optimal, but global_vector_.get_unchecked_ref is protected.
return global_vector_[global_DoF_indices_[ii]];
}
public:
ScalarType& operator[](const size_t /*ii*/)
{
DUNE_THROW(Exceptions::dof_vector_error, "a ConstLocalDofVector is not mutable!");
return dummy_scalar_to_silence_the_warning_;
}
const ScalarType& operator[](const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
protected:
friend BaseType; // To allow access to get_unchecked_ref().
const MapperType& mapper_;
private:
const VectorType& global_vector_;
protected:
DynamicVector<size_t> global_DoF_indices_;
size_t size_;
private:
ScalarType dummy_scalar_to_silence_the_warning_;
}; // class ConstLocalDofVector
template <class Vector, class GridView>
class LocalDofVector : public ConstLocalDofVector<Vector, GridView, internal::LocalDofVectorTraits<Vector, GridView>>
{
using ThisType = LocalDofVector<Vector, GridView>;
using BaseType = ConstLocalDofVector<Vector, GridView, internal::LocalDofVectorTraits<Vector, GridView>>;
public:
using typename BaseType::ScalarType;
using VectorType = Vector;
using MapperType = MapperInterface<GridView>;
LocalDofVector(const MapperType& mapper, VectorType& global_vector)
: BaseType(mapper, global_vector)
, global_vector_(global_vector)
{
}
LocalDofVector(const ThisType&) = default;
LocalDofVector(ThisType&&) = default;
void add_to_entry(const size_t ii, const ScalarType& value)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
global_vector_.add_to_entry(global_DoF_indices_[ii], value);
}
void set_entry(const size_t ii, const ScalarType& value)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
global_vector_.set_entry(global_DoF_indices_[ii], value);
}
ScalarType get_entry(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_.get_entry(global_DoF_indices_[ii]);
}
protected:
ScalarType& get_unchecked_ref(const size_t ii)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
const ScalarType& get_unchecked_ref(const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
public:
ScalarType& operator[](const size_t ii)
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
const ScalarType& operator[](const size_t ii) const
{
DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
assert(ii < size_);
return global_vector_[global_DoF_indices_[ii]];
}
private:
// To allow access to get_unchecked_ref().
friend XT::LA::VectorInterface<internal::LocalDofVectorTraits<Vector, GridView>>;
using BaseType::mapper_;
VectorType& global_vector_;
using BaseType::global_DoF_indices_;
using BaseType::size_;
}; // class LocalDofVector
} // namespace GDT
namespace XT {
namespace Common {
template <class Vector, class GridView, class Traits>
struct VectorAbstraction<GDT::ConstLocalDofVector<Vector, GridView, Traits>>
: public LA::internal::VectorAbstractionBase<GDT::ConstLocalDofVector<Vector, GridView, Traits>>
{
};
template <class Vector, class GridView>
struct VectorAbstraction<GDT::LocalDofVector<Vector, GridView>>
: public LA::internal::VectorAbstractionBase<GDT::LocalDofVector<Vector, GridView>>
{
};
} // namespace Common
} // namespace XT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_DOF_VECTOR_HH
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_LA_SOLVER_ISTL_HH
#define DUNE_STUFF_LA_SOLVER_ISTL_HH
#include <type_traits>
#include <cmath>
#if HAVE_DUNE_ISTL
# include <dune/istl/operators.hh>
# include <dune/istl/preconditioners.hh>
# include <dune/istl/solvers.hh>
# include <dune/istl/umfpack.hh>
#endif // HAVE_DUNE_ISTL
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/la/container/istl.hh>
#include <dune/stuff/la/solver/istl_amg.hh>
#include "../solver.hh"
namespace Dune {
namespace Stuff {
namespace LA {
#if HAVE_DUNE_ISTL
template< class S, class CommunicatorType >
class Solver< IstlRowMajorSparseMatrix< S >, CommunicatorType >
: protected SolverUtils
{
public:
typedef IstlRowMajorSparseMatrix< S > MatrixType;
Solver(const MatrixType& matrix)
: matrix_(matrix)
, communicator_(new CommunicatorType())
{}
Solver(const MatrixType& matrix,
const CommunicatorType& communicator)
: matrix_(matrix)
, communicator_(communicator)
{}
static std::vector< std::string > types()
{
return { "bicgstab.amg.ilu0"
, "bicgstab.ilut"
#if HAVE_UMFPACK
, "umfpack"
#endif
};
} // ... types()
static Common::Configuration options(const std::string type = "")
{
const std::string tp = !type.empty() ? type : types()[0];
SolverUtils::check_given(tp, types());
Common::Configuration iterative_options({"max_iter", "precision", "verbose"},
{"10000", "1e-10", "0"});
iterative_options.set("post_check_solves_system", "1e-5");
if (tp == "bicgstab.amg.ilu0") {
iterative_options.set("smoother.iterations", "1");
iterative_options.set("smoother.relaxation_factor", "1");
iterative_options.set("smoother.verbose", "0");
iterative_options.set("preconditioner.max_level", "100");
iterative_options.set("preconditioner.coarse_target", "1000");
iterative_options.set("preconditioner.min_coarse_rate", "1.2");
iterative_options.set("preconditioner.prolong_damp", "1.6");
iterative_options.set("preconditioner.anisotropy_dim", "2"); // <- this should be the dimDomain of the problem!
iterative_options.set("preconditioner.isotropy_dim", "2"); // <- this as well
iterative_options.set("preconditioner.verbose", "0");
} else if (tp == "bicgstab.ilut") {
iterative_options.set("preconditioner.iterations", "2");
iterative_options.set("preconditioner.relaxation_factor", "1.0");
#if HAVE_UMFPACK
} else if (tp == "umfpack") {
iterative_options = Common::Configuration({"post_check_solves_system", "verbose"}, {"1e-5", "0"});
#endif
} else
DUNE_THROW(Exceptions::internal_error,
"Given type '" << tp << "' is not supported, although it was reported by types()!");
iterative_options.set("type", tp);
return iterative_options;
} // ... options(...)
void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution) const
{
apply(rhs, solution, types()[0]);
}
void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const std::string& type) const
{
apply(rhs, solution, options(type));
}
/**
* \note does a copy of the rhs
*/
void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const Common::Configuration& opts) const
{
try {
if (!opts.has_key("type"))
DUNE_THROW(Exceptions::configuration_error,
"Given options (see below) need to have at least the key 'type' set!\n\n" << opts);
const auto type = opts.get< std::string >("type");
SolverUtils::check_given(type, types());
const Common::Configuration default_opts = options(type);
IstlDenseVector< S > writable_rhs = rhs.copy();
// solve
if (type == "bicgstab.amg.ilu0") {
auto result = AmgApplicator< S, CommunicatorType >(matrix_, communicator_.storage_access()).call(writable_rhs,
solution,
opts,
default_opts);
if (!result.converged)
DUNE_THROW(Exceptions::linear_solver_failed_bc_it_did_not_converge,
"The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n"
<< "Those were the given options:\n\n"
<< opts);
} else if (type == "bicgstab.ilut") {
typedef MatrixAdapter< typename MatrixType::BackendType,
typename IstlDenseVector< S >::BackendType,
typename IstlDenseVector< S >::BackendType > MatrixOperatorType;
MatrixOperatorType matrix_operator(matrix_.backend());
typedef SeqILUn< typename MatrixType::BackendType,
typename IstlDenseVector< S >::BackendType,
typename IstlDenseVector< S >::BackendType > PreconditionerType;
PreconditionerType preconditioner(matrix_.backend(),
opts.get("preconditioner.iterations",
default_opts.get< int >("preconditioner.iterations")),
opts.get("preconditioner.relaxation_factor",
default_opts.get< S >("preconditioner.relaxation_factor")));
typedef BiCGSTABSolver< typename IstlDenseVector< S >::BackendType > SolverType;
SolverType solver(matrix_operator,
preconditioner,
opts.get("precision", default_opts.get< S >("precision")),
opts.get("max_iter", default_opts.get< int >("max_iter")),
opts.get("verbose", default_opts.get< int >("verbose")));
InverseOperatorResult stat;
#if HAVE_MPI
DSC_LOG_DEBUG << "using serial bicgstab.ilut\n";
#endif
solver.apply(solution.backend(), writable_rhs.backend(), stat);
if (!stat.converged)
DUNE_THROW(Exceptions::linear_solver_failed_bc_it_did_not_converge,
"The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n"
<< "Those were the given options:\n\n" << opts);
#if HAVE_UMFPACK
} else if (type == "umfpack") {
UMFPack<typename MatrixType::BackendType> solver(matrix_.backend(),
opts.get("verbose", default_opts.get< int >("verbose")));
InverseOperatorResult stat;
solver.apply(solution.backend(), writable_rhs.backend(), stat);
#endif
} else
DUNE_THROW(Exceptions::internal_error,
"Given type '" << type << "' is not supported, although it was reported by types()!");
// check (use writable_rhs as tmp)
const S post_check_solves_system_threshold = opts.get("post_check_solves_system",
default_opts.get< S >("post_check_solves_system"));
if (post_check_solves_system_threshold > 0) {
matrix_.mv(solution, writable_rhs);
writable_rhs -= rhs;
const S sup_norm = writable_rhs.sup_norm();
if (sup_norm > post_check_solves_system_threshold || std::isnan(sup_norm) || std::isinf(sup_norm))
DUNE_THROW(Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system,
"The computed solution does not solve the system (although the dune-istl backend "
<< "reported no error) and you requested checking (see options below)!\n"
<< "If you want to disable this check, set 'post_check_solves_system = 0' in the options."
<< "\n\n"
<< " (A * x - b).sup_norm() = " << writable_rhs.sup_norm() << "\n\n"
<< "Those were the given options:\n\n" << opts);
}
} catch(ISTLError& e) {
DUNE_THROW(Exceptions::linear_solver_failed, "The dune-istl backend reported: " << e.what());
}
} // ... apply(...)
private:
const MatrixType& matrix_;
const Common::ConstStorageProvider< CommunicatorType > communicator_;
}; // class Solver
#else // HAVE_DUNE_ISTL
template< class S, class CommunicatorType >
class Solver< IstlRowMajorSparseMatrix< S >, CommunicatorType >
{
static_assert(Dune::AlwaysFalse< S >::value, "You are missing dune-istl!");
};
#endif // HAVE_DUNE_ISTL
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_LA_SOLVER_ISTL_HH
<commit_msg>Revert "Revert "[la.solver.istl] add "superlu"""<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_LA_SOLVER_ISTL_HH
#define DUNE_STUFF_LA_SOLVER_ISTL_HH
#include <type_traits>
#include <cmath>
#if HAVE_DUNE_ISTL
# include <dune/istl/operators.hh>
# include <dune/istl/preconditioners.hh>
# include <dune/istl/solvers.hh>
# include <dune/istl/umfpack.hh>
# include <dune/istl/superlu.hh>
#endif // HAVE_DUNE_ISTL
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/la/container/istl.hh>
#include <dune/stuff/la/solver/istl_amg.hh>
#include "../solver.hh"
namespace Dune {
namespace Stuff {
namespace LA {
#if HAVE_DUNE_ISTL
template< class S, class CommunicatorType >
class Solver< IstlRowMajorSparseMatrix< S >, CommunicatorType >
: protected SolverUtils
{
public:
typedef IstlRowMajorSparseMatrix< S > MatrixType;
Solver(const MatrixType& matrix)
: matrix_(matrix)
, communicator_(new CommunicatorType())
{}
Solver(const MatrixType& matrix,
const CommunicatorType& communicator)
: matrix_(matrix)
, communicator_(communicator)
{}
static std::vector< std::string > types()
{
return {
#if !HAVE_MPI && HAVE_SUPERLU
"superlu"
,
#endif
"bicgstab.amg.ilu0"
, "bicgstab.ilut"
#if HAVE_UMFPACK
, "umfpack"
#endif
};
} // ... types()
static Common::Configuration options(const std::string type = "")
{
const std::string tp = !type.empty() ? type : types()[0];
SolverUtils::check_given(tp, types());
Common::Configuration general_opts({"type", "post_check_solves_system", "verbose"},
{tp, "1e-5", "0"});
Common::Configuration iterative_options({"max_iter", "precision"},
{"10000", "1e-10"});
iterative_options += general_opts;
if (tp == "bicgstab.amg.ilu0") {
iterative_options.set("smoother.iterations", "1");
iterative_options.set("smoother.relaxation_factor", "1");
iterative_options.set("smoother.verbose", "0");
iterative_options.set("preconditioner.max_level", "100");
iterative_options.set("preconditioner.coarse_target", "1000");
iterative_options.set("preconditioner.min_coarse_rate", "1.2");
iterative_options.set("preconditioner.prolong_damp", "1.6");
iterative_options.set("preconditioner.anisotropy_dim", "2"); // <- this should be the dimDomain of the problem!
iterative_options.set("preconditioner.isotropy_dim", "2"); // <- this as well
iterative_options.set("preconditioner.verbose", "0");
return iterative_options;
} else if (tp == "bicgstab.ilut") {
iterative_options.set("preconditioner.iterations", "2");
iterative_options.set("preconditioner.relaxation_factor", "1.0");
return iterative_options;
#if HAVE_UMFPACK
} else if (tp == "umfpack") {
return general_opts;
#endif
#if !HAVE_MPI && HAVE_SUPERLU
} else if (tp == "superlu") {
return general_opts;
#endif // !HAVE_MPI && HAVE_SUPERLU
} else
DUNE_THROW(Exceptions::internal_error,
"Given type '" << tp << "' is not supported, although it was reported by types()!");
return Common::Configuration();
} // ... options(...)
void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution) const
{
apply(rhs, solution, types()[0]);
}
void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const std::string& type) const
{
apply(rhs, solution, options(type));
}
/**
* \note does a copy of the rhs
*/
void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const Common::Configuration& opts) const
{
try {
if (!opts.has_key("type"))
DUNE_THROW(Exceptions::configuration_error,
"Given options (see below) need to have at least the key 'type' set!\n\n" << opts);
const auto type = opts.get< std::string >("type");
SolverUtils::check_given(type, types());
const Common::Configuration default_opts = options(type);
IstlDenseVector< S > writable_rhs = rhs.copy();
// solve
if (type == "bicgstab.amg.ilu0") {
auto result = AmgApplicator< S, CommunicatorType >(matrix_, communicator_.storage_access()).call(writable_rhs,
solution,
opts,
default_opts);
if (!result.converged)
DUNE_THROW(Exceptions::linear_solver_failed_bc_it_did_not_converge,
"The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n"
<< "Those were the given options:\n\n"
<< opts);
} else if (type == "bicgstab.ilut") {
typedef MatrixAdapter< typename MatrixType::BackendType,
typename IstlDenseVector< S >::BackendType,
typename IstlDenseVector< S >::BackendType > MatrixOperatorType;
MatrixOperatorType matrix_operator(matrix_.backend());
typedef SeqILUn< typename MatrixType::BackendType,
typename IstlDenseVector< S >::BackendType,
typename IstlDenseVector< S >::BackendType > PreconditionerType;
PreconditionerType preconditioner(matrix_.backend(),
opts.get("preconditioner.iterations",
default_opts.get< int >("preconditioner.iterations")),
opts.get("preconditioner.relaxation_factor",
default_opts.get< S >("preconditioner.relaxation_factor")));
typedef BiCGSTABSolver< typename IstlDenseVector< S >::BackendType > SolverType;
SolverType solver(matrix_operator,
preconditioner,
opts.get("precision", default_opts.get< S >("precision")),
opts.get("max_iter", default_opts.get< int >("max_iter")),
opts.get("verbose", default_opts.get< int >("verbose")));
InverseOperatorResult stat;
#if HAVE_MPI
DSC_LOG_DEBUG << "using serial bicgstab.ilut\n";
#endif
solver.apply(solution.backend(), writable_rhs.backend(), stat);
if (!stat.converged)
DUNE_THROW(Exceptions::linear_solver_failed_bc_it_did_not_converge,
"The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n"
<< "Those were the given options:\n\n" << opts);
#if HAVE_UMFPACK
} else if (type == "umfpack") {
UMFPack<typename MatrixType::BackendType> solver(matrix_.backend(),
opts.get("verbose", default_opts.get< int >("verbose")));
InverseOperatorResult stat;
solver.apply(solution.backend(), writable_rhs.backend(), stat);
#endif // HAVE_UMFPACK
#if !HAVE_MPI && HAVE_SUPERLU
} else if (type == "superlu") {
SuperLU< typename MatrixType::BackendType > solver(matrix_.backend(),
opts.get("verbose", default_opts.get< int >("verbose")));
InverseOperatorResult stat;
solver.apply(solution.backend(), writable_rhs.backend(), stat);
if (!stat.converged)
DUNE_THROW(Exceptions::linear_solver_failed_bc_it_did_not_converge,
"The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n"
<< "Those were the given options:\n\n" << opts);
#endif // !HAVE_MPI && HAVE_SUPERLU
} else
DUNE_THROW(Exceptions::internal_error,
"Given type '" << type << "' is not supported, although it was reported by types()!");
// check (use writable_rhs as tmp)
const S post_check_solves_system_threshold = opts.get("post_check_solves_system",
default_opts.get< S >("post_check_solves_system"));
if (post_check_solves_system_threshold > 0) {
matrix_.mv(solution, writable_rhs);
writable_rhs -= rhs;
const S sup_norm = writable_rhs.sup_norm();
if (sup_norm > post_check_solves_system_threshold || std::isnan(sup_norm) || std::isinf(sup_norm))
DUNE_THROW(Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system,
"The computed solution does not solve the system (although the dune-istl backend "
<< "reported no error) and you requested checking (see options below)!\n"
<< "If you want to disable this check, set 'post_check_solves_system = 0' in the options."
<< "\n\n"
<< " (A * x - b).sup_norm() = " << sup_norm << "\n\n"
<< "Those were the given options:\n\n" << opts);
}
} catch(ISTLError& e) {
DUNE_THROW(Exceptions::linear_solver_failed, "The dune-istl backend reported: " << e.what());
}
} // ... apply(...)
private:
const MatrixType& matrix_;
const Common::ConstStorageProvider< CommunicatorType > communicator_;
}; // class Solver
#else // HAVE_DUNE_ISTL
template< class S, class CommunicatorType >
class Solver< IstlRowMajorSparseMatrix< S >, CommunicatorType >
{
static_assert(Dune::AlwaysFalse< S >::value, "You are missing dune-istl!");
};
#endif // HAVE_DUNE_ISTL
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_LA_SOLVER_ISTL_HH
<|endoftext|> |
<commit_before>#define _JNI_IMPLEMENTATION_ 1
#include <jni.h>
#include <dlfcn.h>
#include <assert.h>
#include "KrapsRDD.h"
#include <unistd.h>
typedef KrapsIterator* (*iterator_constructor_t)(JNIEnv* env);
struct KrapsRDD
{
void* dll;
KrapsIterator* iterator;
void* next() {
return iterator->next();
}
KrapsRDD(void* so, KrapsIterator* iter) : dll(so), iterator(iter) {}
~KrapsRDD() {
delete iterator;
dlclose(dll);
}
};
class KrapsCluster
{
public:
Cluster* cluster;
char** nodes;
public:
void start(JNIEnv* env, jobjectArray hosts, jint nodeId) {
int nNodes = env->GetArrayLength(hosts);
nodes = new char*[nNodes];
for (int i = 0; i < nNodes; i++) {
jstring host = (jstring)env->GetObjectArrayElement(hosts, i % nNodes);
char const* hostName = env->GetStringUTFChars(host, 0);
nodes[i] = new char[strlen(hostName) + 8];
sprintf(nodes[i], "%s:%d", hostName, 5001 + i);
env->ReleaseStringUTFChars(host, hostName);
}
cluster = new Cluster(nodeId, nNodes, nodes);
cluster->userData = NULL;
}
void stop()
{
for (size_t i = 0; i < cluster->nNodes; i++) {
delete nodes[i];
}
delete[] nodes;
delete cluster;
}
};
extern "C" {
JNIEXPORT jlong Java_kraps_KrapsRDD_createIterator(JNIEnv* env, jobject self, jlong kraps, jint queryId, jobjectArray sparkInputs)
{
char buf[256];
sprintf(buf, "libQ%d.so", queryId);
// fprintf(stdout, "Library name: %s\n", buf);
//
// char cwd[1024];
// if (getcwd(cwd, sizeof(cwd)) != NULL)
// fprintf(stdout, "Current working dir: %s\n", cwd);
// else
// perror("getcwd() error");
void* dll = dlopen(buf, RTLD_NOW | RTLD_GLOBAL);
assert(dll != NULL);
sprintf(buf, "getQ%dIterator", queryId);
iterator_constructor_t constructor = (iterator_constructor_t)dlsym(dll, buf);
assert(constructor != NULL);
JavaContext ctx(env, sparkInputs);
Cluster* cluster = Cluster::instance.get();
if (cluster == NULL) {
cluster = ((KrapsCluster*)kraps)->cluster;
Cluster::instance.set(cluster);
} else {
assert(cluster == ((KrapsCluster*)kraps)->cluster);
}
cluster->userData = &ctx;
return (jlong)(size_t)new KrapsRDD(dll, constructor(env));
}
JNIEXPORT jlong Java_kraps_KrapsRDD_nextRow(JNIEnv* env, jobject self, jlong kraps, jlong iterator, jobjectArray sparkInputs)
{
KrapsRDD* rdd = (KrapsRDD*)iterator;
JavaContext ctx(env, sparkInputs);
Cluster* cluster = Cluster::instance.get();
if (cluster == NULL) {
cluster = ((KrapsCluster*)kraps)->cluster;
Cluster::instance.set(cluster);
}
cluster->userData = &ctx;
void* row = rdd->next();
if (row != NULL) {
return (jlong)(size_t)row;
}
cluster->barrier();
delete rdd;
return 0;
}
JNIEXPORT jlong Java_kraps_KrapsCluster_00024_start(JNIEnv* env, jobject self, jobjectArray hosts, jint nodeId)
{
KrapsCluster* cluster = new KrapsCluster();
cluster->start(env, hosts, nodeId);
return (jlong)(size_t)cluster;
}
JNIEXPORT void Java_kraps_KrapsCluster_00024_stop(JNIEnv* env, jobject self, jlong kraps)
{
KrapsCluster* cluster = (KrapsCluster*)kraps;
cluster->stop();
delete cluster;
}
}
<commit_msg>Place dlopen in critical section<commit_after>#define _JNI_IMPLEMENTATION_ 1
#include <jni.h>
#include <dlfcn.h>
#include <pthread.h>
#include <assert.h>
#include "KrapsRDD.h"
#include <unistd.h>
static pthread_mutex_t dllMutex = PTHREAD_MUTEX_INITIALIZER;
typedef KrapsIterator* (*iterator_constructor_t)(JNIEnv* env);
struct KrapsRDD
{
void* dll;
KrapsIterator* iterator;
void* next() {
return iterator->next();
}
KrapsRDD(void* so, KrapsIterator* iter) : dll(so), iterator(iter) {}
~KrapsRDD() {
delete iterator;
dlclose(dll);
}
};
class KrapsCluster
{
public:
Cluster* cluster;
char** nodes;
public:
void start(JNIEnv* env, jobjectArray hosts, jint nodeId) {
int nNodes = env->GetArrayLength(hosts);
nodes = new char*[nNodes];
for (int i = 0; i < nNodes; i++) {
jstring host = (jstring)env->GetObjectArrayElement(hosts, i % nNodes);
char const* hostName = env->GetStringUTFChars(host, 0);
nodes[i] = new char[strlen(hostName) + 8];
sprintf(nodes[i], "%s:%d", hostName, 5001 + i);
env->ReleaseStringUTFChars(host, hostName);
}
cluster = new Cluster(nodeId, nNodes, nodes);
cluster->userData = NULL;
}
void stop()
{
for (size_t i = 0; i < cluster->nNodes; i++) {
delete nodes[i];
}
delete[] nodes;
delete cluster;
}
};
extern "C" {
JNIEXPORT jlong Java_kraps_KrapsRDD_createIterator(JNIEnv* env, jobject self, jlong kraps, jint queryId, jobjectArray sparkInputs)
{
char buf[256];
sprintf(buf, "libQ%d.so", queryId);
// fprintf(stdout, "Library name: %s\n", buf);
//
// char cwd[1024];
// if (getcwd(cwd, sizeof(cwd)) != NULL)
// fprintf(stdout, "Current working dir: %s\n", cwd);
// else
// perror("getcwd() error");
pthread_mutex_lock(&dllMutex);
void* dll = dlopen(buf, RTLD_NOW | RTLD_GLOBAL);
assert(dll != NULL);
sprintf(buf, "getQ%dIterator", queryId);
iterator_constructor_t constructor = (iterator_constructor_t)dlsym(dll, buf);
assert(constructor != NULL);
pthread_mutex_unlock(&dllMutex);
JavaContext ctx(env, sparkInputs);
Cluster* cluster = Cluster::instance.get();
if (cluster == NULL) {
cluster = ((KrapsCluster*)kraps)->cluster;
Cluster::instance.set(cluster);
} else {
assert(cluster == ((KrapsCluster*)kraps)->cluster);
}
cluster->userData = &ctx;
return (jlong)(size_t)new KrapsRDD(dll, constructor(env));
}
JNIEXPORT jlong Java_kraps_KrapsRDD_nextRow(JNIEnv* env, jobject self, jlong kraps, jlong iterator, jobjectArray sparkInputs)
{
KrapsRDD* rdd = (KrapsRDD*)iterator;
JavaContext ctx(env, sparkInputs);
Cluster* cluster = Cluster::instance.get();
if (cluster == NULL) {
cluster = ((KrapsCluster*)kraps)->cluster;
Cluster::instance.set(cluster);
}
cluster->userData = &ctx;
void* row = rdd->next();
if (row != NULL) {
return (jlong)(size_t)row;
}
cluster->barrier();
delete rdd;
return 0;
}
JNIEXPORT jlong Java_kraps_KrapsCluster_00024_start(JNIEnv* env, jobject self, jobjectArray hosts, jint nodeId)
{
KrapsCluster* cluster = new KrapsCluster();
cluster->start(env, hosts, nodeId);
return (jlong)(size_t)cluster;
}
JNIEXPORT void Java_kraps_KrapsCluster_00024_stop(JNIEnv* env, jobject self, jlong kraps)
{
KrapsCluster* cluster = (KrapsCluster*)kraps;
cluster->stop();
delete cluster;
}
}
<|endoftext|> |
<commit_before><commit_msg>[HEVCd] Fix HEVC SCC self reference<commit_after><|endoftext|> |
<commit_before>/*
* PatternMatch.cc
*
* Copyright (C) 2009 Linas Vepstas
*
* Author: Linas Vepstas <linasvepstas@gmail.com> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "PatternMatch.h"
#include "DefaultPatternMatchCB.h"
#include <opencog/util/platform.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/util/Logger.h>
using namespace opencog;
PatternMatch::PatternMatch(void)
{
atom_space = NULL;
}
/* ================================================================= */
/**
* Solve a predicate by pattern matching.
* The predicate is defined in terms of two hypergraphs: one is a
* hypergraph defining a pattern to be matched for, and the other is a
* list of bound variables in the first.
*
* The bound variables are, by definition, nodes. (XXX It might be
* useful to loosen this restriction someday). The list of bound variables
* is then assumed to be listed using the ListLink type. So, for
* example:
*
* ListLink
* SomeNode "variable 1"
* SomeOtherNode "another variable"
*
* The predicate hypergraph is assumed to be a list of "clauses", where
* each "clause" is a tree. The clauses are assumed to be connected,
* i.e. share common nodes or links. The algorithm to find solutions
* will fail on disconnected hypergraphs. The list of clauses is
* specified by means of an AndLink, so, for example:
*
* AndLink
* SomeLink ....
* SomeOtherLink ...
*
* The solution proceeds by requiring each clause to match some part of
* the atomspace (i.e. of the universe of hypergraphs stored in the
* atomspace). When a solution is found, PatternMatchCallback::solution
* method is called, and it is passed two maps: one mapping the bound
* variables to thier solutions, and the other mapping the pattern
* clauses to thier corresponding solution clauses.
*
* At this time, the list of clauses is understood to be a single
* disjunct; that is, all of the clauses must be simultaneously
* satisfied. Thus, in principle, one could build a layer on top of
* this that accepts clauses in disjunctive normal form (and so on...)
* It is not clear at this time how to benefit from Boolean SAT solver
* technlogy (or at what point this would be needed).
*/
void PatternMatch::match(PatternMatchCallback *cb,
Handle hclauses,
Handle hvarbles)
{
Atom * aclauses = TLB::getAtom(hclauses);
Atom * avarbles = TLB::getAtom(hvarbles);
Link * lclauses = dynamic_cast<Link *>(aclauses);
Link * lvarbles = dynamic_cast<Link *>(avarbles);
// Both must be non-empty.
if (!lclauses || !lvarbles) return;
// Types must be as expected
Type tclauses = lclauses->getType();
Type tvarbles = lvarbles->getType();
if (AND_LINK != tclauses)
{
logger().warn("%s: expected AndLink for clause list", __FUNCTION__);
return;
}
if (LIST_LINK != tvarbles)
{
logger().warn("%s: expected ListLink for bound variable list", __FUNCTION__);
return;
}
pme.match(cb, lclauses->getOutgoingSet(), lvarbles->getOutgoingSet());
}
/* ================================================================= */
// Handy dandy utility class.
//
class FindVariables
{
public:
std::vector<Handle> varlist;
/**
* Create a list of all of the VariableNodes that lie in the
* outgoing set of the handle (recursively).
*/
inline bool find_vars(Handle h)
{
Atom *a = TLB::getAtom(h);
Node *n = dynamic_cast<Node *>(a);
if (n)
{
if (n->getType() == VARIABLE_NODE)
{
varlist.push_back(h);
}
return false;
}
return foreach_outgoing_handle(h, &FindVariables::find_vars, this);
}
};
/* ================================================================= */
/**
* class Instantiator -- create grounded expressions from ungrounded ones.
* Given an ungrounded expression (i.e. an expression containing variables)
* and a map between variables and ground terms, it will create a new
* expression, with the ground terms substituted for the variables.
*/
class Instantiator
{
private:
std::map<Handle, Handle> *vmap;
std::vector<Handle> oset;
bool walk_tree(Handle tree);
public:
AtomSpace *as;
Handle instantiate(Handle expr, std::map<Handle, Handle> &vars);
};
bool Instantiator::walk_tree(Handle expr)
{
Atom *a = TLB::getAtom(expr);
Type t = a->getType();
Node *n = dynamic_cast<Node *>(a);
if (n)
{
if (VARIABLE_NODE != t)
{
oset.push_back(expr);
return false;
}
// If we are here, we found a variable. Look it up.
std::map<Handle,Handle>::const_iterator it = vmap->find(expr);
if (vmap->end() != it)
{
Handle soln = it->second;
oset.push_back(soln);
}
else
{
oset.push_back(expr);
}
return false;
}
// If we are here, then we have a link. Walk it.
std::vector<Handle> save_oset = oset;
oset.clear();
// Walk the subtree, substituting values for variables.
foreach_outgoing_handle(expr, &Instantiator::walk_tree, this);
// Now create a duplicate link, but with an outgoing set where
// the variables have been substituted by thier values.
Handle sh = as->addLink(t, oset);
oset = save_oset;
oset.push_back(sh);
return false;
}
/**
* Given a handle to an ungrounded expression, and a set of groundings,
* this will create a grounded expression.
*
* The set of groundings is to be passed in with the map 'vars', which
* maps variable names to thier groundings -- it maps variable names to
* atoms that already exist in the atomspace. This method will then go
* through all of the variables in the expression, and substitute them
* with thier values, creating a new expression. The new expression is
* added to the atomspace, and its handle is returned.
*/
Handle Instantiator::instantiate(Handle expr, std::map<Handle, Handle> &vars)
{
vmap = &vars;
walk_tree(expr);
if (oset.size() != 1)
{
logger().warn("%s: outgoing set size %d is insane!",
__FUNCTION__, oset.size());
}
return oset[0];
}
/* ================================================================= */
/**
* class Implicator -- pattern matching callback for grounding implicands.
*
* This class is meant to be used with the pattern matcher. When the
* pattern matcher calls the callback, it will do so with a particular
* grounding of the search pattern. This class then holds an ungrounded
* implicand, and will create a grounded version of the implicand.
*
* The 'var_soln' argument in the callback contains the map from variables
* to ground terms. 'class Instantiator' is used to perform the actual
* grounding. A list of grounded expressions is created in 'result_list'.
*/
class Implicator :
public DefaultPatternMatchCB
{
private:
Instantiator inst;
public:
AtomSpace *as;
Handle implicand;
std::vector<Handle> result_list;
virtual bool solution(std::map<Handle, Handle> &pred_soln,
std::map<Handle, Handle> &var_soln);
};
bool Implicator::solution(std::map<Handle, Handle> &pred_soln,
std::map<Handle, Handle> &var_soln)
{
inst.as = as;
Handle h = inst.instantiate(implicand, var_soln);
result_list.push_back(h);
return false;
}
/* ================================================================= */
/**
* Evaluate an ImplicationLink.
* Given an ImplicationLink, this method will "evaluate" it, matching
* the predicate, and creating the implicand, assuming the predicate can
* be satisfied. Thus, for example, given the structure
*
* ImplicationLink
* AndList
* EvaluationList
* PredicateNode "_obj"
* ListLink
* ConceptNode "make"
* VariableNode $var0
* EvaluationList
* PredicateNode "from"
* ListLink
* ConceptNode "make"
* VariableNode $var1"
* EvaluationList
* PredicateNode "make_from"
* ListLink
* VariableNode $var0
* VariableNode $var1
*
* Then, if the atomspace also contains a parsed version of the English
* sentence "Pottery is made from clay", that is, if it contains the
* hypergraph
*
* EvaluationList
* PredicateNode "_obj"
* ListLink
* ConceptNode "make"
* ConceptNode "pottery"
*
* and the hypergraph
*
* EvaluationList
* PredicateNode "from"
* ListLink
* ConceptNode "make"
* ConceptNode "clay"
*
* Then, by pattern matching, the predicate part of the ImplicationLink
* can be fulfilled, binding $var0 to "pottery" and $var1 to "clay".
* These bindings are refered to as the 'solutions' to the variables.
* So, e.g. $var0 is 'solved' by "pottery".
*
* Next, the implicand is then created; that is, the following hypergraph
* is created and added to the atomspace:
*
* EvaluationList
* PredicateNode "make_from"
* ListLink
* ConceptNode "pottery"
* ConceptNode "clay"
*
* As the above example illustrates, this function expects that the
* input handle is an implication link. It expects the implication link
* to consist entirely of one disjunct (one AndList) and one implicand.
* All variables are implicit, and are identified by VariableNodes (they
* are not explicitly called out). Variable substitution in the
* implicand copies over the types of the solutions to the variables.
*/
Handle PatternMatch::imply (Handle himplication)
{
Atom * aimpl = TLB::getAtom(himplication);
Link * limpl = dynamic_cast<Link *>(aimpl);
// Must be non-empty.
if (!limpl) return Handle::UNDEFINED;
// Type must be as expected
Type timpl = limpl->getType();
if (IMPLICATION_LINK != timpl)
{
logger().warn("%s: expected ImplicationLink", __FUNCTION__);
return Handle::UNDEFINED;
}
const std::vector<Handle>& oset = limpl->getOutgoingSet();
if (2 != oset.size())
{
logger().warn("%s: ImplicationLink has wrong size", __FUNCTION__);
return Handle::UNDEFINED;
}
Handle hclauses = oset[0];
Handle implicand = oset[1];
Atom * aclauses = TLB::getAtom(hclauses);
Link * lclauses = dynamic_cast<Link *>(aclauses);
// Must be non-empty.
if (!lclauses) return Handle::UNDEFINED;
// Types must be as expected
Type tclauses = lclauses->getType();
if (AND_LINK != tclauses)
{
logger().warn("%s: expected AndLink for clause list", __FUNCTION__);
return Handle::UNDEFINED;
}
// Extract a list of variables.
FindVariables fv;
fv.find_vars(hclauses);
// Now perform the search.
Implicator impl;
impl.implicand = implicand;
impl.as = atom_space;
pme.match(&impl, lclauses->getOutgoingSet(), fv.varlist);
// The result_list contains a list of the grounded expressions.
// Turn it into a true list, and return it.
Handle gl = atom_space->addLink(LIST_LINK, impl.result_list);
return gl;
}
/* ===================== END OF FILE ===================== */
<commit_msg>provide additional documentation.<commit_after>/*
* PatternMatch.cc
*
* Copyright (C) 2009 Linas Vepstas
*
* Author: Linas Vepstas <linasvepstas@gmail.com> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "PatternMatch.h"
#include "DefaultPatternMatchCB.h"
#include <opencog/util/platform.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/util/Logger.h>
using namespace opencog;
PatternMatch::PatternMatch(void)
{
atom_space = NULL;
}
/* ================================================================= */
/**
* Solve a predicate by pattern matching.
* The predicate is defined in terms of two hypergraphs: one is a
* hypergraph defining a pattern to be matched for, and the other is a
* list of bound variables in the first.
*
* The bound variables are, by definition, nodes. (XXX It might be
* useful to loosen this restriction someday). The list of bound variables
* is then assumed to be listed using the ListLink type. So, for
* example:
*
* ListLink
* SomeNode "variable 1"
* SomeOtherNode "another variable"
*
* The predicate hypergraph is assumed to be a list of "clauses", where
* each "clause" is a tree. The clauses are assumed to be connected,
* i.e. share common nodes or links. The algorithm to find solutions
* will fail on disconnected hypergraphs. The list of clauses is
* specified by means of an AndLink, so, for example:
*
* AndLink
* SomeLink ....
* SomeOtherLink ...
*
* The solution proceeds by requiring each clause to match some part of
* the atomspace (i.e. of the universe of hypergraphs stored in the
* atomspace). When a solution is found, PatternMatchCallback::solution
* method is called, and it is passed two maps: one mapping the bound
* variables to thier solutions, and the other mapping the pattern
* clauses to thier corresponding solution clauses.
*
* At this time, the list of clauses is understood to be a single
* disjunct; that is, all of the clauses must be simultaneously
* satisfied. Thus, in principle, one could build a layer on top of
* this that accepts clauses in disjunctive normal form (and so on...)
* It is not clear at this time how to benefit from Boolean SAT solver
* technlogy (or at what point this would be needed).
*/
void PatternMatch::match(PatternMatchCallback *cb,
Handle hclauses,
Handle hvarbles)
{
Atom * aclauses = TLB::getAtom(hclauses);
Atom * avarbles = TLB::getAtom(hvarbles);
Link * lclauses = dynamic_cast<Link *>(aclauses);
Link * lvarbles = dynamic_cast<Link *>(avarbles);
// Both must be non-empty.
if (!lclauses || !lvarbles) return;
// Types must be as expected
Type tclauses = lclauses->getType();
Type tvarbles = lvarbles->getType();
if (AND_LINK != tclauses)
{
logger().warn("%s: expected AndLink for clause list", __FUNCTION__);
return;
}
if (LIST_LINK != tvarbles)
{
logger().warn("%s: expected ListLink for bound variable list", __FUNCTION__);
return;
}
pme.match(cb, lclauses->getOutgoingSet(), lvarbles->getOutgoingSet());
}
/* ================================================================= */
// Handy dandy utility class.
//
class FindVariables
{
public:
std::vector<Handle> varlist;
/**
* Create a list of all of the VariableNodes that lie in the
* outgoing set of the handle (recursively).
*/
inline bool find_vars(Handle h)
{
Atom *a = TLB::getAtom(h);
Node *n = dynamic_cast<Node *>(a);
if (n)
{
if (n->getType() == VARIABLE_NODE)
{
varlist.push_back(h);
}
return false;
}
return foreach_outgoing_handle(h, &FindVariables::find_vars, this);
}
};
/* ================================================================= */
/**
* class Instantiator -- create grounded expressions from ungrounded ones.
* Given an ungrounded expression (i.e. an expression containing variables)
* and a map between variables and ground terms, it will create a new
* expression, with the ground terms substituted for the variables.
*/
class Instantiator
{
private:
std::map<Handle, Handle> *vmap;
std::vector<Handle> oset;
bool walk_tree(Handle tree);
public:
AtomSpace *as;
Handle instantiate(Handle expr, std::map<Handle, Handle> &vars);
};
bool Instantiator::walk_tree(Handle expr)
{
Atom *a = TLB::getAtom(expr);
Type t = a->getType();
Node *n = dynamic_cast<Node *>(a);
if (n)
{
if (VARIABLE_NODE != t)
{
oset.push_back(expr);
return false;
}
// If we are here, we found a variable. Look it up.
std::map<Handle,Handle>::const_iterator it = vmap->find(expr);
if (vmap->end() != it)
{
Handle soln = it->second;
oset.push_back(soln);
}
else
{
oset.push_back(expr);
}
return false;
}
// If we are here, then we have a link. Walk it.
std::vector<Handle> save_oset = oset;
oset.clear();
// Walk the subtree, substituting values for variables.
foreach_outgoing_handle(expr, &Instantiator::walk_tree, this);
// Now create a duplicate link, but with an outgoing set where
// the variables have been substituted by thier values.
Handle sh = as->addLink(t, oset);
oset = save_oset;
oset.push_back(sh);
return false;
}
/**
* Given a handle to an ungrounded expression, and a set of groundings,
* this will create a grounded expression.
*
* The set of groundings is to be passed in with the map 'vars', which
* maps variable names to thier groundings -- it maps variable names to
* atoms that already exist in the atomspace. This method will then go
* through all of the variables in the expression, and substitute them
* with thier values, creating a new expression. The new expression is
* added to the atomspace, and its handle is returned.
*/
Handle Instantiator::instantiate(Handle expr, std::map<Handle, Handle> &vars)
{
vmap = &vars;
walk_tree(expr);
if (oset.size() != 1)
{
logger().warn("%s: outgoing set size %d is insane!",
__FUNCTION__, oset.size());
}
return oset[0];
}
/* ================================================================= */
/**
* class Implicator -- pattern matching callback for grounding implicands.
*
* This class is meant to be used with the pattern matcher. When the
* pattern matcher calls the callback, it will do so with a particular
* grounding of the search pattern. This class then holds an ungrounded
* implicand, and will create a grounded version of the implicand.
*
* The 'var_soln' argument in the callback contains the map from variables
* to ground terms. 'class Instantiator' is used to perform the actual
* grounding. A list of grounded expressions is created in 'result_list'.
*/
class Implicator :
public DefaultPatternMatchCB
{
private:
Instantiator inst;
public:
AtomSpace *as;
Handle implicand;
std::vector<Handle> result_list;
virtual bool solution(std::map<Handle, Handle> &pred_soln,
std::map<Handle, Handle> &var_soln);
};
bool Implicator::solution(std::map<Handle, Handle> &pred_soln,
std::map<Handle, Handle> &var_soln)
{
inst.as = as;
Handle h = inst.instantiate(implicand, var_soln);
result_list.push_back(h);
return false;
}
/* ================================================================= */
/**
* Evaluate an ImplicationLink.
* Given an ImplicationLink, this method will "evaluate" it, matching
* the predicate, and creating a grounded implicand, assuming the
* predicate can be satisfied. Thus, for example, given the structure
*
* ImplicationLink
* AndList
* EvaluationList
* PredicateNode "_obj"
* ListLink
* ConceptNode "make"
* VariableNode $var0
* EvaluationList
* PredicateNode "from"
* ListLink
* ConceptNode "make"
* VariableNode $var1"
* EvaluationList
* PredicateNode "make_from"
* ListLink
* VariableNode $var0
* VariableNode $var1
*
* Then, if the atomspace also contains a parsed version of the English
* sentence "Pottery is made from clay", that is, if it contains the
* hypergraph
*
* EvaluationList
* PredicateNode "_obj"
* ListLink
* ConceptNode "make"
* ConceptNode "pottery"
*
* and the hypergraph
*
* EvaluationList
* PredicateNode "from"
* ListLink
* ConceptNode "make"
* ConceptNode "clay"
*
* Then, by pattern matching, the predicate part of the ImplicationLink
* can be fulfilled, binding $var0 to "pottery" and $var1 to "clay".
* These bindings are refered to as the 'groundings' or 'solutions'
* to the variables. So, e.g. $var0 is 'grounded' by "pottery".
*
* Next, a grounded copy of the implicand is then created; that is,
* the following hypergraph is created and added to the atomspace:
*
* EvaluationList
* PredicateNode "make_from"
* ListLink
* ConceptNode "pottery"
* ConceptNode "clay"
*
* As the above example illustrates, this function expects that the
* input handle is an implication link. It expects the implication link
* to consist entirely of one disjunct (one AndList) and one (ungrounded)
* implicand. All variables are implicit, and are identified by being
* VariableNodes. These variables are interpreted as 'free variables'
* having no binding. The act of pattern-matching to the predicate of
* the implication has an implicit 'for-all' flavour to it: the pattern
* is matched to 'all' matches in the atomspace.
*
* When a pattern match is found, the variables can be understood as
* being grounded by some explicit ground terms in the atomspace. This
* grounding is then used to create a grounded version of the
* (ungrounded) implicand. That is, the variables in the implicand are
* substituted by thier grounding values. This method then returns a
* list of all of the grounded implicands that were created.
*
* Note that this method can be used to create a simple forward-chainer:
* One need only to take a set of implication links, and call this
* method repeatedly on them, until one is exhausted.
*/
Handle PatternMatch::imply (Handle himplication)
{
Atom * aimpl = TLB::getAtom(himplication);
Link * limpl = dynamic_cast<Link *>(aimpl);
// Must be non-empty.
if (!limpl) return Handle::UNDEFINED;
// Type must be as expected
Type timpl = limpl->getType();
if (IMPLICATION_LINK != timpl)
{
logger().warn("%s: expected ImplicationLink", __FUNCTION__);
return Handle::UNDEFINED;
}
const std::vector<Handle>& oset = limpl->getOutgoingSet();
if (2 != oset.size())
{
logger().warn("%s: ImplicationLink has wrong size", __FUNCTION__);
return Handle::UNDEFINED;
}
Handle hclauses = oset[0];
Handle implicand = oset[1];
Atom * aclauses = TLB::getAtom(hclauses);
Link * lclauses = dynamic_cast<Link *>(aclauses);
// Must be non-empty.
if (!lclauses) return Handle::UNDEFINED;
// Types must be as expected
Type tclauses = lclauses->getType();
if (AND_LINK != tclauses)
{
logger().warn("%s: expected AndLink for clause list", __FUNCTION__);
return Handle::UNDEFINED;
}
// Extract a list of variables.
FindVariables fv;
fv.find_vars(hclauses);
// Now perform the search.
Implicator impl;
impl.implicand = implicand;
impl.as = atom_space;
pme.match(&impl, lclauses->getOutgoingSet(), fv.varlist);
// The result_list contains a list of the grounded expressions.
// Turn it into a true list, and return it.
Handle gl = atom_space->addLink(LIST_LINK, impl.result_list);
return gl;
}
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>/*
* opencog/server/ListRequest.cc
*
* Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
* All Rights Reserved
*
* Written by Gustavo Gama <gama@vettalabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ListRequest.h"
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/atomspace/types.h>
#include <opencog/server/CogServer.h>
using namespace opencog;
ListRequest::ListRequest()
{
}
ListRequest::~ListRequest()
{
logger().debug("[ListRequest] destructor");
}
bool ListRequest::syntaxError()
{
_error << "invalid syntax" << std::endl;
sendError();
return false;
}
bool ListRequest::execute()
{
std::string name = "";
Type type = NOTYPE;
Handle handle = Handle::UNDEFINED;
bool subtypes = false;
AtomSpace* as = server().getAtomSpace();
std::ostringstream err;
std::list<std::string>::const_iterator it;
for (it = _parameters.begin(); it != _parameters.end(); ++it) {
if (*it == "-h") { // filter by handle
++it;
if (it == _parameters.end()) return syntaxError();
UUID uuid = strtol((*it).c_str(), NULL, 0);
handle = Handle(uuid);
if (TLB::isInvalidHandle(handle)) {
_error << "invalid handle" << std::endl;
sendError();
return false;
}
_handles.push_back(handle);
} else if (*it == "-n") { // filter by name
++it;
if (it == _parameters.end()) return syntaxError();
name.assign(*it);
} else if (*it == "-t") { // filter by type, excluding subtypes
++it;
if (it == _parameters.end()) return syntaxError();
type = classserver().getType((*it).c_str());
if (type == NOTYPE) {
_error << "invalid type" << std::endl;
sendError();
return false;
}
} else if (*it == "-T") { // filter by type, including subtypes
++it;
if (it == _parameters.end()) return syntaxError();
type = classserver().getType((*it).c_str());
if (type == NOTYPE) {
_error << "invalid type" << std::endl;
sendError();
return false;
}
subtypes = true;
}
}
if (name != "" && type != NOTYPE) { // filter by name & type
_handles.push_back(as->getHandle(type, name.c_str()));
} else if (name != "") { // filter by name
as->getHandleSet(std::back_inserter(_handles), ATOM, name.c_str(), true);
} else if (type != NOTYPE) { // filter by type
as->getHandleSet(std::back_inserter(_handles), type, subtypes);
} else {
as->getHandleSet(back_inserter(_handles), ATOM, true);
}
sendOutput();
return true;
}
void ListRequest::sendOutput() const
{
std::ostringstream oss;
if (_mimeType == "text/plain") {
std::vector<Handle>::const_iterator it;
for (it = _handles.begin(); it != _handles.end(); ++it) {
Atom* atom = TLB::getAtom(*it);
oss << atom->toString() << std::endl;
}
} else throw RuntimeException(TRACE_INFO, "Unsupported mime-type: %s", _mimeType.c_str());
send(oss.str());
}
void ListRequest::sendError() const
{
if (_mimeType != "text/plain")
throw RuntimeException(TRACE_INFO, "Unsupported mime-type: %s", _mimeType.c_str());
send(_error.str());
}
<commit_msg>Apply patch from David Crane <dncrane@gmail.com> email: [opencog-dev] list command doesn't worth properly with -T <type> -n <name><commit_after>/*
* opencog/server/ListRequest.cc
*
* Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
* All Rights Reserved
*
* Written by Gustavo Gama <gama@vettalabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ListRequest.h"
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/atomspace/types.h>
#include <opencog/server/CogServer.h>
using namespace opencog;
ListRequest::ListRequest()
{
}
ListRequest::~ListRequest()
{
logger().debug("[ListRequest] destructor");
}
bool ListRequest::syntaxError()
{
_error << "invalid syntax" << std::endl;
sendError();
return false;
}
bool ListRequest::execute()
{
std::string name = "";
Type type = NOTYPE;
Handle handle = Handle::UNDEFINED;
bool subtypes = false;
AtomSpace* as = server().getAtomSpace();
std::ostringstream err;
std::list<std::string>::const_iterator it;
for (it = _parameters.begin(); it != _parameters.end(); ++it) {
if (*it == "-h") { // filter by handle
++it;
if (it == _parameters.end()) return syntaxError();
UUID uuid = strtol((*it).c_str(), NULL, 0);
handle = Handle(uuid);
if (TLB::isInvalidHandle(handle)) {
_error << "invalid handle" << std::endl;
sendError();
return false;
}
_handles.push_back(handle);
} else if (*it == "-n") { // filter by name
++it;
if (it == _parameters.end()) return syntaxError();
name.assign(*it);
} else if (*it == "-t") { // filter by type, excluding subtypes
++it;
if (it == _parameters.end()) return syntaxError();
type = classserver().getType((*it).c_str());
if (type == NOTYPE) {
_error << "invalid type" << std::endl;
sendError();
return false;
}
} else if (*it == "-T") { // filter by type, including subtypes
++it;
if (it == _parameters.end()) return syntaxError();
type = classserver().getType((*it).c_str());
if (type == NOTYPE) {
_error << "invalid type" << std::endl;
sendError();
return false;
}
subtypes = true;
}
}
if (name != "" && type != NOTYPE) { // filter by name & type
as->getHandleSet
(std::back_inserter(_handles), type, name.c_str(), subtypes);
} else if (name != "") { // filter by name
as->getHandleSet(std::back_inserter(_handles), ATOM, name.c_str(), true);
} else if (type != NOTYPE) { // filter by type
as->getHandleSet(std::back_inserter(_handles), type, subtypes);
} else {
as->getHandleSet(back_inserter(_handles), ATOM, true);
}
sendOutput();
return true;
}
void ListRequest::sendOutput() const
{
std::ostringstream oss;
if (_mimeType == "text/plain") {
std::vector<Handle>::const_iterator it;
for (it = _handles.begin(); it != _handles.end(); ++it) {
Atom* atom = TLB::getAtom(*it);
oss << atom->toString() << std::endl;
}
} else throw RuntimeException(TRACE_INFO, "Unsupported mime-type: %s", _mimeType.c_str());
send(oss.str());
}
void ListRequest::sendError() const
{
if (_mimeType != "text/plain")
throw RuntimeException(TRACE_INFO, "Unsupported mime-type: %s", _mimeType.c_str());
send(_error.str());
}
<|endoftext|> |
<commit_before>#include "parsing/utf8.hpp"
#include <string>
#include <string.h>
#include "rdb_protocol/datum_string.hpp"
namespace utf8 {
static unsigned int HIGH_BIT = 0x80;
static unsigned int HIGH_TWO_BITS = 0xC0;
static unsigned int HIGH_THREE_BITS = 0xE0;
static unsigned int HIGH_FOUR_BITS = 0xF0;
static unsigned int HIGH_FIVE_BITS = 0xF8;
inline bool is_standalone(char c) {
// 0xxxxxxx - ASCII character
return (c & HIGH_BIT) == 0;
}
inline bool is_twobyte_start(char c) {
// 110xxxxx - two character multibyte
return (c & HIGH_THREE_BITS) == HIGH_TWO_BITS;
}
inline bool is_threebyte_start(char c) {
// 1110xxxx - three character multibyte
return (c & HIGH_FOUR_BITS) == HIGH_THREE_BITS;
}
inline bool is_fourbyte_start(char c) {
// 11110xxx - four character multibyte
return (c & HIGH_FIVE_BITS) == HIGH_FOUR_BITS;
}
inline bool is_continuation(char c) {
// 10xxxxxx - continuation character
return ((c & HIGH_TWO_BITS) != HIGH_BIT);
}
inline unsigned int continuation_data(char c) {
return ((c & ~HIGH_TWO_BITS) & 0xFF);
}
inline unsigned int extract_bits(char c, unsigned int bits) {
return ((c & ~bits) & 0xFF);
}
inline unsigned int extract_and_shift(char c, unsigned int bits, unsigned int amount) {
return extract_bits(c, bits) << amount;
}
template <class Iterator>
inline bool check_continuation(const Iterator & p, const Iterator & end,
size_t position, reason_t * reason) {
if (p == end) {
reason->position = position;
reason->explanation = "Expected continuation byte, saw end of string";
return false;
}
if (is_continuation(*p)) {
reason->position = position;
reason->explanation = "Expected continuation byte, saw something else";
return false;
}
return true;
}
template <class Iterator>
inline bool is_valid_internal(const Iterator & begin, const Iterator & end,
reason_t *reason) {
Iterator p = begin;
size_t position = 0;
while (p != end) {
if (is_standalone(*p)) {
// 0xxxxxxx - ASCII character
;
} else if (is_twobyte_start(*p)) {
// 110xxxxx - two character multibyte
unsigned int result = extract_and_shift(*p, HIGH_THREE_BITS, 6);
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p);
if (result < 0x0080) {
// can be represented in one byte, so using two is illegal
reason->position = position;
reason->explanation = "Overlong encoding seen";
return false;
}
} else if (is_threebyte_start(*p)) {
// 1110xxxx - three character multibyte
unsigned int result = extract_and_shift(*p, HIGH_FOUR_BITS, 12);
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p) << 6;
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p);
if (result < 0x0800) {
// can be represented in two bytes, so using three is illegal
reason->position = position;
reason->explanation = "Overlong encoding seen";
return false;
}
} else if (is_fourbyte_start(*p)) {
// 11110xxx - four character multibyte
unsigned int result = extract_and_shift(*p, HIGH_FIVE_BITS, 18);
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p) << 12;
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p) << 6;
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p);
if (result < 0x10000) {
// can be represented in three bytes, so using four is illegal
reason->position = position;
reason->explanation = "Overlong encoding seen";
return false;
}
if (result > 0x10FFFF) {
// UTF-8 defined by RFC 3629 to end at U+10FFFF now
reason->position = position;
reason->explanation = "Non-Unicode character encoded (beyond U+10FFFF)";
return false;
}
} else {
// high bit character outside of a surrogate context
reason->position = position;
reason->explanation = "Invalid initial byte seen";
return false;
}
++p; ++position;
}
return true;
}
bool is_valid(const datum_string_t &str) {
reason_t reason;
return is_valid_internal(str.data(), str.data() + str.size(), &reason);
}
bool is_valid(const std::string &str) {
reason_t reason;
return is_valid_internal(str.begin(), str.end(), &reason);
}
bool is_valid(const char *start, const char *end) {
reason_t reason;
return is_valid_internal(start, end, &reason);
}
bool is_valid(const char *str) {
reason_t reason;
size_t len = strlen(str);
const char *end = str + len;
return is_valid_internal(str, end, &reason);
}
bool is_valid(const datum_string_t &str, reason_t *reason) {
return is_valid_internal(str.data(), str.data() + str.size(), reason);
}
bool is_valid(const std::string &str, reason_t *reason) {
return is_valid_internal(str.begin(), str.end(), reason);
}
bool is_valid(const char *start, const char *end, reason_t *reason) {
return is_valid_internal(start, end, reason);
}
bool is_valid(const char *str, reason_t *reason) {
size_t len = strlen(str);
const char *end = str + len;
return is_valid_internal(str, end, reason);
}
};
<commit_msg>Convert `continuation_data` to use `extract_bits`.<commit_after>#include "parsing/utf8.hpp"
#include <string>
#include <string.h>
#include "rdb_protocol/datum_string.hpp"
namespace utf8 {
static unsigned int HIGH_BIT = 0x80;
static unsigned int HIGH_TWO_BITS = 0xC0;
static unsigned int HIGH_THREE_BITS = 0xE0;
static unsigned int HIGH_FOUR_BITS = 0xF0;
static unsigned int HIGH_FIVE_BITS = 0xF8;
inline bool is_standalone(char c) {
// 0xxxxxxx - ASCII character
return (c & HIGH_BIT) == 0;
}
inline bool is_twobyte_start(char c) {
// 110xxxxx - two character multibyte
return (c & HIGH_THREE_BITS) == HIGH_TWO_BITS;
}
inline bool is_threebyte_start(char c) {
// 1110xxxx - three character multibyte
return (c & HIGH_FOUR_BITS) == HIGH_THREE_BITS;
}
inline bool is_fourbyte_start(char c) {
// 11110xxx - four character multibyte
return (c & HIGH_FIVE_BITS) == HIGH_FOUR_BITS;
}
inline bool is_continuation(char c) {
// 10xxxxxx - continuation character
return ((c & HIGH_TWO_BITS) != HIGH_BIT);
}
inline unsigned int extract_bits(char c, unsigned int bits) {
return ((c & ~bits) & 0xFF);
}
inline unsigned int continuation_data(char c) {
return extract_bits(c, HIGH_TWO_BITS);
}
inline unsigned int extract_and_shift(char c, unsigned int bits, unsigned int amount) {
return extract_bits(c, bits) << amount;
}
template <class Iterator>
inline bool check_continuation(const Iterator & p, const Iterator & end,
size_t position, reason_t * reason) {
if (p == end) {
reason->position = position;
reason->explanation = "Expected continuation byte, saw end of string";
return false;
}
if (is_continuation(*p)) {
reason->position = position;
reason->explanation = "Expected continuation byte, saw something else";
return false;
}
return true;
}
template <class Iterator>
inline bool is_valid_internal(const Iterator & begin, const Iterator & end,
reason_t *reason) {
Iterator p = begin;
size_t position = 0;
while (p != end) {
if (is_standalone(*p)) {
// 0xxxxxxx - ASCII character
;
} else if (is_twobyte_start(*p)) {
// 110xxxxx - two character multibyte
unsigned int result = extract_and_shift(*p, HIGH_THREE_BITS, 6);
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p);
if (result < 0x0080) {
// can be represented in one byte, so using two is illegal
reason->position = position;
reason->explanation = "Overlong encoding seen";
return false;
}
} else if (is_threebyte_start(*p)) {
// 1110xxxx - three character multibyte
unsigned int result = extract_and_shift(*p, HIGH_FOUR_BITS, 12);
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p) << 6;
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p);
if (result < 0x0800) {
// can be represented in two bytes, so using three is illegal
reason->position = position;
reason->explanation = "Overlong encoding seen";
return false;
}
} else if (is_fourbyte_start(*p)) {
// 11110xxx - four character multibyte
unsigned int result = extract_and_shift(*p, HIGH_FIVE_BITS, 18);
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p) << 12;
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p) << 6;
++p; ++position;
if (!check_continuation(p, end, position, reason)) return false;
result |= continuation_data(*p);
if (result < 0x10000) {
// can be represented in three bytes, so using four is illegal
reason->position = position;
reason->explanation = "Overlong encoding seen";
return false;
}
if (result > 0x10FFFF) {
// UTF-8 defined by RFC 3629 to end at U+10FFFF now
reason->position = position;
reason->explanation = "Non-Unicode character encoded (beyond U+10FFFF)";
return false;
}
} else {
// high bit character outside of a surrogate context
reason->position = position;
reason->explanation = "Invalid initial byte seen";
return false;
}
++p; ++position;
}
return true;
}
bool is_valid(const datum_string_t &str) {
reason_t reason;
return is_valid_internal(str.data(), str.data() + str.size(), &reason);
}
bool is_valid(const std::string &str) {
reason_t reason;
return is_valid_internal(str.begin(), str.end(), &reason);
}
bool is_valid(const char *start, const char *end) {
reason_t reason;
return is_valid_internal(start, end, &reason);
}
bool is_valid(const char *str) {
reason_t reason;
size_t len = strlen(str);
const char *end = str + len;
return is_valid_internal(str, end, &reason);
}
bool is_valid(const datum_string_t &str, reason_t *reason) {
return is_valid_internal(str.data(), str.data() + str.size(), reason);
}
bool is_valid(const std::string &str, reason_t *reason) {
return is_valid_internal(str.begin(), str.end(), reason);
}
bool is_valid(const char *start, const char *end, reason_t *reason) {
return is_valid_internal(start, end, reason);
}
bool is_valid(const char *str, reason_t *reason) {
size_t len = strlen(str);
const char *end = str + len;
return is_valid_internal(str, end, reason);
}
};
<|endoftext|> |
<commit_before>/*
* Copyright 2015 WebAssembly Community Group participants
*
* 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 <chrono>
#include <sstream>
#include <passes/passes.h>
#include <pass.h>
#include <wasm-validator.h>
namespace wasm {
// PassRegistry
PassRegistry::PassRegistry() {
registerPasses();
}
static PassRegistry singleton;
PassRegistry* PassRegistry::get() {
return &singleton;
}
void PassRegistry::registerPass(const char* name, const char *description, Creator create) {
assert(passInfos.find(name) == passInfos.end());
passInfos[name] = PassInfo(description, create);
}
Pass* PassRegistry::createPass(std::string name) {
if (passInfos.find(name) == passInfos.end()) return nullptr;
auto ret = passInfos[name].create();
ret->name = name;
return ret;
}
std::vector<std::string> PassRegistry::getRegisteredNames() {
std::vector<std::string> ret;
for (auto pair : passInfos) {
ret.push_back(pair.first);
}
return ret;
}
std::string PassRegistry::getPassDescription(std::string name) {
assert(passInfos.find(name) != passInfos.end());
return passInfos[name].description;
}
// PassRunner
void PassRegistry::registerPasses() {
registerPass("coalesce-locals", "reduce # of locals by coalescing", createCoalesceLocalsPass);
registerPass("coalesce-locals-learning", "reduce # of locals by coalescing and learning", createCoalesceLocalsWithLearningPass);
registerPass("dce", "removes unreachable code", createDeadCodeEliminationPass);
registerPass("duplicate-function-elimination", "removes duplicate functions", createDuplicateFunctionEliminationPass);
registerPass("extract-function", "leaves just one function (useful for debugging)", createExtractFunctionPass);
registerPass("legalize-js-interface", "legalizes i64 types on the import/export boundary", createLegalizeJSInterfacePass);
registerPass("merge-blocks", "merges blocks to their parents", createMergeBlocksPass);
registerPass("metrics", "reports metrics", createMetricsPass);
registerPass("nm", "name list", createNameListPass);
registerPass("name-manager", "utility pass to manage names in modules", createNameManagerPass);
registerPass("optimize-instructions", "optimizes instruction combinations", createOptimizeInstructionsPass);
registerPass("post-emscripten", "miscellaneous optimizations for Emscripten-generated code", createPostEmscriptenPass);
registerPass("print", "print in s-expression format", createPrinterPass);
registerPass("print-minified", "print in minified s-expression format", createMinifiedPrinterPass);
registerPass("print-full", "print in full s-expression format", createFullPrinterPass);
registerPass("relooper-jump-threading", "thread relooper jumps (fastcomp output only)", createRelooperJumpThreadingPass);
registerPass("remove-imports", "removes imports and replaces them with nops", createRemoveImportsPass);
registerPass("remove-memory", "removes memory segments", createRemoveMemoryPass);
registerPass("remove-unused-brs", "removes breaks from locations that are not needed", createRemoveUnusedBrsPass);
registerPass("remove-unused-functions", "removes unused functions", createRemoveUnusedFunctionsPass);
registerPass("remove-unused-names", "removes names from locations that are never branched to", createRemoveUnusedNamesPass);
registerPass("reorder-functions", "sorts functions by access frequency", createReorderFunctionsPass);
registerPass("reorder-locals", "sorts locals by access frequency", createReorderLocalsPass);
registerPass("simplify-locals", "miscellaneous locals-related optimizations", createSimplifyLocalsPass);
registerPass("vacuum", "removes obviously unneeded code", createVacuumPass);
registerPass("precompute", "computes compile-time evaluatable expressions", createPrecomputePass);
// registerPass("lower-i64", "lowers i64 into pairs of i32s", createLowerInt64Pass);
}
void PassRunner::addDefaultOptimizationPasses() {
add("duplicate-function-elimination");
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
add("duplicate-function-elimination"); // optimizations show more functions as duplicate
}
void PassRunner::addDefaultFunctionOptimizationPasses() {
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
}
void PassRunner::addDefaultGlobalOptimizationPasses() {
add("duplicate-function-elimination");
}
void PassRunner::run() {
if (debug) {
// for debug logging purposes, run each pass in full before running the other
auto totalTime = std::chrono::duration<double>(0);
size_t padding = 0;
std::cerr << "[PassRunner] running passes..." << std::endl;
for (auto pass : passes) {
padding = std::max(padding, pass->name.size());
}
bool passDebug = getenv("BINARYEN_PASS_DEBUG") && getenv("BINARYEN_PASS_DEBUG")[0] != '0';
for (auto* pass : passes) {
// ignoring the time, save a printout of the module before, in case this pass breaks it, so we can print the before and after
std::stringstream moduleBefore;
if (passDebug) {
WasmPrinter::printModule(wasm, moduleBefore);
}
// prepare to run
std::chrono::high_resolution_clock::time_point before;
std::cerr << "[PassRunner] running pass: " << pass->name << "... ";
for (size_t i = 0; i < padding - pass->name.size(); i++) {
std::cerr << ' ';
}
before = std::chrono::high_resolution_clock::now();
if (pass->isFunctionParallel()) {
// function-parallel passes should get a new instance per function
for (auto& func : wasm->functions) {
runPassOnFunction(pass, func.get());
}
} else {
pass->run(this, wasm);
}
auto after = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = after - before;
std::cerr << diff.count() << " seconds." << std::endl;
totalTime += diff;
// validate, ignoring the time
std::cerr << "[PassRunner] (validating)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
if (passDebug) {
std::cerr << "Last pass (" << pass->name << ") broke validation. Here is the module before: \n" << moduleBefore.str() << "\n";
} else {
std::cerr << "Last pass (" << pass->name << ") broke validation. Run with BINARYEN_PASS_DEBUG=1 in the env to see the earlier state\n";
}
abort();
}
}
std::cerr << "[PassRunner] passes took " << totalTime.count() << " seconds." << std::endl;
// validate
std::cerr << "[PassRunner] (final validation)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
std::cerr << "final module does not validate\n";
abort();
}
} else {
// non-debug normal mode, run them in an optimal manner - for locality it is better
// to run as many passes as possible on a single function before moving to the next
std::vector<Pass*> stack;
auto flush = [&]() {
if (stack.size() > 0) {
// run the stack of passes on all the functions, in parallel
size_t num = ThreadPool::get()->size();
std::vector<std::function<ThreadWorkState ()>> doWorkers;
std::atomic<size_t> nextFunction;
nextFunction.store(0);
size_t numFunctions = wasm->functions.size();
for (size_t i = 0; i < num; i++) {
doWorkers.push_back([&]() {
auto index = nextFunction.fetch_add(1);
// get the next task, if there is one
if (index >= numFunctions) {
return ThreadWorkState::Finished; // nothing left
}
Function* func = this->wasm->functions[index].get();
// do the current task: run all passes on this function
for (auto* pass : stack) {
runPassOnFunction(pass, func);
}
if (index + 1 == numFunctions) {
return ThreadWorkState::Finished; // we did the last one
}
return ThreadWorkState::More;
});
}
ThreadPool::get()->work(doWorkers);
}
stack.clear();
};
for (auto* pass : passes) {
if (pass->isFunctionParallel()) {
stack.push_back(pass);
} else {
flush();
pass->run(this, wasm);
}
}
flush();
}
}
void PassRunner::runFunction(Function* func) {
if (debug) {
std::cerr << "[PassRunner] running passes on function " << func->name << std::endl;
}
for (auto* pass : passes) {
runPassOnFunction(pass, func);
}
}
PassRunner::~PassRunner() {
for (auto pass : passes) {
delete pass;
}
}
void PassRunner::doAdd(Pass* pass) {
passes.push_back(pass);
pass->prepareToRun(this, wasm);
}
void PassRunner::runPassOnFunction(Pass* pass, Function* func) {
#if 0
if (debug) {
std::cerr << "[PassRunner] runPass " << pass->name << " OnFunction " << func->name << "\n";
}
#endif
// function-parallel passes get a new instance per function
if (pass->isFunctionParallel()) {
auto instance = std::unique_ptr<Pass>(pass->create());
instance->runFunction(this, wasm, func);
} else {
pass->runFunction(this, wasm, func);
}
}
} // namespace wasm
<commit_msg>reuse code in add*Passes<commit_after>/*
* Copyright 2015 WebAssembly Community Group participants
*
* 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 <chrono>
#include <sstream>
#include <passes/passes.h>
#include <pass.h>
#include <wasm-validator.h>
namespace wasm {
// PassRegistry
PassRegistry::PassRegistry() {
registerPasses();
}
static PassRegistry singleton;
PassRegistry* PassRegistry::get() {
return &singleton;
}
void PassRegistry::registerPass(const char* name, const char *description, Creator create) {
assert(passInfos.find(name) == passInfos.end());
passInfos[name] = PassInfo(description, create);
}
Pass* PassRegistry::createPass(std::string name) {
if (passInfos.find(name) == passInfos.end()) return nullptr;
auto ret = passInfos[name].create();
ret->name = name;
return ret;
}
std::vector<std::string> PassRegistry::getRegisteredNames() {
std::vector<std::string> ret;
for (auto pair : passInfos) {
ret.push_back(pair.first);
}
return ret;
}
std::string PassRegistry::getPassDescription(std::string name) {
assert(passInfos.find(name) != passInfos.end());
return passInfos[name].description;
}
// PassRunner
void PassRegistry::registerPasses() {
registerPass("coalesce-locals", "reduce # of locals by coalescing", createCoalesceLocalsPass);
registerPass("coalesce-locals-learning", "reduce # of locals by coalescing and learning", createCoalesceLocalsWithLearningPass);
registerPass("dce", "removes unreachable code", createDeadCodeEliminationPass);
registerPass("duplicate-function-elimination", "removes duplicate functions", createDuplicateFunctionEliminationPass);
registerPass("extract-function", "leaves just one function (useful for debugging)", createExtractFunctionPass);
registerPass("legalize-js-interface", "legalizes i64 types on the import/export boundary", createLegalizeJSInterfacePass);
registerPass("merge-blocks", "merges blocks to their parents", createMergeBlocksPass);
registerPass("metrics", "reports metrics", createMetricsPass);
registerPass("nm", "name list", createNameListPass);
registerPass("name-manager", "utility pass to manage names in modules", createNameManagerPass);
registerPass("optimize-instructions", "optimizes instruction combinations", createOptimizeInstructionsPass);
registerPass("post-emscripten", "miscellaneous optimizations for Emscripten-generated code", createPostEmscriptenPass);
registerPass("print", "print in s-expression format", createPrinterPass);
registerPass("print-minified", "print in minified s-expression format", createMinifiedPrinterPass);
registerPass("print-full", "print in full s-expression format", createFullPrinterPass);
registerPass("relooper-jump-threading", "thread relooper jumps (fastcomp output only)", createRelooperJumpThreadingPass);
registerPass("remove-imports", "removes imports and replaces them with nops", createRemoveImportsPass);
registerPass("remove-memory", "removes memory segments", createRemoveMemoryPass);
registerPass("remove-unused-brs", "removes breaks from locations that are not needed", createRemoveUnusedBrsPass);
registerPass("remove-unused-functions", "removes unused functions", createRemoveUnusedFunctionsPass);
registerPass("remove-unused-names", "removes names from locations that are never branched to", createRemoveUnusedNamesPass);
registerPass("reorder-functions", "sorts functions by access frequency", createReorderFunctionsPass);
registerPass("reorder-locals", "sorts locals by access frequency", createReorderLocalsPass);
registerPass("simplify-locals", "miscellaneous locals-related optimizations", createSimplifyLocalsPass);
registerPass("vacuum", "removes obviously unneeded code", createVacuumPass);
registerPass("precompute", "computes compile-time evaluatable expressions", createPrecomputePass);
// registerPass("lower-i64", "lowers i64 into pairs of i32s", createLowerInt64Pass);
}
void PassRunner::addDefaultOptimizationPasses() {
add("duplicate-function-elimination");
addDefaultFunctionOptimizationPasses();
add("duplicate-function-elimination"); // optimizations show more functions as duplicate
}
void PassRunner::addDefaultFunctionOptimizationPasses() {
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
}
void PassRunner::addDefaultGlobalOptimizationPasses() {
add("duplicate-function-elimination");
}
void PassRunner::run() {
if (debug) {
// for debug logging purposes, run each pass in full before running the other
auto totalTime = std::chrono::duration<double>(0);
size_t padding = 0;
std::cerr << "[PassRunner] running passes..." << std::endl;
for (auto pass : passes) {
padding = std::max(padding, pass->name.size());
}
bool passDebug = getenv("BINARYEN_PASS_DEBUG") && getenv("BINARYEN_PASS_DEBUG")[0] != '0';
for (auto* pass : passes) {
// ignoring the time, save a printout of the module before, in case this pass breaks it, so we can print the before and after
std::stringstream moduleBefore;
if (passDebug) {
WasmPrinter::printModule(wasm, moduleBefore);
}
// prepare to run
std::chrono::high_resolution_clock::time_point before;
std::cerr << "[PassRunner] running pass: " << pass->name << "... ";
for (size_t i = 0; i < padding - pass->name.size(); i++) {
std::cerr << ' ';
}
before = std::chrono::high_resolution_clock::now();
if (pass->isFunctionParallel()) {
// function-parallel passes should get a new instance per function
for (auto& func : wasm->functions) {
runPassOnFunction(pass, func.get());
}
} else {
pass->run(this, wasm);
}
auto after = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = after - before;
std::cerr << diff.count() << " seconds." << std::endl;
totalTime += diff;
// validate, ignoring the time
std::cerr << "[PassRunner] (validating)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
if (passDebug) {
std::cerr << "Last pass (" << pass->name << ") broke validation. Here is the module before: \n" << moduleBefore.str() << "\n";
} else {
std::cerr << "Last pass (" << pass->name << ") broke validation. Run with BINARYEN_PASS_DEBUG=1 in the env to see the earlier state\n";
}
abort();
}
}
std::cerr << "[PassRunner] passes took " << totalTime.count() << " seconds." << std::endl;
// validate
std::cerr << "[PassRunner] (final validation)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
std::cerr << "final module does not validate\n";
abort();
}
} else {
// non-debug normal mode, run them in an optimal manner - for locality it is better
// to run as many passes as possible on a single function before moving to the next
std::vector<Pass*> stack;
auto flush = [&]() {
if (stack.size() > 0) {
// run the stack of passes on all the functions, in parallel
size_t num = ThreadPool::get()->size();
std::vector<std::function<ThreadWorkState ()>> doWorkers;
std::atomic<size_t> nextFunction;
nextFunction.store(0);
size_t numFunctions = wasm->functions.size();
for (size_t i = 0; i < num; i++) {
doWorkers.push_back([&]() {
auto index = nextFunction.fetch_add(1);
// get the next task, if there is one
if (index >= numFunctions) {
return ThreadWorkState::Finished; // nothing left
}
Function* func = this->wasm->functions[index].get();
// do the current task: run all passes on this function
for (auto* pass : stack) {
runPassOnFunction(pass, func);
}
if (index + 1 == numFunctions) {
return ThreadWorkState::Finished; // we did the last one
}
return ThreadWorkState::More;
});
}
ThreadPool::get()->work(doWorkers);
}
stack.clear();
};
for (auto* pass : passes) {
if (pass->isFunctionParallel()) {
stack.push_back(pass);
} else {
flush();
pass->run(this, wasm);
}
}
flush();
}
}
void PassRunner::runFunction(Function* func) {
if (debug) {
std::cerr << "[PassRunner] running passes on function " << func->name << std::endl;
}
for (auto* pass : passes) {
runPassOnFunction(pass, func);
}
}
PassRunner::~PassRunner() {
for (auto pass : passes) {
delete pass;
}
}
void PassRunner::doAdd(Pass* pass) {
passes.push_back(pass);
pass->prepareToRun(this, wasm);
}
void PassRunner::runPassOnFunction(Pass* pass, Function* func) {
#if 0
if (debug) {
std::cerr << "[PassRunner] runPass " << pass->name << " OnFunction " << func->name << "\n";
}
#endif
// function-parallel passes get a new instance per function
if (pass->isFunctionParallel()) {
auto instance = std::unique_ptr<Pass>(pass->create());
instance->runFunction(this, wasm, func);
} else {
pass->runFunction(this, wasm, func);
}
}
} // namespace wasm
<|endoftext|> |
<commit_before>// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PBLOG_STORE_HPP_
#define PBLOG_STORE_HPP_
#include <pblog/pblog.h>
#include <pblog/protocol.pb.h>
#include <pblog/stream.hpp>
#include <vector>
#include <apr_pools.h>
namespace pblog {
using ::std::vector;
using ::std::string;
class PBLOG_EXPORT Store {
public:
/** construct a store from a filesystem path */
Store(const char *path);
Store(const char *path, apr_pool_t *p);
~Store();
/** return the path to this store */
const char * path();
/** obtain a list of the buckets in the store */
vector<string> * buckets();
/** list of stream sets in a bucket */
vector<string> * stream_sets_in_bucket(const string bucket);
/** list of streams in stream set */
vector<string> * streams_in_stream_set(const string bucket, const string stream_set);
vector<string> * stream_paths();
string bucket_path(const string bucket);
string bucket_directory(const string bucket);
string stream_set_path(const string bucket, string stream_set);
string stream_set_directory(const string bucket, const string stream_set);
string stream_path(const string bucket, const string stream_set, const string stream);
string path_to_filesystem_path(const string path);
bool stream_info(const string bucket, const string stream_set, const string stream, protocol::StreamInfo &info);
bool stream_set_info(const string bucket, string stream_set, protocol::StreamSetInfo &info);
bool bucket_info(const string bucket, protocol::BucketInfo &info);
bool store_info(protocol::StoreInfo &info);
bool parse_stream_path(const string path, string &bucket, string &set, string &stream);
bool get_input_stream(const string path, InputStream &s);
bool get_input_stream(const string bucket, const string stream_set, const string stream, InputStream &s);
protected:
vector<string> * directories_in_directory(const string dir);
vector<string> * files_in_directory(const string dir);
private:
const char* _path;
apr_pool_t* _p;
};
} // namespace pblog
#endif
<commit_msg>add comment about thread safety<commit_after>// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PBLOG_STORE_HPP_
#define PBLOG_STORE_HPP_
#include <pblog/pblog.h>
#include <pblog/protocol.pb.h>
#include <pblog/stream.hpp>
#include <vector>
#include <apr_pools.h>
namespace pblog {
using ::std::vector;
using ::std::string;
// represents a stream store
// functions are reentrant and thread-safe unless otherwise specified
class PBLOG_EXPORT Store {
public:
/** construct a store from a filesystem path */
Store(const char *path);
Store(const char *path, apr_pool_t *p);
~Store();
/** return the path to this store */
const char * path();
/** obtain a list of the buckets in the store */
vector<string> * buckets();
/** list of stream sets in a bucket */
vector<string> * stream_sets_in_bucket(const string bucket);
/** list of streams in stream set */
vector<string> * streams_in_stream_set(const string bucket, const string stream_set);
vector<string> * stream_paths();
string bucket_path(const string bucket);
string bucket_directory(const string bucket);
string stream_set_path(const string bucket, string stream_set);
string stream_set_directory(const string bucket, const string stream_set);
string stream_path(const string bucket, const string stream_set, const string stream);
string path_to_filesystem_path(const string path);
bool stream_info(const string bucket, const string stream_set, const string stream, protocol::StreamInfo &info);
bool stream_set_info(const string bucket, string stream_set, protocol::StreamSetInfo &info);
bool bucket_info(const string bucket, protocol::BucketInfo &info);
bool store_info(protocol::StoreInfo &info);
bool parse_stream_path(const string path, string &bucket, string &set, string &stream);
bool get_input_stream(const string path, InputStream &s);
bool get_input_stream(const string bucket, const string stream_set, const string stream, InputStream &s);
protected:
vector<string> * directories_in_directory(const string dir);
vector<string> * files_in_directory(const string dir);
private:
const char* _path;
apr_pool_t* _p;
};
} // namespace pblog
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "init.hh"
#include "supervisor.hh"
#include "directories.hh"
#include "distributed_loader.hh"
#include "disk-error-handler.hh"
namespace utils {
static future<> disk_sanity(fs::path path, bool developer_mode) {
return check_direct_io_support(path.native()).then([] {
return make_ready_future<>();
}).handle_exception([path](auto ep) {
startlog.error("Could not access {}: {}", path, ep);
return make_exception_future<>(ep);
});
};
future<> directories::touch_and_lock(fs::path path) {
return io_check([path] { return recursive_touch_directory(path.native()); }).then_wrapped([this, path] (future<> f) {
try {
f.get();
return file_lock::acquire(path / ".lock").then([this](file_lock lock) {
_locks.emplace_back(std::move(lock));
}).handle_exception([path](auto ep) {
// only do this because "normal" unhandled exception exit in seastar
// _drops_ system_error message ("what()") and thus does not quite deliver
// the relevant info to the user
try {
std::rethrow_exception(ep);
} catch (std::exception& e) {
startlog.error("Could not initialize {}: {}", path, e.what());
throw;
} catch (...) {
throw;
}
});
} catch (...) {
startlog.error("Directory '{}' cannot be initialized. Tried to do it but failed with: {}", path, std::current_exception());
throw;
}
});
}
static void add(fs::path path, std::vector<fs::path>& to) {
to.push_back(path);
}
static void add(sstring path, std::vector<fs::path>& to) {
add(fs::path(path), to);
}
static void add(std::vector<sstring> paths, std::vector<fs::path>& to) {
for (auto& path : paths) {
add(path, to);
}
}
static void add_sharded(sstring p, std::vector<fs::path>& to) {
fs::path path(p);
for (unsigned i = 0; i < smp::count; i++) {
add(path / seastar::to_sstring(i).c_str(), to);
}
}
future<> directories::init(db::config& cfg, bool hinted_handoff_enabled) {
std::vector<fs::path> paths;
add(cfg.data_file_directories(), paths);
add(cfg.commitlog_directory(), paths);
if (hinted_handoff_enabled) {
add_sharded(cfg.hints_directory(), paths);
}
add_sharded(cfg.view_hints_directory(), paths);
supervisor::notify("creating and verifying directories");
return parallel_for_each(paths, [this, &cfg] (fs::path path) {
return touch_and_lock(path).then([path = std::move(path), &cfg] {
return disk_sanity(path, cfg.developer_mode()).then([path = std::move(path)] {
return distributed_loader::verify_owner_and_mode(path).handle_exception([](auto ep) {
startlog.error("Failed owner and mode verification: {}", ep);
return make_exception_future<>(ep);
});
});
});
});
}
} // namespace utils
<commit_msg>directories: Keep a unique set of directories to initialize<commit_after>/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "init.hh"
#include "supervisor.hh"
#include "directories.hh"
#include "distributed_loader.hh"
#include "disk-error-handler.hh"
namespace utils {
static future<> disk_sanity(fs::path path, bool developer_mode) {
return check_direct_io_support(path.native()).then([] {
return make_ready_future<>();
}).handle_exception([path](auto ep) {
startlog.error("Could not access {}: {}", path, ep);
return make_exception_future<>(ep);
});
};
future<> directories::touch_and_lock(fs::path path) {
return io_check([path] { return recursive_touch_directory(path.native()); }).then_wrapped([this, path] (future<> f) {
try {
f.get();
return file_lock::acquire(path / ".lock").then([this](file_lock lock) {
_locks.emplace_back(std::move(lock));
}).handle_exception([path](auto ep) {
// only do this because "normal" unhandled exception exit in seastar
// _drops_ system_error message ("what()") and thus does not quite deliver
// the relevant info to the user
try {
std::rethrow_exception(ep);
} catch (std::exception& e) {
startlog.error("Could not initialize {}: {}", path, e.what());
throw;
} catch (...) {
throw;
}
});
} catch (...) {
startlog.error("Directory '{}' cannot be initialized. Tried to do it but failed with: {}", path, std::current_exception());
throw;
}
});
}
static void add(fs::path path, std::set<fs::path>& to) {
to.insert(path);
}
static void add(sstring path, std::set<fs::path>& to) {
add(fs::path(path), to);
}
static void add(std::vector<sstring> paths, std::set<fs::path>& to) {
for (auto& path : paths) {
add(path, to);
}
}
static void add_sharded(sstring p, std::set<fs::path>& to) {
fs::path path(p);
for (unsigned i = 0; i < smp::count; i++) {
add(path / seastar::to_sstring(i).c_str(), to);
}
}
future<> directories::init(db::config& cfg, bool hinted_handoff_enabled) {
std::set<fs::path> paths;
add(cfg.data_file_directories(), paths);
add(cfg.commitlog_directory(), paths);
if (hinted_handoff_enabled) {
add_sharded(cfg.hints_directory(), paths);
}
add_sharded(cfg.view_hints_directory(), paths);
supervisor::notify("creating and verifying directories");
return parallel_for_each(paths, [this, &cfg] (fs::path path) {
return touch_and_lock(path).then([path = std::move(path), &cfg] {
return disk_sanity(path, cfg.developer_mode()).then([path = std::move(path)] {
return distributed_loader::verify_owner_and_mode(path).handle_exception([](auto ep) {
startlog.error("Failed owner and mode verification: {}", ep);
return make_exception_future<>(ep);
});
});
});
});
}
} // namespace utils
<|endoftext|> |
<commit_before>#include <memory>
#include <UnitTest++/UnitTest++.h>
#include "Article.h"
#include "ArticleCollection.h"
#include "WalkerException.h"
SUITE(CollectionMergeTests)
{
using namespace WikiWalker;
/*!
* Create test data of the following structure:
* dragon -> treasure
* -> fire
* -> flying
* cat -> -
* apple -> fruit
* window -> outside
*/
void createArticlesAndFillFirst(ArticleCollection & ac)
{
auto a1 = std::make_shared<Article>("Dragon");
auto a2 = std::make_shared<Article>("Treasure");
auto a3 = std::make_shared<Article>("Fire");
auto a4 = std::make_shared<Article>("Flying");
a1->addLink(a2);
a1->addLink(a3);
a1->addLink(a4);
auto a5 = std::make_shared<Article>("Cat");
auto a6 = std::make_shared<Article>("Apple");
auto a7 = std::make_shared<Article>("Fruit");
a6->addLink(a7);
auto a8 = std::make_shared<Article>("Window");
auto a9 = std::make_shared<Article>("Outside");
a8->addLink(a9);
ac.add(a1);
ac.add(a2);
ac.add(a3);
ac.add(a4);
ac.add(a5);
ac.add(a6);
ac.add(a7);
ac.add(a8);
ac.add(a9);
}
/*!
* Create test data of the following structure:
*
* dragon -> -
* cat -> milk
* -> lazy
* wood -> house
* window -> glass
* -> cleaning
*/
void createArticlesAndFillSecond(ArticleCollection & ac)
{
auto b1 = std::make_shared<Article>("Dragon");
auto b2 = std::make_shared<Article>("Cat");
auto b9 = std::make_shared<Article>("Milk");
auto b3 = std::make_shared<Article>("Lazy");
b2->addLink(b3);
b2->addLink(b9);
auto b4 = std::make_shared<Article>("Wood");
auto b5 = std::make_shared<Article>("House");
b4->addLink(b5);
auto b6 = std::make_shared<Article>("Window");
auto b7 = std::make_shared<Article>("Glass");
auto b8 = std::make_shared<Article>("Cleaning");
b6->addLink(b7);
b6->addLink(b8);
ac.add(b1);
ac.add(b2);
ac.add(b3);
ac.add(b4);
ac.add(b5);
ac.add(b6);
ac.add(b7);
ac.add(b8);
ac.add(b9);
}
/*! check whether data from first set is preferred
*
* Overview of the combined structure-
*
* dragon -> treasure | dragon -> -
* -> fire |
* -> flying |
* |
* cat -> - | cat -> milk
* | -> lazy
* |
* apple -> fruit |
* |
* | wood -> house
* |
* window -> outside | window -> glass
* | -> cleaning
*
*
* So we have 15 articles in total, and either side of the links may exist
*/
void checkConflicts_DataFromFirstSetPreferred(ArticleCollection & c1)
{
// 15 articles in total, no matter what
CHECK_EQUAL(15, c1.getNumArticles());
// data from createArticlesAndFillFirst won
auto ptr = c1.get("Dragon");
CHECK(ptr != nullptr);
CHECK_EQUAL(3, ptr->getNumLinks());
ptr = c1.get("Cat");
CHECK(ptr != nullptr);
CHECK_THROW(ptr->getNumLinks(), WalkerException);
ptr = c1.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
}
/*!
* see #checkFirst, only for the second set
*/
void checkConflicts_DataFromSecondSetPreferred(ArticleCollection & c2)
{
CHECK_EQUAL(15, c2.getNumArticles());
// data from createArticlesAndFillSecond won
auto ptr = c2.get("Dragon");
CHECK(ptr != nullptr);
CHECK_THROW(ptr->getNumLinks(), WalkerException);
ptr = c2.get("Cat");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
ptr = c2.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
}
/*!
*
* see #checkFirst, only for non-conflicting items
*/
void checkNonConflictingItems(ArticleCollection & c)
{
// check non-conflicting items, too
auto ptr = c.get("Apple");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
ptr = c.get("Wood");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
}
TEST(ArticleCollection_TestMergeIgnore)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
checkConflicts_DataFromFirstSetPreferred(a1);
checkNonConflictingItems(a1);
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::IgnoreDuplicates);
checkConflicts_DataFromSecondSetPreferred(a2);
checkNonConflictingItems(a2);
}
}
// overwrite behaves "exactly the opposite" of ignore
TEST(ArticleCollection_TestMergeOverwrite)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::AlwaysOverwrite);
checkConflicts_DataFromSecondSetPreferred(a1);
checkNonConflictingItems(a1);
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::AlwaysOverwrite);
checkConflicts_DataFromFirstSetPreferred(a2);
checkNonConflictingItems(a2);
}
}
void checkMoreLinks(ArticleCollection & ac)
{
auto ptr = ac.get("Dragon");
CHECK(ptr != nullptr);
CHECK_EQUAL(3, ptr->getNumLinks());
ptr = ac.get("Cat");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
ptr = ac.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
}
TEST(ArticleCollection_TestMergeMoreLinks)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks);
CHECK_EQUAL(15, a1.getNumArticles());
checkMoreLinks(a1);
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks);
CHECK_EQUAL(15, a2.getNumArticles());
checkMoreLinks(a2);
}
}
TEST(ArticleCollection_TestMerge)
{
ArticleCollection ac1;
ac1.add(std::make_shared<Article>("ManaMana"));
ac1.add(std::make_shared<Article>("Dragon"));
ac1.add(std::make_shared<Article>("Cereals"));
{
ArticleCollection ac2;
ac2.add(std::make_shared<Article>("Dragon"));
ac2.add(std::make_shared<Article>("Git"));
ac2.add(std::make_shared<Article>("Stroustrup"));
ac1.merge(ac2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
CHECK_EQUAL(5, ac1.getNumArticles());
CHECK_EQUAL(3, ac2.getNumArticles());
}
// check again after scope is left
CHECK_EQUAL(5, ac1.getNumArticles());
}
}
<commit_msg>Clarify / document / rename remaining merge tests<commit_after>#include <memory>
#include <UnitTest++/UnitTest++.h>
#include "Article.h"
#include "ArticleCollection.h"
#include "WalkerException.h"
SUITE(CollectionMergeTests)
{
using namespace WikiWalker;
/*!
* Create test data of the following structure:
* dragon -> treasure
* -> fire
* -> flying
* cat -> -
* apple -> fruit
* window -> outside
*/
void createArticlesAndFillFirst(ArticleCollection & ac)
{
auto a1 = std::make_shared<Article>("Dragon");
auto a2 = std::make_shared<Article>("Treasure");
auto a3 = std::make_shared<Article>("Fire");
auto a4 = std::make_shared<Article>("Flying");
a1->addLink(a2);
a1->addLink(a3);
a1->addLink(a4);
auto a5 = std::make_shared<Article>("Cat");
auto a6 = std::make_shared<Article>("Apple");
auto a7 = std::make_shared<Article>("Fruit");
a6->addLink(a7);
auto a8 = std::make_shared<Article>("Window");
auto a9 = std::make_shared<Article>("Outside");
a8->addLink(a9);
ac.add(a1);
ac.add(a2);
ac.add(a3);
ac.add(a4);
ac.add(a5);
ac.add(a6);
ac.add(a7);
ac.add(a8);
ac.add(a9);
}
/*!
* Create test data of the following structure:
*
* dragon -> -
* cat -> milk
* -> lazy
* wood -> house
* window -> glass
* -> cleaning
*/
void createArticlesAndFillSecond(ArticleCollection & ac)
{
auto b1 = std::make_shared<Article>("Dragon");
auto b2 = std::make_shared<Article>("Cat");
auto b9 = std::make_shared<Article>("Milk");
auto b3 = std::make_shared<Article>("Lazy");
b2->addLink(b3);
b2->addLink(b9);
auto b4 = std::make_shared<Article>("Wood");
auto b5 = std::make_shared<Article>("House");
b4->addLink(b5);
auto b6 = std::make_shared<Article>("Window");
auto b7 = std::make_shared<Article>("Glass");
auto b8 = std::make_shared<Article>("Cleaning");
b6->addLink(b7);
b6->addLink(b8);
ac.add(b1);
ac.add(b2);
ac.add(b3);
ac.add(b4);
ac.add(b5);
ac.add(b6);
ac.add(b7);
ac.add(b8);
ac.add(b9);
}
/*! check whether data from first set is preferred
*
* Overview of the combined structure-
*
* dragon -> treasure | dragon -> -
* -> fire |
* -> flying |
* |
* cat -> - | cat -> milk
* | -> lazy
* |
* apple -> fruit |
* |
* | wood -> house
* |
* window -> outside | window -> glass
* | -> cleaning
*
*
* So we have 15 articles in total, and either side of the links may exist
*/
void checkConflicts_DataFromFirstSetPreferred(ArticleCollection & c1)
{
// 15 articles in total, no matter what
CHECK_EQUAL(15, c1.getNumArticles());
// data from createArticlesAndFillFirst won
auto ptr = c1.get("Dragon");
CHECK(ptr != nullptr);
CHECK_EQUAL(3, ptr->getNumLinks());
ptr = c1.get("Cat");
CHECK(ptr != nullptr);
CHECK_THROW(ptr->getNumLinks(), WalkerException);
ptr = c1.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
}
/*!
* see #checkConflicts_DataFromFirstSetPreferred, only for the second set
*/
void checkConflicts_DataFromSecondSetPreferred(ArticleCollection & c2)
{
CHECK_EQUAL(15, c2.getNumArticles());
// data from createArticlesAndFillSecond won
auto ptr = c2.get("Dragon");
CHECK(ptr != nullptr);
CHECK_THROW(ptr->getNumLinks(), WalkerException);
ptr = c2.get("Cat");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
ptr = c2.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
}
/*!
* see #checkConflicts_DataFromFirstSetPreferred, only for non-conflicting items
*/
void checkNonConflictingItems(ArticleCollection & c)
{
// check non-conflicting items, too
auto ptr = c.get("Apple");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
ptr = c.get("Wood");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
}
TEST(ArticleCollection_TestMergeIgnore)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
checkConflicts_DataFromFirstSetPreferred(a1);
checkNonConflictingItems(a1);
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::IgnoreDuplicates);
checkConflicts_DataFromSecondSetPreferred(a2);
checkNonConflictingItems(a2);
}
}
// overwrite behaves "exactly the opposite" of ignore
TEST(ArticleCollection_TestMergeOverwrite)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::AlwaysOverwrite);
checkConflicts_DataFromSecondSetPreferred(a1);
checkNonConflictingItems(a1);
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::AlwaysOverwrite);
checkConflicts_DataFromFirstSetPreferred(a2);
checkNonConflictingItems(a2);
}
}
/*!
* see #checkConflicts_DataFromFirstSetPreferred, only for items with most links
*/
void checkConflicts_DataWithMoreLinksPreferred(ArticleCollection & ac)
{
auto ptr = ac.get("Dragon");
CHECK(ptr != nullptr);
CHECK_EQUAL(3, ptr->getNumLinks());
ptr = ac.get("Cat");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
ptr = ac.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
}
TEST(ArticleCollection_TestMergeMoreLinks)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks);
CHECK_EQUAL(15, a1.getNumArticles());
checkConflicts_DataWithMoreLinksPreferred(a1);
checkNonConflictingItems(a1);
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks);
CHECK_EQUAL(15, a2.getNumArticles());
checkConflicts_DataWithMoreLinksPreferred(a2);
checkNonConflictingItems(a2);
}
}
TEST(ArticleCollection_TestMerge)
{
ArticleCollection ac1;
ac1.add(std::make_shared<Article>("ManaMana"));
ac1.add(std::make_shared<Article>("Dragon"));
ac1.add(std::make_shared<Article>("Cereals"));
{
ArticleCollection ac2;
ac2.add(std::make_shared<Article>("Dragon"));
ac2.add(std::make_shared<Article>("Git"));
ac2.add(std::make_shared<Article>("Stroustrup"));
ac1.merge(ac2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
CHECK_EQUAL(5, ac1.getNumArticles());
CHECK_EQUAL(3, ac2.getNumArticles());
}
// check again after scope is left
CHECK_EQUAL(5, ac1.getNumArticles());
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014-2015 DataStax
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include "cassandra.h"
#include "test_utils.hpp"
#include "cql_ccm_bridge.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/test/debug.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>
struct AthenticationTests {
AthenticationTests()
: cluster(cass_cluster_new())
, conf(cql::get_ccm_bridge_configuration())
, ccm(cql::cql_ccm_bridge_t::create(conf, "test")) {
boost::debug::detect_memory_leaks(false);
ccm->populate(1);
ccm->update_config("authenticator", "PasswordAuthenticator");
ccm->start(1, "-Dcassandra.superuser_setup_delay_ms=0");
test_utils::initialize_contact_points(cluster.get(), conf.ip_prefix(), 1, 0);
// Sometimes the superuser will still not be setup
boost::this_thread::sleep_for(boost::chrono::seconds(1));
}
void auth(int protocol_version) {
cass_cluster_set_protocol_version(cluster.get(), protocol_version);
cass_cluster_set_credentials(cluster.get(), "cassandra", "cassandra");
test_utils::CassSessionPtr session(test_utils::create_session(cluster.get()));
test_utils::CassResultPtr result;
test_utils::execute_query(session.get(), "SELECT * FROM system.schema_keyspaces", &result);
BOOST_CHECK(cass_result_row_count(result.get()) > 0);
}
void invalid_credentials(int protocol_version, const char* username,
const char* password, const char* expected_error,
CassError expected_code) {
test_utils::CassLog::reset(expected_error);
cass_cluster_set_protocol_version(cluster.get(), protocol_version);
cass_cluster_set_credentials(cluster.get(), username, password);
{
CassError code;
test_utils::CassSessionPtr temp_session(test_utils::create_session(cluster.get(), &code));
BOOST_CHECK_EQUAL(expected_code, code);
}
BOOST_CHECK(test_utils::CassLog::message_count() > 0);
}
test_utils::CassClusterPtr cluster;
const cql::cql_ccm_bridge_configuration_t& conf;
boost::shared_ptr<cql::cql_ccm_bridge_t> ccm;
};
BOOST_FIXTURE_TEST_SUITE(authentication, AthenticationTests)
BOOST_AUTO_TEST_CASE(protocol_versions)
{
auth(1);
auth(2);
}
BOOST_AUTO_TEST_CASE(empty_credentials)
{
// This is a case that could be guarded in the API entry point, or errored in connection. However,
// auth is subject to major changes and this is just a simple form.
// This test serves to characterize what is there presently.
const char* expected_error
= "java.lang.AssertionError: org.apache.cassandra.exceptions.InvalidRequestException: Key may not be empty";
invalid_credentials(1, "", "", expected_error, CASS_ERROR_LIB_NO_HOSTS_AVAILABLE);
invalid_credentials(2, "", "", expected_error, CASS_ERROR_LIB_NO_HOSTS_AVAILABLE);
}
BOOST_AUTO_TEST_CASE(bad_credentials)
{
const char* expected_error
= "had the following error on startup: Username and/or password are incorrect";
invalid_credentials(1, "invalid", "invalid", expected_error, CASS_ERROR_SERVER_BAD_CREDENTIALS);
invalid_credentials(2, "invalid", "invalid", expected_error, CASS_ERROR_SERVER_BAD_CREDENTIALS);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Adding missing protocol versions and fixing for C* 2.2<commit_after>/*
Copyright (c) 2014-2015 DataStax
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include "cassandra.h"
#include "test_utils.hpp"
#include "cql_ccm_bridge.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/test/debug.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>
struct AthenticationTests {
AthenticationTests()
: cluster(cass_cluster_new())
, conf(cql::get_ccm_bridge_configuration())
, ccm(cql::cql_ccm_bridge_t::create(conf, "test")) {
boost::debug::detect_memory_leaks(false);
ccm->populate(1);
ccm->update_config("authenticator", "PasswordAuthenticator");
ccm->start(1, "-Dcassandra.superuser_setup_delay_ms=0");
test_utils::initialize_contact_points(cluster.get(), conf.ip_prefix(), 1, 0);
// Sometimes the superuser will still not be setup
boost::this_thread::sleep_for(boost::chrono::seconds(1));
}
void auth(int protocol_version) {
cass_cluster_set_protocol_version(cluster.get(), protocol_version);
cass_cluster_set_credentials(cluster.get(), "cassandra", "cassandra");
test_utils::CassSessionPtr session(test_utils::create_session(cluster.get()));
test_utils::CassResultPtr result;
test_utils::execute_query(session.get(), "SELECT * FROM system.schema_keyspaces", &result);
BOOST_CHECK(cass_result_row_count(result.get()) > 0);
}
void invalid_credentials(int protocol_version, const char* username,
const char* password, const char* expected_error,
CassError expected_code) {
test_utils::CassLog::reset(expected_error);
cass_cluster_set_protocol_version(cluster.get(), protocol_version);
cass_cluster_set_credentials(cluster.get(), username, password);
{
CassError code;
test_utils::CassSessionPtr temp_session(test_utils::create_session(cluster.get(), &code));
BOOST_CHECK_EQUAL(expected_code, code);
}
BOOST_CHECK(test_utils::CassLog::message_count() > 0);
}
test_utils::CassClusterPtr cluster;
const cql::cql_ccm_bridge_configuration_t& conf;
boost::shared_ptr<cql::cql_ccm_bridge_t> ccm;
};
BOOST_FIXTURE_TEST_SUITE(authentication, AthenticationTests)
BOOST_AUTO_TEST_CASE(protocol_versions)
{
auth(1);
auth(2);
auth(3);
auth(4);
}
BOOST_AUTO_TEST_CASE(empty_credentials)
{
// This is a case that could be guarded in the API entry point, or errored in connection. However,
// auth is subject to major changes and this is just a simple form.
// This test serves to characterize what is there presently.
const char* expected_error
= "Key may not be empty";
invalid_credentials(1, "", "", expected_error, CASS_ERROR_LIB_NO_HOSTS_AVAILABLE);
invalid_credentials(2, "", "", expected_error, CASS_ERROR_LIB_NO_HOSTS_AVAILABLE);
invalid_credentials(3, "", "", expected_error, CASS_ERROR_LIB_NO_HOSTS_AVAILABLE);
invalid_credentials(4, "", "", expected_error, CASS_ERROR_LIB_NO_HOSTS_AVAILABLE);
}
BOOST_AUTO_TEST_CASE(bad_credentials)
{
const char* expected_error
= "had the following error on startup: Username and/or password are incorrect";
invalid_credentials(1, "invalid", "invalid", expected_error, CASS_ERROR_SERVER_BAD_CREDENTIALS);
invalid_credentials(2, "invalid", "invalid", expected_error, CASS_ERROR_SERVER_BAD_CREDENTIALS);
invalid_credentials(3, "invalid", "invalid", expected_error, CASS_ERROR_SERVER_BAD_CREDENTIALS);
invalid_credentials(4, "invalid", "invalid", expected_error, CASS_ERROR_SERVER_BAD_CREDENTIALS);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
enum {start, end, height};
/**
* @param buildings: A list of lists of integers
* @return: Find the outline of those buildings
*/
vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) {
return ComputeSkylineInInterval(buildings, 0, buildings.size());
}
// Divide and Conquer.
vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings,
int left_endpoint, int right_endpoint) {
if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it.
return {buildings.cbegin() + left_endpoint,
buildings.cbegin() + right_endpoint};
}
int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2);
auto left_skyline = ComputeSkylineInInterval(buildings, left_endpoint, mid);
auto right_skyline = ComputeSkylineInInterval(buildings, mid, right_endpoint);
return MergeSkylines(left_skyline, right_skyline);
}
// Merge Sort
vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) {
int i = 0, j = 0;
vector<vector<int>> merged;
while (i < left_skyline.size() && j < right_skyline.size()) {
if (left_skyline[i][end] < right_skyline[j][start]) {
merged.emplace_back(left_skyline[i++]);
} else if (right_skyline[j][end] < left_skyline[i][start]) {
merged.emplace_back(right_skyline[j++]);
} else if (left_skyline[i][start] <= right_skyline[j][start]) {
MergeIntersectSkylines(merged, left_skyline[i], i,
right_skyline[j], j);
} else { // left_skyline[i][start] > right_skyline[j][start].
MergeIntersectSkylines(merged, right_skyline[j], j,
left_skyline[i], i);
}
}
// Insert the remaining skylines.
merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end());
merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end());
return merged;
}
// a[start] <= b[start]
void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx,
vector<int>& b, int& b_idx) {
if (a[end] <= b[end]) {
if (a[height] > b[height]) { // |aaa|
if (b[end] != a[end]) { // |abb|b
merged.emplace_back(a), ++a_idx;
b[start] = a[end];
} else { // aaa
++b_idx; // abb
}
} else if (a[height] == b[height]) { // abb
b[start] = a[start], ++a_idx; // abb
} else { // a[height] < b[height].
if (a[start] != b[start]) { // bb
merged.emplace_back(vector<int>{a[start], b[start], a[height]}); // |a|bb
}
++a_idx;
}
} else { // a[end] > b[end].
if (a[height] >= b[height]) { // aaaa
++b_idx; // abba
} else {
// |bb|
// |a||bb|a
if (a[start] != b[start]) {
merged.emplace_back(vector<int>{a[start], b[start], a[height]});
}
a[start] = b[end];
merged.emplace_back(b), ++b_idx;
}
}
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
/**
* @param buildings: A list of lists of integers
* @return: Find the outline of those buildings
*/
vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) {
auto outline(move(getSkyline(buildings)));
vector<vector<int>> res;
int start = -1, height = 0;
for (const auto& h : outline) {
if (start == -1) {
start = h.first, height = h.second;
} else if (height != h.second) {
if (height > 0) {
res.emplace_back(move(vector<int>{start, h.first, height}));
}
start = h.first, height = h.second;
}
}
return res;
}
vector<pair<int, int> > getSkyline(const vector<vector<int>>& buildings) {
unordered_map<int, vector<int>> start_point_to_heights;
unordered_map<int, vector<int>> end_point_to_heights;
set<int> points;
for (int i = 0; i < buildings.size(); ++i) {
start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]);
end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]);
points.emplace(buildings[i][0]);
points.emplace(buildings[i][1]);
}
vector<pair<int, int>> res;
map<int, int> height_to_count;
int curr_max = 0;
// Enumerate each point in increasing order.
for (auto it = points.begin(); it != points.end(); ++it) {
vector<int> start_point_heights = start_point_to_heights[*it];
vector<int> end_point_heights = end_point_to_heights[*it];
for (int i = 0; i < start_point_heights.size(); ++i) {
++height_to_count[start_point_heights[i]];
}
for (int i = 0; i < end_point_heights.size(); ++i) {
--height_to_count[end_point_heights[i]];
if (height_to_count[end_point_heights[i]] == 0) {
height_to_count.erase(end_point_heights[i]);
}
}
if (height_to_count.empty()) {
curr_max = 0;
res.emplace_back(*it, curr_max);
} else if (curr_max != height_to_count.rbegin()->first) {
curr_max = height_to_count.rbegin()->first;
res.emplace_back(*it, curr_max);
}
}
return res;
}
};
<commit_msg>Update building-outline.cpp<commit_after>// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
enum {start, end, height};
/**
* @param buildings: A list of lists of integers
* @return: Find the outline of those buildings
*/
vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) {
return ComputeSkylineInInterval(buildings, 0, buildings.size());
}
// Divide and Conquer.
vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings,
int left_endpoint, int right_endpoint) {
if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it.
return {buildings.cbegin() + left_endpoint,
buildings.cbegin() + right_endpoint};
}
int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2);
auto left_skyline = ComputeSkylineInInterval(buildings, left_endpoint, mid);
auto right_skyline = ComputeSkylineInInterval(buildings, mid, right_endpoint);
return MergeSkylines(left_skyline, right_skyline);
}
// Merge Sort
vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) {
int i = 0, j = 0;
vector<vector<int>> merged;
while (i < left_skyline.size() && j < right_skyline.size()) {
if (left_skyline[i][end] < right_skyline[j][start]) {
merged.emplace_back(left_skyline[i++]);
} else if (right_skyline[j][end] < left_skyline[i][start]) {
merged.emplace_back(right_skyline[j++]);
} else if (left_skyline[i][start] <= right_skyline[j][start]) {
MergeIntersectSkylines(merged, left_skyline[i], i,
right_skyline[j], j);
} else { // left_skyline[i][start] > right_skyline[j][start].
MergeIntersectSkylines(merged, right_skyline[j], j,
left_skyline[i], i);
}
}
// Insert the remaining skylines.
merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end());
merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end());
return merged;
}
// a[start] <= b[start]
void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx,
vector<int>& b, int& b_idx) {
if (a[end] <= b[end]) {
if (a[height] > b[height]) { // |aaa|
if (b[end] != a[end]) { // |abb|b
merged.emplace_back(a), ++a_idx;
b[start] = a[end];
} else { // aaa
++b_idx; // abb
}
} else if (a[height] == b[height]) { // abb
b[start] = a[start], ++a_idx; // abb
} else { // a[height] < b[height].
if (a[start] != b[start]) { // bb
merged.emplace_back(vector<int>{a[start], b[start], a[height]}); // |a|bb
}
++a_idx;
}
} else { // a[end] > b[end].
if (a[height] >= b[height]) { // aaaa
++b_idx; // abba
} else {
// |bb|
// |a||bb|a
if (a[start] != b[start]) {
merged.emplace_back(vector<int>{a[start], b[start], a[height]});
}
a[start] = b[end];
merged.emplace_back(b), ++b_idx;
}
}
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
/**
* @param buildings: A list of lists of integers
* @return: Find the outline of those buildings
*/
vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) {
unordered_map<int, vector<int>> start_point_to_heights;
unordered_map<int, vector<int>> end_point_to_heights;
set<int> points;
for (int i = 0; i < buildings.size(); ++i) {
start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]);
end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]);
points.emplace(buildings[i][0]);
points.emplace(buildings[i][1]);
}
vector<vector<int>> res;
map<int, int> height_to_count;
int curr_start = -1;
int curr_max = 0;
// Enumerate each point in increasing order.
for (auto it = points.begin(); it != points.end(); ++it) {
vector<int> start_point_heights = start_point_to_heights[*it];
vector<int> end_point_heights = end_point_to_heights[*it];
for (int i = 0; i < start_point_heights.size(); ++i) {
++height_to_count[start_point_heights[i]];
}
for (int i = 0; i < end_point_heights.size(); ++i) {
--height_to_count[end_point_heights[i]];
if (height_to_count[end_point_heights[i]] == 0) {
height_to_count.erase(end_point_heights[i]);
}
}
if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) {
if (curr_max > 0) {
res.emplace_back(move(vector<int>{curr_start, *it, curr_max}));
}
curr_start = *it;
curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first;
}
}
return res;
}
};
<|endoftext|> |
<commit_before>// Time: O(n * k^2 + r), n is the number of the words,
// k is the max length of the words,
// r is the number of the result.
// Space: O(n * k + r)
class Solution {
public:
struct hashPair {
public:
template <typename T, typename U>
std::size_t operator()(const std::pair<T, U> &x) const {
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
unordered_map<string, int> lookup;
unordered_set<pair<int, int>, hashPair> visited;
for (int i = 0; i < words.size(); ++i) {
lookup[words[i]] = i;
}
for (int i = 0; i < words.size(); ++i) {
const int k = words[i].size();
for (int l = 0; l <= k; ++l) {
if (is_palindrome(words[i], 0, l - 1)) {
string tmp = words[i].substr(l);
reverse(tmp.begin(), tmp.end());
if (lookup.find(tmp) != lookup.end()) {
if ((lookup[tmp] != i) &&
(visited.find(make_pair(lookup[tmp], i)) == visited.end())) {
res.push_back({lookup[tmp], i});
visited.emplace(make_pair(lookup[tmp], i));
}
}
}
if (is_palindrome(words[i], l, k - 1)) {
string tmp = words[i].substr(0, l);
reverse(tmp.begin(), tmp.end());
if (lookup.find(tmp) != lookup.end()) {
if ((i != lookup[tmp]) &&
(visited.find(make_pair(i, lookup[tmp])) == visited.end())) {
res.push_back({i, lookup[tmp]});
visited.emplace(make_pair(i, lookup[tmp]));
}
}
}
}
}
return res;
}
private:
bool is_palindrome(string& s, int start, int end) {
while (start < end) {
if (s[start++] != s[end--]) {
return false;
}
}
return true;
}
};
// Time: O(n * k + r), n is the number of the words,
// k is the max length of the words,
// r is the number of the result.
// Space: O(n * k^2)
// Manacher solution.
class Solution2 {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
unordered_multimap<string, int> prefix, suffix;
for (int i = 0; i < words.size(); ++i) {
vector<int> P;
manacher(words[i], &P);
for (int j = 0; j < P.size(); ++j) {
if (j - P[j] == 1) {
prefix.emplace(words[i].substr((j + P[j]) / 2), i);
}
if (j + P[j] == P.size() - 2) {
suffix.emplace(words[i].substr(0, (j - P[j]) / 2), i);
}
}
}
vector<vector<int>> res;
for (int i = 0; i < words.size(); ++i) {
string reversed_word(words[i].rbegin(), words[i].rend());
auto its = prefix.equal_range(reversed_word);
for (auto it = its.first; it != its.second; ++it) {
if (it->second != i) {
res.push_back({i, it->second});
}
}
its = suffix.equal_range(reversed_word);
for (auto it = its.first; it != its.second; ++it) {
if (words[i].size() != words[it->second].size()) {
res.push_back({it->second, i});
}
}
}
return res;
}
void manacher(const string& s, vector<int> *P) {
string T = preProcess(s);
const int n = T.length();
P->resize(n);
int C = 0, R = 0;
for (int i = 1; i < n - 1; ++i) {
int i_mirror = 2 * C - i;
(*P)[i] = (R > i) ? min(R - i, (*P)[i_mirror]) : 0;
while (T[i + 1 + (*P)[i]] == T[i - 1 - (*P)[i]]) {
++(*P)[i];
}
if (i + (*P)[i] > R) {
C = i;
R = i + (*P)[i];
}
}
}
string preProcess(const string& s) {
if (s.empty()) {
return "^$";
}
string ret = "^";
for (int i = 0; i < s.length(); ++i) {
ret += "#" + s.substr(i, 1);
}
ret += "#$";
return ret;
}
};
// Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words.
// k is the max length of the words,
// r is the number of the result.
// Space: O(n * k)
class Solution_MLE {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
TrieNode trie;
for (int i = 0; i < words.size(); ++i) {
trie.insert(words[i], i);
}
for (int i = 0; i < words.size(); ++i) {
trie.find(words[i], i, &res);
}
return res;
}
private:
struct TrieNode {
int word_idx = -1;
unordered_map<char, TrieNode *> leaves;
void insert(const string& s, int i) {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
}
p->word_idx = i;
}
void find(const string& s, int idx, vector<vector<int>> *res) {
auto* p = this;
for (int i = s.length() - 1; i >= 0; --i) { // O(k)
if (p->leaves.find(s[i]) != p->leaves.cend()) {
p = p->leaves[s[i]];
if (p->word_idx != -1 && p->word_idx != idx &&
is_palindrome(s, i - 1)) { // O(k)
res->push_back({p->word_idx, idx});
}
} else {
break;
}
}
}
bool is_palindrome(const string& s, int j) {
int i = 0;
while (i <= j) {
if (s[i++] != s[j--]) {
return false;
}
}
return true;
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
};
<commit_msg>Update palindrome-pairs.cpp<commit_after>// Time: O(n * k^2 + r), n is the number of the words,
// k is the max length of the words,
// r is the number of the result.
// Space: O(n * k + r)
class Solution {
public:
struct hashPair {
public:
template <typename T, typename U>
std::size_t operator()(const std::pair<T, U> &x) const {
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
unordered_map<string, int> lookup;
unordered_set<pair<int, int>, hashPair> visited; // At most O(r) space.
for (int i = 0; i < words.size(); ++i) {
lookup[words[i]] = i; // Total O(n * k) space.
}
for (int i = 0; i < words.size(); ++i) {
const int k = words[i].size();
for (int l = 0; l <= k; ++l) {
if (is_palindrome(words[i], 0, l - 1)) {
string tmp = words[i].substr(l);
reverse(tmp.begin(), tmp.end());
if (lookup.find(tmp) != lookup.end()) {
if ((lookup[tmp] != i) &&
(visited.find(make_pair(lookup[tmp], i)) == visited.end())) {
res.push_back({lookup[tmp], i});
visited.emplace(make_pair(lookup[tmp], i));
}
}
}
if (is_palindrome(words[i], l, k - 1)) {
string tmp = words[i].substr(0, l);
reverse(tmp.begin(), tmp.end());
if (lookup.find(tmp) != lookup.end()) {
if ((i != lookup[tmp]) &&
(visited.find(make_pair(i, lookup[tmp])) == visited.end())) {
res.push_back({i, lookup[tmp]});
visited.emplace(make_pair(i, lookup[tmp]));
}
}
}
}
}
return res;
}
private:
bool is_palindrome(string& s, int start, int end) {
while (start < end) {
if (s[start++] != s[end--]) {
return false;
}
}
return true;
}
};
// Time: O(n * k^2 + r), n is the number of the words,
// k is the max length of the words,
// r is the number of the result.
// Space: O(n * k^2)
// Manacher solution.
class Solution2 {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
unordered_multimap<string, int> prefix, suffix;
for (int i = 0; i < words.size(); ++i) { // O(n)
vector<int> P;
manacher(words[i], &P);
for (int j = 0; j < P.size(); ++j) { // O(k)
if (j - P[j] == 1) {
prefix.emplace(words[i].substr((j + P[j]) / 2), i); // O(k)
}
if (j + P[j] == P.size() - 2) {
suffix.emplace(words[i].substr(0, (j - P[j]) / 2), i);
}
}
}
vector<vector<int>> res;
for (int i = 0; i < words.size(); ++i) { // O(n)
string reversed_word(words[i].rbegin(), words[i].rend()); // O(k)
auto its = prefix.equal_range(reversed_word);
for (auto it = its.first; it != its.second; ++it) {
if (it->second != i) {
res.push_back({i, it->second});
}
}
its = suffix.equal_range(reversed_word);
for (auto it = its.first; it != its.second; ++it) {
if (words[i].size() != words[it->second].size()) {
res.push_back({it->second, i});
}
}
}
return res;
}
void manacher(const string& s, vector<int> *P) {
string T = preProcess(s);
const int n = T.length();
P->resize(n);
int C = 0, R = 0;
for (int i = 1; i < n - 1; ++i) {
int i_mirror = 2 * C - i;
(*P)[i] = (R > i) ? min(R - i, (*P)[i_mirror]) : 0;
while (T[i + 1 + (*P)[i]] == T[i - 1 - (*P)[i]]) {
++(*P)[i];
}
if (i + (*P)[i] > R) {
C = i;
R = i + (*P)[i];
}
}
}
string preProcess(const string& s) {
if (s.empty()) {
return "^$";
}
string ret = "^";
for (int i = 0; i < s.length(); ++i) {
ret += "#" + s.substr(i, 1);
}
ret += "#$";
return ret;
}
};
// Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words.
// k is the max length of the words,
// r is the number of the result.
// Space: O(n * k)
class Solution_MLE {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
TrieNode trie;
for (int i = 0; i < words.size(); ++i) {
trie.insert(words[i], i);
}
for (int i = 0; i < words.size(); ++i) {
trie.find(words[i], i, &res);
}
return res;
}
private:
struct TrieNode {
int word_idx = -1;
unordered_map<char, TrieNode *> leaves;
void insert(const string& s, int i) {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
}
p->word_idx = i;
}
void find(const string& s, int idx, vector<vector<int>> *res) {
auto* p = this;
for (int i = s.length() - 1; i >= 0; --i) { // O(k)
if (p->leaves.find(s[i]) != p->leaves.cend()) {
p = p->leaves[s[i]];
if (p->word_idx != -1 && p->word_idx != idx &&
is_palindrome(s, i - 1)) { // O(k)
res->push_back({p->word_idx, idx});
}
} else {
break;
}
}
}
bool is_palindrome(const string& s, int j) {
int i = 0;
while (i <= j) {
if (s[i++] != s[j--]) {
return false;
}
}
return true;
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
};
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org>
Copyright (C) 2002 Anders Lund <anders.lund@lund.tdcadsl.dk>
Copyright (C) 2007 Anders Lund <anders@alweb.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kateconsole.h"
#include "kateconsole.moc"
#include <kicon.h>
#include <kiconloader.h>
#include <ktexteditor/document.h>
#include <ktexteditor/view.h>
#include <kde_terminal_interface.h>
#include <kshell.h>
#include <kparts/part.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <KDialog>
#include <kurl.h>
#include <klibloader.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>
//Added by qt3to4:
#include <QShowEvent>
#include <QCheckBox>
#include <QVBoxLayout>
#include <kgenericfactory.h>
#include <kpluginfactory.h>
#include <kauthorized.h>
K_EXPORT_COMPONENT_FACTORY( katekonsoleplugin, KGenericFactory<KateKonsolePlugin>( "katekonsoleplugin" ) )
KateKonsolePlugin::KateKonsolePlugin( QObject* parent, const QStringList& ):
Kate::Plugin ( (Kate::Application*)parent )
{
if (!KAuthorized::authorizeKAction("shell_access"))
{
KMessageBox::sorry(0, i18n ("You do not have enough karma to access a shell or terminal emulation"));
}
}
Kate::PluginView *KateKonsolePlugin::createView (Kate::MainWindow *mainWindow)
{
KateKonsolePluginView *view = new KateKonsolePluginView (mainWindow);
mViews.append( view );
return view;
}
Kate::PluginConfigPage *KateKonsolePlugin::configPage (uint number, QWidget *parent, const char *name)
{
Q_UNUSED(name)
if (number != 0)
return 0;
return new KateKonsoleConfigPage(parent, this);
}
QString KateKonsolePlugin::configPageName (uint number) const
{
if (number != 0) return QString();
return i18n("Terminal");
}
QString KateKonsolePlugin::configPageFullName (uint number) const
{
if (number != 0) return QString();
return i18n("Terminal Settings");
}
KIcon KateKonsolePlugin::configPageIcon (uint number) const
{
if (number != 0) return KIcon();
return KIcon("utilities-terminal");
}
void KateKonsolePlugin::readConfig()
{
foreach ( KateKonsolePluginView *view, mViews )
view->readConfig();
}
KateKonsolePluginView::KateKonsolePluginView (Kate::MainWindow *mainWindow)
: Kate::PluginView (mainWindow)
{
// init console
QWidget *toolview = mainWindow->createToolView ("kate_private_plugin_katekonsoleplugin", Kate::MainWindow::Bottom, SmallIcon("utilities-terminal"), i18n("Terminal"));
m_console = new KateConsole(mainWindow, toolview);
}
KateKonsolePluginView::~KateKonsolePluginView ()
{
// cleanup, kill toolview + console
QWidget *toolview = m_console->parentWidget();
delete m_console;
delete toolview;
}
void KateKonsolePluginView::readConfig()
{
m_console->readConfig();
}
KateConsole::KateConsole (Kate::MainWindow *mw, QWidget *parent)
: KVBox (parent), KXMLGUIClient()
, m_part (0)
, m_mw (mw)
, m_toolView (parent)
{
QAction* a = actionCollection()->addAction("katekonsole_tools_pipe_to_terminal");
a->setIcon(KIcon("pipe"));
a->setText(i18n("&Pipe to Terminal"));
connect(a, SIGNAL(triggered()), this, SLOT(slotPipeToConsole()));
a = actionCollection()->addAction("katekonsole_tools_sync");
a->setText(i18n("S&yncronize Terminal with Current Document"));
connect(a, SIGNAL(triggered()), this, SLOT(slotManualSync()));
a = actionCollection()->addAction("katekonsole_tools_toggle_focus");
a->setIcon(KIcon("utilities-terminal"));
a->setText(i18n("&Focus Terminal"));
connect(a, SIGNAL(triggered()), this, SLOT(slotToggleFocus()));
setComponentData (KComponentData("kate"));
setXMLFile("plugins/katekonsole/ui.rc");
m_mw->guiFactory()->addClient (this);
readConfig();
}
KateConsole::~KateConsole ()
{
m_mw->guiFactory()->removeClient (this);
if (m_part)
disconnect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) );
}
void KateConsole::loadConsoleIfNeeded()
{
if (m_part) return;
if (!window() || !parentWidget()) return;
if (!window() || !isVisibleTo(window())) return;
KPluginFactory *factory = KPluginLoader("libkonsolepart").factory();
if (!factory) return;
m_part = static_cast<KParts::ReadOnlyPart *>(factory->create<QObject>(this, this));
if (!m_part) return;
// start the terminal
qobject_cast<TerminalInterface*>(m_part)->showShellInDir( QString() );
KGlobal::locale()->insertCatalog("konsole");
setFocusProxy(m_part->widget());
m_part->widget()->show();
connect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) );
slotSync();
}
void KateConsole::slotDestroyed ()
{
m_part = 0;
// hide the dockwidget
if (parentWidget())
{
m_mw->hideToolView (m_toolView);
m_mw->centralWidget()->setFocus ();
}
}
void KateConsole::showEvent(QShowEvent *)
{
if (m_part) return;
loadConsoleIfNeeded();
}
void KateConsole::cd (const KUrl &url)
{
sendInput("cd " + KShell::quoteArg(url.path()) + '\n');
}
void KateConsole::sendInput( const QString& text )
{
loadConsoleIfNeeded();
if (!m_part) return;
TerminalInterface *t = qobject_cast<TerminalInterface *>(m_part);
if (!t) return;
t->sendInput (text);
}
void KateConsole::slotPipeToConsole ()
{
if (KMessageBox::warningContinueCancel
(m_mw->window()
, i18n ("Do you really want to pipe the text to the console? This will execute any contained commands with your user rights.")
, i18n ("Pipe to Terminal?")
, KGuiItem(i18n("Pipe to Terminal")), KStandardGuiItem::cancel(), "Pipe To Terminal Warning") != KMessageBox::Continue)
return;
KTextEditor::View *v = m_mw->activeView();
if (!v)
return;
if (v->selection())
sendInput (v->selectionText());
else
sendInput (v->document()->text());
}
void KateConsole::slotSync()
{
if (m_mw->activeView() ) {
if ( m_mw->activeView()->document()->url().isValid()
&& m_mw->activeView()->document()->url().isLocalFile() ) {
cd(KUrl( m_mw->activeView()->document()->url().directory() ));
} else if ( !m_mw->activeView()->document()->url().isEmpty() ) {
sendInput( "### " + i18n("Sorry, can not cd into '%1'", m_mw->activeView()->document()->url().directory() ) + "\n" );
}
}
}
void KateConsole::slotManualSync()
{
slotSync();
if ( ! m_part || ! m_part->widget()->isVisible() )
m_mw->showToolView( parentWidget() );
}
void KateConsole::slotToggleFocus()
{
QAction *action = actionCollection()->action("katekonsole_tools_toggle_focus");
if ( ! m_part ) {
m_mw->showToolView( parentWidget() );
action->setText( i18n("Defocus Terminal") );
return; // this shows and focuses the konsole
}
if ( ! m_part ) return;
if (m_part->widget()->hasFocus()) {
if (m_mw->activeView())
m_mw->activeView()->setFocus();
action->setText( i18n("Focus Terminal") );
} else {
// show the view if it is hidden
if (parentWidget()->isHidden())
m_mw->showToolView( parentWidget() );
else // should focus the widget too!
m_part->widget()->setFocus( Qt::OtherFocusReason );
action->setText( i18n("Defocus Terminal") );
}
}
void KateConsole::readConfig()
{
if ( KConfigGroup(KGlobal::config(), "Konsole").readEntry("AutoSyncronize", false) )
connect( m_mw, SIGNAL(viewChanged()), SLOT(slotSync()) );
else
disconnect( m_mw, SIGNAL(viewChanged()), this, SLOT(slotSync()) );
}
KateKonsoleConfigPage::KateKonsoleConfigPage( QWidget* parent, KateKonsolePlugin *plugin )
: Kate::PluginConfigPage( parent )
, mPlugin( plugin )
{
QVBoxLayout *lo = new QVBoxLayout( this );
lo->setSpacing( KDialog::spacingHint() );
cbAutoSyncronize = new QCheckBox( i18n("&Automatically syncronize the terminal with the current document when possible"), this );
lo->addWidget( cbAutoSyncronize );
reset();
lo->addStretch();
connect( cbAutoSyncronize, SIGNAL(stateChanged(int)), SIGNAL(changed()) );
}
void KateKonsoleConfigPage::apply()
{
KConfigGroup config(KGlobal::config(), "Konsole");
config.writeEntry("AutoSyncronize", cbAutoSyncronize->isChecked());
config.sync();
mPlugin->readConfig();
}
void KateKonsoleConfigPage::reset()
{
KConfigGroup config(KGlobal::config(), "Konsole");
cbAutoSyncronize->setChecked(config.readEntry("AutoSyncronize", false));
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Fix the handling of action collections ( setComponentData() )<commit_after>/* This file is part of the KDE project
Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org>
Copyright (C) 2002 Anders Lund <anders.lund@lund.tdcadsl.dk>
Copyright (C) 2007 Anders Lund <anders@alweb.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kateconsole.h"
#include "kateconsole.moc"
#include <kicon.h>
#include <kiconloader.h>
#include <ktexteditor/document.h>
#include <ktexteditor/view.h>
#include <kde_terminal_interface.h>
#include <kshell.h>
#include <kparts/part.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <KDialog>
#include <kurl.h>
#include <klibloader.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>
//Added by qt3to4:
#include <QShowEvent>
#include <QCheckBox>
#include <QVBoxLayout>
#include <kgenericfactory.h>
#include <kpluginfactory.h>
#include <kauthorized.h>
K_EXPORT_COMPONENT_FACTORY( katekonsoleplugin, KGenericFactory<KateKonsolePlugin>( "katekonsoleplugin" ) )
KateKonsolePlugin::KateKonsolePlugin( QObject* parent, const QStringList& ):
Kate::Plugin ( (Kate::Application*)parent )
{
if (!KAuthorized::authorizeKAction("shell_access"))
{
KMessageBox::sorry(0, i18n ("You do not have enough karma to access a shell or terminal emulation"));
}
}
Kate::PluginView *KateKonsolePlugin::createView (Kate::MainWindow *mainWindow)
{
KateKonsolePluginView *view = new KateKonsolePluginView (mainWindow);
mViews.append( view );
return view;
}
Kate::PluginConfigPage *KateKonsolePlugin::configPage (uint number, QWidget *parent, const char *name)
{
Q_UNUSED(name)
if (number != 0)
return 0;
return new KateKonsoleConfigPage(parent, this);
}
QString KateKonsolePlugin::configPageName (uint number) const
{
if (number != 0) return QString();
return i18n("Terminal");
}
QString KateKonsolePlugin::configPageFullName (uint number) const
{
if (number != 0) return QString();
return i18n("Terminal Settings");
}
KIcon KateKonsolePlugin::configPageIcon (uint number) const
{
if (number != 0) return KIcon();
return KIcon("utilities-terminal");
}
void KateKonsolePlugin::readConfig()
{
foreach ( KateKonsolePluginView *view, mViews )
view->readConfig();
}
KateKonsolePluginView::KateKonsolePluginView (Kate::MainWindow *mainWindow)
: Kate::PluginView (mainWindow)
{
// init console
QWidget *toolview = mainWindow->createToolView ("kate_private_plugin_katekonsoleplugin", Kate::MainWindow::Bottom, SmallIcon("utilities-terminal"), i18n("Terminal"));
m_console = new KateConsole(mainWindow, toolview);
}
KateKonsolePluginView::~KateKonsolePluginView ()
{
// cleanup, kill toolview + console
QWidget *toolview = m_console->parentWidget();
delete m_console;
delete toolview;
}
void KateKonsolePluginView::readConfig()
{
m_console->readConfig();
}
KateConsole::KateConsole (Kate::MainWindow *mw, QWidget *parent)
: KVBox (parent), KXMLGUIClient()
, m_part (0)
, m_mw (mw)
, m_toolView (parent)
{
// this must be called before putting anything into actionCollection()
setComponentData (KComponentData("kate"));
QAction* a = actionCollection()->addAction("katekonsole_tools_pipe_to_terminal");
a->setIcon(KIcon("pipe"));
a->setText(i18n("&Pipe to Terminal"));
connect(a, SIGNAL(triggered()), this, SLOT(slotPipeToConsole()));
a = actionCollection()->addAction("katekonsole_tools_sync");
a->setText(i18n("S&yncronize Terminal with Current Document"));
connect(a, SIGNAL(triggered()), this, SLOT(slotManualSync()));
a = actionCollection()->addAction("katekonsole_tools_toggle_focus");
a->setIcon(KIcon("utilities-terminal"));
a->setText(i18n("&Focus Terminal"));
connect(a, SIGNAL(triggered()), this, SLOT(slotToggleFocus()));
setXMLFile("plugins/katekonsole/ui.rc");
m_mw->guiFactory()->addClient (this);
readConfig();
}
KateConsole::~KateConsole ()
{
m_mw->guiFactory()->removeClient (this);
if (m_part)
disconnect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) );
}
void KateConsole::loadConsoleIfNeeded()
{
if (m_part) return;
if (!window() || !parentWidget()) return;
if (!window() || !isVisibleTo(window())) return;
KPluginFactory *factory = KPluginLoader("libkonsolepart").factory();
if (!factory) return;
m_part = static_cast<KParts::ReadOnlyPart *>(factory->create<QObject>(this, this));
if (!m_part) return;
// start the terminal
qobject_cast<TerminalInterface*>(m_part)->showShellInDir( QString() );
KGlobal::locale()->insertCatalog("konsole");
setFocusProxy(m_part->widget());
m_part->widget()->show();
connect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) );
slotSync();
}
void KateConsole::slotDestroyed ()
{
m_part = 0;
// hide the dockwidget
if (parentWidget())
{
m_mw->hideToolView (m_toolView);
m_mw->centralWidget()->setFocus ();
}
}
void KateConsole::showEvent(QShowEvent *)
{
if (m_part) return;
loadConsoleIfNeeded();
}
void KateConsole::cd (const KUrl &url)
{
sendInput("cd " + KShell::quoteArg(url.path()) + '\n');
}
void KateConsole::sendInput( const QString& text )
{
loadConsoleIfNeeded();
if (!m_part) return;
TerminalInterface *t = qobject_cast<TerminalInterface *>(m_part);
if (!t) return;
t->sendInput (text);
}
void KateConsole::slotPipeToConsole ()
{
if (KMessageBox::warningContinueCancel
(m_mw->window()
, i18n ("Do you really want to pipe the text to the console? This will execute any contained commands with your user rights.")
, i18n ("Pipe to Terminal?")
, KGuiItem(i18n("Pipe to Terminal")), KStandardGuiItem::cancel(), "Pipe To Terminal Warning") != KMessageBox::Continue)
return;
KTextEditor::View *v = m_mw->activeView();
if (!v)
return;
if (v->selection())
sendInput (v->selectionText());
else
sendInput (v->document()->text());
}
void KateConsole::slotSync()
{
if (m_mw->activeView() ) {
if ( m_mw->activeView()->document()->url().isValid()
&& m_mw->activeView()->document()->url().isLocalFile() ) {
cd(KUrl( m_mw->activeView()->document()->url().directory() ));
} else if ( !m_mw->activeView()->document()->url().isEmpty() ) {
sendInput( "### " + i18n("Sorry, can not cd into '%1'", m_mw->activeView()->document()->url().directory() ) + "\n" );
}
}
}
void KateConsole::slotManualSync()
{
slotSync();
if ( ! m_part || ! m_part->widget()->isVisible() )
m_mw->showToolView( parentWidget() );
}
void KateConsole::slotToggleFocus()
{
QAction *action = actionCollection()->action("katekonsole_tools_toggle_focus");
if ( ! m_part ) {
m_mw->showToolView( parentWidget() );
action->setText( i18n("Defocus Terminal") );
return; // this shows and focuses the konsole
}
if ( ! m_part ) return;
if (m_part->widget()->hasFocus()) {
if (m_mw->activeView())
m_mw->activeView()->setFocus();
action->setText( i18n("Focus Terminal") );
} else {
// show the view if it is hidden
if (parentWidget()->isHidden())
m_mw->showToolView( parentWidget() );
else // should focus the widget too!
m_part->widget()->setFocus( Qt::OtherFocusReason );
action->setText( i18n("Defocus Terminal") );
}
}
void KateConsole::readConfig()
{
if ( KConfigGroup(KGlobal::config(), "Konsole").readEntry("AutoSyncronize", false) )
connect( m_mw, SIGNAL(viewChanged()), SLOT(slotSync()) );
else
disconnect( m_mw, SIGNAL(viewChanged()), this, SLOT(slotSync()) );
}
KateKonsoleConfigPage::KateKonsoleConfigPage( QWidget* parent, KateKonsolePlugin *plugin )
: Kate::PluginConfigPage( parent )
, mPlugin( plugin )
{
QVBoxLayout *lo = new QVBoxLayout( this );
lo->setSpacing( KDialog::spacingHint() );
cbAutoSyncronize = new QCheckBox( i18n("&Automatically syncronize the terminal with the current document when possible"), this );
lo->addWidget( cbAutoSyncronize );
reset();
lo->addStretch();
connect( cbAutoSyncronize, SIGNAL(stateChanged(int)), SIGNAL(changed()) );
}
void KateKonsoleConfigPage::apply()
{
KConfigGroup config(KGlobal::config(), "Konsole");
config.writeEntry("AutoSyncronize", cbAutoSyncronize->isChecked());
config.sync();
mPlugin->readConfig();
}
void KateKonsoleConfigPage::reset()
{
KConfigGroup config(KGlobal::config(), "Konsole");
cbAutoSyncronize->setChecked(config.readEntry("AutoSyncronize", false));
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2dmultirange.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-07-13 09:55:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BGFX_RANGE_B2DMULTIRANGE_HXX
#define _BGFX_RANGE_B2DMULTIRANGE_HXX
#ifndef INCLUDED_O3TL_COW_WRAPPER_HXX
#include <o3tl/cow_wrapper.hxx>
#endif
#include <memory>
namespace basegfx
{
class B2DTuple;
class B2DRange;
class B2DPolyPolygon;
class ImplB2DMultiRange;
/** Multiple ranges in one object.
This class combines multiple ranges in one object, providing a
total, enclosing range for it.
You can use this class e.g. when updating views containing
rectangular objects. Add each modified object to a
B2DMultiRange, then test each viewable object against
intersection with the multi range.
*/
class B2DMultiRange
{
public:
B2DMultiRange();
~B2DMultiRange();
/** Create a multi range with exactly one containing range
*/
explicit B2DMultiRange( const B2DRange& rRange );
B2DMultiRange( const B2DMultiRange& );
B2DMultiRange& operator=( const B2DMultiRange& );
/** Check whether range is empty.
@return true, if this object either contains no ranges at
all, or all contained ranges are empty.
*/
bool isEmpty() const;
/** Reset to empty.
After this call, the object will not contain any ranges,
and isEmpty() will return true.
*/
void reset();
/** Test whether given tuple is inside one or more of the
included ranges.
*/
bool isInside( const B2DTuple& rTuple ) const;
/** Test whether given range is inside one or more of the
included ranges.
*/
bool isInside( const B2DRange& rRange ) const;
/** Test whether given range overlaps one or more of the
included ranges.
*/
bool overlaps( const B2DRange& rRange ) const;
/** Add given range to the number of contained ranges.
*/
void addRange( const B2DRange& rRange );
/** Get overall bound rect for all included ranges.
*/
B2DRange getBounds() const;
/** Request poly-polygon representing the added ranges.
This method creates a poly-polygon, consisting exactly out
of the contained ranges.
*/
B2DPolyPolygon getPolyPolygon() const;
private:
o3tl::cow_wrapper< ImplB2DMultiRange > mpImpl;
};
}
#endif /* _BGFX_RANGE_B2DMULTIRANGE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.4.70); FILE MERGED 2008/04/01 15:01:09 thb 1.4.70.2: #i85898# Stripping all external header guards 2008/03/28 16:05:43 rt 1.4.70.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: b2dmultirange.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BGFX_RANGE_B2DMULTIRANGE_HXX
#define _BGFX_RANGE_B2DMULTIRANGE_HXX
#include <o3tl/cow_wrapper.hxx>
#include <memory>
namespace basegfx
{
class B2DTuple;
class B2DRange;
class B2DPolyPolygon;
class ImplB2DMultiRange;
/** Multiple ranges in one object.
This class combines multiple ranges in one object, providing a
total, enclosing range for it.
You can use this class e.g. when updating views containing
rectangular objects. Add each modified object to a
B2DMultiRange, then test each viewable object against
intersection with the multi range.
*/
class B2DMultiRange
{
public:
B2DMultiRange();
~B2DMultiRange();
/** Create a multi range with exactly one containing range
*/
explicit B2DMultiRange( const B2DRange& rRange );
B2DMultiRange( const B2DMultiRange& );
B2DMultiRange& operator=( const B2DMultiRange& );
/** Check whether range is empty.
@return true, if this object either contains no ranges at
all, or all contained ranges are empty.
*/
bool isEmpty() const;
/** Reset to empty.
After this call, the object will not contain any ranges,
and isEmpty() will return true.
*/
void reset();
/** Test whether given tuple is inside one or more of the
included ranges.
*/
bool isInside( const B2DTuple& rTuple ) const;
/** Test whether given range is inside one or more of the
included ranges.
*/
bool isInside( const B2DRange& rRange ) const;
/** Test whether given range overlaps one or more of the
included ranges.
*/
bool overlaps( const B2DRange& rRange ) const;
/** Add given range to the number of contained ranges.
*/
void addRange( const B2DRange& rRange );
/** Get overall bound rect for all included ranges.
*/
B2DRange getBounds() const;
/** Request poly-polygon representing the added ranges.
This method creates a poly-polygon, consisting exactly out
of the contained ranges.
*/
B2DPolyPolygon getPolyPolygon() const;
private:
o3tl::cow_wrapper< ImplB2DMultiRange > mpImpl;
};
}
#endif /* _BGFX_RANGE_B2DMULTIRANGE_HXX */
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM file system
*/
#include "sync_item.h"
#include <cerrno>
#include <vector>
#include "sync_mediator.h"
#include "sync_union.h"
using namespace std; // NOLINT
namespace publish {
SyncItem::SyncItem() :
union_engine_(NULL),
whiteout_(false),
opaque_(false),
masked_hardlink_(false),
has_catalog_marker_(false),
valid_graft_(false),
graft_marker_present_(false),
external_data_(false),
graft_chunklist_(NULL),
graft_size_(-1),
scratch_type_(static_cast<SyncItemType>(0)),
rdonly_type_(static_cast<SyncItemType>(0)),
compression_algorithm_(zlib::kZlibDefault) {}
SyncItem::SyncItem(const string &relative_parent_path,
const string &filename,
const SyncUnion *union_engine,
const SyncItemType entry_type) :
union_engine_(union_engine),
whiteout_(false),
opaque_(false),
masked_hardlink_(false),
has_catalog_marker_(false),
valid_graft_(false),
graft_marker_present_(false),
external_data_(false),
relative_parent_path_(relative_parent_path),
filename_(filename),
graft_chunklist_(NULL),
graft_size_(-1),
scratch_type_(entry_type),
rdonly_type_(kItemUnknown),
compression_algorithm_(zlib::kZlibDefault)
{
content_hash_.algorithm = shash::kAny;
CheckMarkerFiles();
}
SyncItem::~SyncItem() {
delete graft_chunklist_;
}
SyncItemType SyncItem::GetGenericFiletype(const SyncItem::EntryStat &stat) const
{
const SyncItemType type = stat.GetSyncItemType();
if (type == kItemUnknown) {
PrintWarning("'" + GetRelativePath() + "' has an unsupported file type "
"(st_mode: " + StringifyInt(stat.stat.st_mode) +
" errno: " + StringifyInt(stat.error_code) + ")");
abort();
}
return type;
}
SyncItemType SyncItem::GetRdOnlyFiletype() const {
StatRdOnly();
// file could not exist in read-only branch, or a regular file could have
// been replaced by a directory in the read/write branch, like:
// rdonly:
// /foo/bar/regular_file <-- ENOTDIR when asking for (.../is_dir_now)
// r/w:
// /foo/bar/regular_file/
// /foo/bar/regular_file/is_dir_now
if (rdonly_stat_.error_code == ENOENT ||
rdonly_stat_.error_code == ENOTDIR) return kItemNew;
return GetGenericFiletype(rdonly_stat_);
}
SyncItemType SyncItem::GetScratchFiletype() const {
StatScratch();
if (scratch_stat_.error_code != 0) {
PrintWarning("Failed to stat() '" + GetRelativePath() + "' in scratch. "
"(errno: " + StringifyInt(scratch_stat_.error_code) + ")");
abort();
}
return GetGenericFiletype(scratch_stat_);
}
void SyncItem::MarkAsWhiteout(const std::string &actual_filename) {
// Mark the file as whiteout entry and strip the whiteout prefix
whiteout_ = true;
filename_ = actual_filename;
// Find the entry in the repository
StatRdOnly(true); // <== refreshing the stat (filename might have changed)
const SyncItemType deleted_type = (rdonly_stat_.error_code == 0)
? GetRdOnlyFiletype()
: kItemUnknown;
rdonly_type_ = deleted_type;
scratch_type_ = deleted_type;
if (deleted_type == kItemUnknown) {
// Marking a SyncItem as 'whiteout' but no file to be removed found: This
// should not happen (actually AUFS prevents users from creating whiteouts)
// but can be provoked through an AUFS 'bug' (see test 593 or CVM-880).
// --> Warn the user, continue with kItemUnknown and cross your fingers!
PrintWarning("'" + GetRelativePath() + "' should be deleted, but was not "
"found in repository.");
}
}
void SyncItem::MarkAsOpaqueDirectory() {
assert(IsDirectory());
opaque_ = true;
}
unsigned int SyncItem::GetRdOnlyLinkcount() const {
StatRdOnly();
return rdonly_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetRdOnlyInode() const {
StatRdOnly();
return rdonly_stat_.stat.st_ino;
}
unsigned int SyncItem::GetUnionLinkcount() const {
StatUnion();
return union_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetUnionInode() const {
StatUnion();
return union_stat_.stat.st_ino;
}
void SyncItem::StatGeneric(const string &path,
EntryStat *info,
const bool refresh) {
if (info->obtained && !refresh) return;
int retval = platform_lstat(path.c_str(), &info->stat);
info->error_code = (retval != 0) ? errno : 0;
info->obtained = true;
}
catalog::DirectoryEntryBase SyncItem::CreateBasicCatalogDirent() const {
catalog::DirectoryEntryBase dirent;
// inode and parent inode is determined at runtime of client
dirent.inode_ = catalog::DirectoryEntry::kInvalidInode;
// this might mask the actual link count in case hardlinks are not supported
// (i.e. on setups using OverlayFS)
dirent.linkcount_ = HasHardlinks() ? this->GetUnionStat().st_nlink : 1;
dirent.mode_ = this->GetUnionStat().st_mode;
dirent.uid_ = this->GetUnionStat().st_uid;
dirent.gid_ = this->GetUnionStat().st_gid;
dirent.size_ = graft_size_ > -1 ? graft_size_ :
this->GetUnionStat().st_size;
dirent.mtime_ = this->GetUnionStat().st_mtime;
dirent.checksum_ = this->GetContentHash();
dirent.is_external_file_ = this->IsExternalData();
dirent.compression_algorithm_ = this->GetCompressionAlgorithm();
dirent.name_.Assign(filename_.data(), filename_.length());
if (this->IsSymlink()) {
char slnk[PATH_MAX+1];
const ssize_t length =
readlink((this->GetUnionPath()).c_str(), slnk, PATH_MAX);
assert(length >= 0);
dirent.symlink_.Assign(slnk, length);
}
return dirent;
}
std::string SyncItem::GetRdOnlyPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->rdonly_path() + relative_path;
}
std::string SyncItem::GetUnionPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->union_path() + relative_path;
}
std::string SyncItem::GetScratchPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->scratch_path() + relative_path;
}
void SyncItem::CheckMarkerFiles() {
if (IsRegularFile()) {
CheckGraft();
} else if (IsDirectory()) {
CheckCatalogMarker();
}
}
void SyncItem::CheckCatalogMarker() {
has_catalog_marker_ = FileExists(GetUnionPath() + "/.cvmfscatalog");
}
std::string SyncItem::GetGraftMarkerPath() const {
return union_engine_->scratch_path() + "/" +
((relative_parent_path_.empty()) ?
".cvmfsgraft-" + filename_ :
relative_parent_path_ + (filename_.empty() ? "" :
("/.cvmfsgraft-" + filename_)));
}
void SyncItem::CheckGraft() {
valid_graft_ = false;
bool found_checksum = false;
std::string checksum_type;
std::string checksum_value;
std::string graftfile = GetGraftMarkerPath();
LogCvmfs(kLogFsTraversal, kLogDebug, "Checking potential graft path %s.",
graftfile.c_str());
FILE *fp = fopen(graftfile.c_str(), "r");
if (fp == NULL) {
if (errno != ENOENT) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to open graft file "
"(%s): %s (errno=%d)",
graftfile.c_str(), strerror(errno), errno);
}
return;
}
graft_marker_present_ = true;
valid_graft_ = true;
std::string line;
std::vector<std::string> contents;
std::vector<off_t> chunk_offsets;
std::vector<shash::Any> chunk_checksums;
while (GetLineFile(fp, &line)) {
std::string trimmed_line = Trim(line);
if (!trimmed_line.size()) {continue;}
if (trimmed_line[0] == '#') {continue;}
std::vector<std::string> info = SplitString(trimmed_line, '=', 2);
if (info.size() != 2) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid line in graft file: %s",
trimmed_line.c_str());
}
info[0] = Trim(info[0]);
info[1] = Trim(info[1]);
if (info[0] == "size") {
uint64_t tmp_size;
if (!String2Uint64Parse(info[1], &tmp_size)) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Failed to parse value of %s "
"to integer: %s (errno=%d)", trimmed_line.c_str(),
strerror(errno), errno);
continue;
}
graft_size_ = tmp_size;
} else if (info[0] == "checksum") {
std::string hash_str = info[1];
shash::HexPtr hashP(hash_str);
if (hashP.IsValid()) {
content_hash_ = shash::MkFromHexPtr(hashP);
found_checksum = true;
} else {
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid checksum value: %s.",
info[1].c_str());
}
continue;
} else if (info[0] == "chunk_offsets") {
std::vector<std::string> offsets = SplitString(info[1], ',');
for (std::vector<std::string>::const_iterator it = offsets.begin();
it != offsets.end(); it++)
{
uint64_t val;
if (!String2Uint64Parse(*it, &val)) {
valid_graft_ = false;
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk offset: %s.",
it->c_str());
break;
}
chunk_offsets.push_back(val);
}
} else if (info[0] == "chunk_checksums") {
std::vector<std::string> csums = SplitString(info[1], ',');
for (std::vector<std::string>::const_iterator it = csums.begin();
it != csums.end(); it++)
{
shash::HexPtr hashP(*it);
if (hashP.IsValid()) {
chunk_checksums.push_back(shash::MkFromHexPtr(hashP));
} else {
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk checksum "
"value: %s.", it->c_str());
valid_graft_ = false;
break;
}
}
}
}
if (!feof(fp)) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to read from catalog "
"marker (%s): %s (errno=%d)",
graftfile.c_str(), strerror(errno), errno);
}
fclose(fp);
valid_graft_ = valid_graft_ && (graft_size_ > -1) && found_checksum
&& (chunk_checksums.size() == chunk_offsets.size());
if (!valid_graft_ || chunk_offsets.empty())
return;
// Parse chunks
graft_chunklist_ = new FileChunkList(chunk_offsets.size());
off_t last_offset = chunk_offsets[0];
if (last_offset != 0) {
LogCvmfs(kLogFsTraversal, kLogWarning, "First chunk offset must be 0"
" (in graft marker %s).", graftfile.c_str());
valid_graft_ = false;
}
for (unsigned idx = 1; idx < chunk_offsets.size(); idx++) {
off_t cur_offset = chunk_offsets[idx];
if (last_offset >= cur_offset) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Chunk offsets must be sorted "
"in strictly increasing order (in graft marker %s).",
graftfile.c_str());
valid_graft_ = false;
break;
}
size_t cur_size = cur_offset - last_offset;
graft_chunklist_->PushBack(FileChunk(chunk_checksums[idx - 1],
last_offset,
cur_size));
last_offset = cur_offset;
}
if (graft_size_ <= last_offset) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Last offset must be strictly "
"less than total file size (in graft marker %s).",
graftfile.c_str());
valid_graft_ = false;
}
graft_chunklist_->PushBack(FileChunk(chunk_checksums.back(),
last_offset,
graft_size_ - last_offset));
}
} // namespace publish
<commit_msg>fix false warning about graft files when removing subtrees on overlayfs<commit_after>/**
* This file is part of the CernVM file system
*/
#include "sync_item.h"
#include <cerrno>
#include <vector>
#include "sync_mediator.h"
#include "sync_union.h"
using namespace std; // NOLINT
namespace publish {
SyncItem::SyncItem() :
union_engine_(NULL),
whiteout_(false),
opaque_(false),
masked_hardlink_(false),
has_catalog_marker_(false),
valid_graft_(false),
graft_marker_present_(false),
external_data_(false),
graft_chunklist_(NULL),
graft_size_(-1),
scratch_type_(static_cast<SyncItemType>(0)),
rdonly_type_(static_cast<SyncItemType>(0)),
compression_algorithm_(zlib::kZlibDefault) {}
SyncItem::SyncItem(const string &relative_parent_path,
const string &filename,
const SyncUnion *union_engine,
const SyncItemType entry_type) :
union_engine_(union_engine),
whiteout_(false),
opaque_(false),
masked_hardlink_(false),
has_catalog_marker_(false),
valid_graft_(false),
graft_marker_present_(false),
external_data_(false),
relative_parent_path_(relative_parent_path),
filename_(filename),
graft_chunklist_(NULL),
graft_size_(-1),
scratch_type_(entry_type),
rdonly_type_(kItemUnknown),
compression_algorithm_(zlib::kZlibDefault)
{
content_hash_.algorithm = shash::kAny;
CheckMarkerFiles();
}
SyncItem::~SyncItem() {
delete graft_chunklist_;
}
SyncItemType SyncItem::GetGenericFiletype(const SyncItem::EntryStat &stat) const
{
const SyncItemType type = stat.GetSyncItemType();
if (type == kItemUnknown) {
PrintWarning("'" + GetRelativePath() + "' has an unsupported file type "
"(st_mode: " + StringifyInt(stat.stat.st_mode) +
" errno: " + StringifyInt(stat.error_code) + ")");
abort();
}
return type;
}
SyncItemType SyncItem::GetRdOnlyFiletype() const {
StatRdOnly();
// file could not exist in read-only branch, or a regular file could have
// been replaced by a directory in the read/write branch, like:
// rdonly:
// /foo/bar/regular_file <-- ENOTDIR when asking for (.../is_dir_now)
// r/w:
// /foo/bar/regular_file/
// /foo/bar/regular_file/is_dir_now
if (rdonly_stat_.error_code == ENOENT ||
rdonly_stat_.error_code == ENOTDIR) return kItemNew;
return GetGenericFiletype(rdonly_stat_);
}
SyncItemType SyncItem::GetScratchFiletype() const {
StatScratch();
if (scratch_stat_.error_code != 0) {
PrintWarning("Failed to stat() '" + GetRelativePath() + "' in scratch. "
"(errno: " + StringifyInt(scratch_stat_.error_code) + ")");
abort();
}
return GetGenericFiletype(scratch_stat_);
}
void SyncItem::MarkAsWhiteout(const std::string &actual_filename) {
// Mark the file as whiteout entry and strip the whiteout prefix
whiteout_ = true;
filename_ = actual_filename;
// Find the entry in the repository
StatRdOnly(true); // <== refreshing the stat (filename might have changed)
const SyncItemType deleted_type = (rdonly_stat_.error_code == 0)
? GetRdOnlyFiletype()
: kItemUnknown;
rdonly_type_ = deleted_type;
scratch_type_ = deleted_type;
if (deleted_type == kItemUnknown) {
// Marking a SyncItem as 'whiteout' but no file to be removed found: This
// should not happen (actually AUFS prevents users from creating whiteouts)
// but can be provoked through an AUFS 'bug' (see test 593 or CVM-880).
// --> Warn the user, continue with kItemUnknown and cross your fingers!
PrintWarning("'" + GetRelativePath() + "' should be deleted, but was not "
"found in repository.");
}
}
void SyncItem::MarkAsOpaqueDirectory() {
assert(IsDirectory());
opaque_ = true;
}
unsigned int SyncItem::GetRdOnlyLinkcount() const {
StatRdOnly();
return rdonly_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetRdOnlyInode() const {
StatRdOnly();
return rdonly_stat_.stat.st_ino;
}
unsigned int SyncItem::GetUnionLinkcount() const {
StatUnion();
return union_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetUnionInode() const {
StatUnion();
return union_stat_.stat.st_ino;
}
void SyncItem::StatGeneric(const string &path,
EntryStat *info,
const bool refresh) {
if (info->obtained && !refresh) return;
int retval = platform_lstat(path.c_str(), &info->stat);
info->error_code = (retval != 0) ? errno : 0;
info->obtained = true;
}
catalog::DirectoryEntryBase SyncItem::CreateBasicCatalogDirent() const {
catalog::DirectoryEntryBase dirent;
// inode and parent inode is determined at runtime of client
dirent.inode_ = catalog::DirectoryEntry::kInvalidInode;
// this might mask the actual link count in case hardlinks are not supported
// (i.e. on setups using OverlayFS)
dirent.linkcount_ = HasHardlinks() ? this->GetUnionStat().st_nlink : 1;
dirent.mode_ = this->GetUnionStat().st_mode;
dirent.uid_ = this->GetUnionStat().st_uid;
dirent.gid_ = this->GetUnionStat().st_gid;
dirent.size_ = graft_size_ > -1 ? graft_size_ :
this->GetUnionStat().st_size;
dirent.mtime_ = this->GetUnionStat().st_mtime;
dirent.checksum_ = this->GetContentHash();
dirent.is_external_file_ = this->IsExternalData();
dirent.compression_algorithm_ = this->GetCompressionAlgorithm();
dirent.name_.Assign(filename_.data(), filename_.length());
if (this->IsSymlink()) {
char slnk[PATH_MAX+1];
const ssize_t length =
readlink((this->GetUnionPath()).c_str(), slnk, PATH_MAX);
assert(length >= 0);
dirent.symlink_.Assign(slnk, length);
}
return dirent;
}
std::string SyncItem::GetRdOnlyPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->rdonly_path() + relative_path;
}
std::string SyncItem::GetUnionPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->union_path() + relative_path;
}
std::string SyncItem::GetScratchPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->scratch_path() + relative_path;
}
void SyncItem::CheckMarkerFiles() {
if (IsRegularFile()) {
CheckGraft();
} else if (IsDirectory()) {
CheckCatalogMarker();
}
}
void SyncItem::CheckCatalogMarker() {
has_catalog_marker_ = FileExists(GetUnionPath() + "/.cvmfscatalog");
}
std::string SyncItem::GetGraftMarkerPath() const {
return union_engine_->scratch_path() + "/" +
((relative_parent_path_.empty()) ?
".cvmfsgraft-" + filename_ :
relative_parent_path_ + (filename_.empty() ? "" :
("/.cvmfsgraft-" + filename_)));
}
void SyncItem::CheckGraft() {
valid_graft_ = false;
bool found_checksum = false;
std::string checksum_type;
std::string checksum_value;
std::string graftfile = GetGraftMarkerPath();
LogCvmfs(kLogFsTraversal, kLogDebug, "Checking potential graft path %s.",
graftfile.c_str());
FILE *fp = fopen(graftfile.c_str(), "r");
if (fp == NULL) {
// This sync item can be a file from a removed directory tree on overlayfs.
// In this case, the entire tree is missing on the scratch directory and
// the errno is ENOTDIR.
if ((errno != ENOENT) && (errno != ENOTDIR)) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to open graft file "
"(%s): %s (errno=%d)",
graftfile.c_str(), strerror(errno), errno);
}
return;
}
graft_marker_present_ = true;
valid_graft_ = true;
std::string line;
std::vector<std::string> contents;
std::vector<off_t> chunk_offsets;
std::vector<shash::Any> chunk_checksums;
while (GetLineFile(fp, &line)) {
std::string trimmed_line = Trim(line);
if (!trimmed_line.size()) {continue;}
if (trimmed_line[0] == '#') {continue;}
std::vector<std::string> info = SplitString(trimmed_line, '=', 2);
if (info.size() != 2) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid line in graft file: %s",
trimmed_line.c_str());
}
info[0] = Trim(info[0]);
info[1] = Trim(info[1]);
if (info[0] == "size") {
uint64_t tmp_size;
if (!String2Uint64Parse(info[1], &tmp_size)) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Failed to parse value of %s "
"to integer: %s (errno=%d)", trimmed_line.c_str(),
strerror(errno), errno);
continue;
}
graft_size_ = tmp_size;
} else if (info[0] == "checksum") {
std::string hash_str = info[1];
shash::HexPtr hashP(hash_str);
if (hashP.IsValid()) {
content_hash_ = shash::MkFromHexPtr(hashP);
found_checksum = true;
} else {
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid checksum value: %s.",
info[1].c_str());
}
continue;
} else if (info[0] == "chunk_offsets") {
std::vector<std::string> offsets = SplitString(info[1], ',');
for (std::vector<std::string>::const_iterator it = offsets.begin();
it != offsets.end(); it++)
{
uint64_t val;
if (!String2Uint64Parse(*it, &val)) {
valid_graft_ = false;
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk offset: %s.",
it->c_str());
break;
}
chunk_offsets.push_back(val);
}
} else if (info[0] == "chunk_checksums") {
std::vector<std::string> csums = SplitString(info[1], ',');
for (std::vector<std::string>::const_iterator it = csums.begin();
it != csums.end(); it++)
{
shash::HexPtr hashP(*it);
if (hashP.IsValid()) {
chunk_checksums.push_back(shash::MkFromHexPtr(hashP));
} else {
LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk checksum "
"value: %s.", it->c_str());
valid_graft_ = false;
break;
}
}
}
}
if (!feof(fp)) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to read from catalog "
"marker (%s): %s (errno=%d)",
graftfile.c_str(), strerror(errno), errno);
}
fclose(fp);
valid_graft_ = valid_graft_ && (graft_size_ > -1) && found_checksum
&& (chunk_checksums.size() == chunk_offsets.size());
if (!valid_graft_ || chunk_offsets.empty())
return;
// Parse chunks
graft_chunklist_ = new FileChunkList(chunk_offsets.size());
off_t last_offset = chunk_offsets[0];
if (last_offset != 0) {
LogCvmfs(kLogFsTraversal, kLogWarning, "First chunk offset must be 0"
" (in graft marker %s).", graftfile.c_str());
valid_graft_ = false;
}
for (unsigned idx = 1; idx < chunk_offsets.size(); idx++) {
off_t cur_offset = chunk_offsets[idx];
if (last_offset >= cur_offset) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Chunk offsets must be sorted "
"in strictly increasing order (in graft marker %s).",
graftfile.c_str());
valid_graft_ = false;
break;
}
size_t cur_size = cur_offset - last_offset;
graft_chunklist_->PushBack(FileChunk(chunk_checksums[idx - 1],
last_offset,
cur_size));
last_offset = cur_offset;
}
if (graft_size_ <= last_offset) {
LogCvmfs(kLogFsTraversal, kLogWarning, "Last offset must be strictly "
"less than total file size (in graft marker %s).",
graftfile.c_str());
valid_graft_ = false;
}
graft_chunklist_->PushBack(FileChunk(chunk_checksums.back(),
last_offset,
graft_size_ - last_offset));
}
} // namespace publish
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkImageToImageMetricv4GetValueAndDerivativeThreaderBase_hxx
#define __itkImageToImageMetricv4GetValueAndDerivativeThreaderBase_hxx
#include "itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.h"
#include "itkNumericTraits.h"
namespace itk
{
template< class TDomainPartitioner, class TImageToImageMetricv4 >
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::ImageToImageMetricv4GetValueAndDerivativeThreaderBase()
{
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
void
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::BeforeThreadedExecution()
{
//---------------------------------------------------------------
// Resize the per thread memory objects.
/* Per-thread results */
this->m_MeasurePerThread.resize( this->GetNumberOfThreadsUsed() );
this->m_NumberOfValidPointsPerThread.resize( this->GetNumberOfThreadsUsed() );
this->m_DerivativesPerThread.resize( this->GetNumberOfThreadsUsed() );
this->m_CompensatedDerivativesPerThread.resize( this->GetNumberOfThreadsUsed() );
/* This one is intermediary, for getting per-point results. */
this->m_LocalDerivativesPerThread.resize( this->GetNumberOfThreadsUsed() );
/* Per-thread pre-allocated Jacobian objects for efficiency */
this->m_MovingTransformJacobianPerThread.resize( this->GetNumberOfThreadsUsed() );
/* This size always comes from the moving image */
const NumberOfParametersType globalDerivativeSize =
this->m_Associate->m_MovingTransform->GetNumberOfParameters();
for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++)
{
/* Allocate intermediary per-thread storage used to get results from
* derived classes */
this->m_LocalDerivativesPerThread[i].SetSize(
this->m_Associate->GetNumberOfLocalParameters() );
this->m_MovingTransformJacobianPerThread[i].SetSize(
this->m_Associate->VirtualImageDimension,
this->m_Associate->GetNumberOfLocalParameters() );
if ( this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
/* For transforms with local support, e.g. displacement field,
* use a single derivative container that's updated by region
* in multiple threads.
* Initialization to zero is done in main class. */
itkDebugMacro(
"ImageToImageMetricv4::Initialize: transform HAS local support\n");
/* Set each per-thread object to point to m_DerivativeResult for efficiency. */
this->m_DerivativesPerThread[i].SetData(
this->m_Associate->m_DerivativeResult->data_block(),
this->m_Associate->m_DerivativeResult->Size(),
false );
}
else
{
itkDebugMacro(
"ImageToImageMetricv4::Initialize: transform does NOT have local support\n");
/* Global transforms get a separate derivatives container for each thread
* that holds the result over a particular image region.
* Use a CompensatedSummation value to provide for better consistency between
* different number of threads. */
this->m_CompensatedDerivativesPerThread[i].resize( globalDerivativeSize );
}
}
//---------------------------------------------------------------
// Set initial values.
for (ThreadIdType thread = 0; thread<this->GetNumberOfThreadsUsed(); thread++)
{
this->m_NumberOfValidPointsPerThread[thread] = NumericTraits< SizeValueType >::Zero;
this->m_MeasurePerThread[thread] = NumericTraits< InternalComputationValueType >::Zero;
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
/* Be sure to init to 0 here, because the threader may not use
* all the threads if the region is better split into fewer
* subregions. */
for( NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
this->m_CompensatedDerivativesPerThread[thread][p].ResetToZero();
}
}
}
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
void
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::AfterThreadedExecution()
{
/* Store the number of valid points the enclosing class \c
* m_NumberOfValidPoints by collecting the valid points per thread. */
this->m_Associate->m_NumberOfValidPoints = NumericTraits< SizeValueType >::Zero;
for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++)
{
this->m_Associate->m_NumberOfValidPoints += this->m_NumberOfValidPointsPerThread[i];
}
itkDebugMacro( "ImageToImageMetricv4: NumberOfValidPoints: "
<< this->m_Associate->m_NumberOfValidPoints );
/* For global transforms, sum the derivatives from each region. */
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
for (NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
/* Use a compensated sum to be ready for when there is a very large number of threads */
CompensatedDerivativeValueType sum;
sum.ResetToZero();
for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++)
{
sum += this->m_CompensatedDerivativesPerThread[i][p].GetSum();
}
(*(this->m_Associate->m_DerivativeResult))[p] += sum.GetSum();
}
}
/* Check the number of valid points. If there aren't enough,
* m_Value and m_DerivativeResult will get appropriate values assigned,
* and a warning will be output. */
if( this->m_Associate->VerifyNumberOfValidPoints( this->m_Associate->m_Value, *(this->m_Associate->m_DerivativeResult) ) )
{
this->m_Associate->m_Value = NumericTraits<MeasureType>::Zero;
/* Accumulate the metric value from threads and store the average. */
for(size_t i=0; i< this->m_MeasurePerThread.size(); i++)
{
this->m_Associate->m_Value += this->m_MeasurePerThread[i];
}
this->m_Associate->m_Value /= this->m_Associate->m_NumberOfValidPoints;
/* For global transforms, calculate the average values */
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
*(this->m_Associate->m_DerivativeResult) /= this->m_Associate->m_NumberOfValidPoints;
}
}
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
bool
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::ProcessVirtualPoint( const VirtualIndexType & virtualIndex,
const VirtualPointType & virtualPoint,
const ThreadIdType threadId )
{
FixedOutputPointType mappedFixedPoint;
FixedImagePixelType mappedFixedPixelValue;
FixedImageGradientType mappedFixedImageGradient;
MovingOutputPointType mappedMovingPoint;
MovingImagePixelType mappedMovingPixelValue;
MovingImageGradientType mappedMovingImageGradient;
bool pointIsValid = false;
MeasureType metricValueResult;
/* Transform the point into fixed and moving spaces, and evaluate.
* Do this in a try block to catch exceptions and print more useful info
* then we otherwise get when exceptions are caught in MultiThreader. */
try
{
pointIsValid = this->m_Associate->TransformAndEvaluateFixedPoint( virtualIndex,
virtualPoint,
this->m_Associate->GetGradientSourceIncludesFixed(),
mappedFixedPoint,
mappedFixedPixelValue,
mappedFixedImageGradient );
}
catch( ExceptionObject & exc )
{
//NOTE: there must be a cleaner way to do this:
std::string msg("Caught exception: \n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
if( !pointIsValid )
{
return pointIsValid;
}
try
{
pointIsValid = this->m_Associate->TransformAndEvaluateMovingPoint( virtualIndex,
virtualPoint,
this->m_Associate->GetGradientSourceIncludesMoving(),
mappedMovingPoint,
mappedMovingPixelValue,
mappedMovingImageGradient );
}
catch( ExceptionObject & exc )
{
std::string msg("Caught exception: \n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
if( !pointIsValid )
{
return pointIsValid;
}
/* Call the user method in derived classes to do the specific
* calculations for value and derivative. */
try
{
pointIsValid = this->ProcessPoint(
virtualIndex,
virtualPoint,
mappedFixedPoint, mappedFixedPixelValue,
mappedFixedImageGradient,
mappedMovingPoint, mappedMovingPixelValue,
mappedMovingImageGradient,
metricValueResult, this->m_LocalDerivativesPerThread[threadId],
threadId );
}
catch( ExceptionObject & exc )
{
//NOTE: there must be a cleaner way to do this:
std::string msg("Exception in GetValueAndDerivativeProcessPoint:\n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
if( pointIsValid )
{
this->m_NumberOfValidPointsPerThread[threadId]++;
this->m_MeasurePerThread[threadId] += metricValueResult;
this->StorePointDerivativeResult( virtualIndex, threadId );
}
return pointIsValid;
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
void
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::StorePointDerivativeResult( const VirtualIndexType & virtualIndex,
const ThreadIdType threadId )
{
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
/* Global support */
if ( this->m_Associate->GetUseFloatingPointCorrection() )
{
DerivativeValueType correctionResolution = this->m_Associate->GetFloatingPointCorrectionResolution();
for (NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
intmax_t test = static_cast< intmax_t >( this->m_LocalDerivativesPerThread[threadId][p] * correctionResolution );
this->m_LocalDerivativesPerThread[threadId][p] = static_cast<DerivativeValueType>( test / correctionResolution );
}
}
for (NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
this->m_CompensatedDerivativesPerThread[threadId][p] += this->m_LocalDerivativesPerThread[threadId][p];
}
}
else
{
// Update derivative at some index
// this requires the moving image displacement field to be
// same size as virtual image, and that VirtualImage PixelType
// is scalar.
try
{
OffsetValueType offset =
this->m_Associate->ComputeParameterOffsetFromVirtualDomainIndex( virtualIndex, this->m_Associate->m_MovingTransform->GetNumberOfLocalParameters() );
for (NumberOfParametersType i=0;
i < this->m_Associate->m_MovingTransform->GetNumberOfLocalParameters(); i++)
{
/* Be sure to *add* here and not assign. Required for proper behavior
* with multi-variate metric. */
this->m_DerivativesPerThread[threadId][offset+i] += this->m_LocalDerivativesPerThread[threadId][i];
}
}
catch( ExceptionObject & exc )
{
std::string msg("Caught exception: \n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
}
}
} // end namespace itk
#endif
<commit_msg>BUG: Avoid EXC_BAD_ACCESS access when resizing array<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkImageToImageMetricv4GetValueAndDerivativeThreaderBase_hxx
#define __itkImageToImageMetricv4GetValueAndDerivativeThreaderBase_hxx
#include "itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.h"
#include "itkNumericTraits.h"
namespace itk
{
template< class TDomainPartitioner, class TImageToImageMetricv4 >
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::ImageToImageMetricv4GetValueAndDerivativeThreaderBase()
{
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
void
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::BeforeThreadedExecution()
{
//---------------------------------------------------------------
// Resize the per thread memory objects.
/* Per-thread results */
this->m_MeasurePerThread.resize( this->GetNumberOfThreadsUsed() );
this->m_NumberOfValidPointsPerThread.resize( this->GetNumberOfThreadsUsed() );
this->m_CompensatedDerivativesPerThread.resize( this->GetNumberOfThreadsUsed() );
/* This one is intermediary, for getting per-point results. */
this->m_LocalDerivativesPerThread.resize( this->GetNumberOfThreadsUsed() );
/* Per-thread pre-allocated Jacobian objects for efficiency */
this->m_MovingTransformJacobianPerThread.resize( this->GetNumberOfThreadsUsed() );
/* Make sure to clear this vector first. Otherwise if we've previoulsy pointed each element
* Array to an m_DerivativeResult that's been deallocated, we'll get an access
* exception if the vector is resized to a larger size, triggering a copy of the
* first element. */
this->m_DerivativesPerThread.clear();
this->m_DerivativesPerThread.resize( this->GetNumberOfThreadsUsed() );
/* This size always comes from the moving image */
const NumberOfParametersType globalDerivativeSize =
this->m_Associate->m_MovingTransform->GetNumberOfParameters();
for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++)
{
/* Allocate intermediary per-thread storage used to get results from
* derived classes */
this->m_LocalDerivativesPerThread[i].SetSize(
this->m_Associate->GetNumberOfLocalParameters() );
this->m_MovingTransformJacobianPerThread[i].SetSize(
this->m_Associate->VirtualImageDimension,
this->m_Associate->GetNumberOfLocalParameters() );
if ( this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
/* For transforms with local support, e.g. displacement field,
* use a single derivative container that's updated by region
* in multiple threads.
* Initialization to zero is done in main class. */
itkDebugMacro("ImageToImageMetricv4::Initialize: transform HAS local support\n");
/* Set each per-thread object to point to m_DerivativeResult for efficiency. */
this->m_DerivativesPerThread[i].SetData(
this->m_Associate->m_DerivativeResult->data_block(),
this->m_Associate->m_DerivativeResult->Size(),
false );
}
else
{
itkDebugMacro("ImageToImageMetricv4::Initialize: transform does NOT have local support\n");
/* Global transforms get a separate derivatives container for each thread
* that holds the result over a particular image region.
* Use a CompensatedSummation value to provide for better consistency between
* different number of threads. */
this->m_CompensatedDerivativesPerThread[i].resize( globalDerivativeSize );
}
}
//---------------------------------------------------------------
// Set initial values.
for (ThreadIdType thread = 0; thread<this->GetNumberOfThreadsUsed(); thread++)
{
this->m_NumberOfValidPointsPerThread[thread] = NumericTraits< SizeValueType >::Zero;
this->m_MeasurePerThread[thread] = NumericTraits< InternalComputationValueType >::Zero;
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
/* Be sure to init to 0 here, because the threader may not use
* all the threads if the region is better split into fewer
* subregions. */
for( NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
this->m_CompensatedDerivativesPerThread[thread][p].ResetToZero();
}
}
}
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
void
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::AfterThreadedExecution()
{
/* Store the number of valid points the enclosing class \c
* m_NumberOfValidPoints by collecting the valid points per thread. */
this->m_Associate->m_NumberOfValidPoints = NumericTraits< SizeValueType >::Zero;
for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++)
{
this->m_Associate->m_NumberOfValidPoints += this->m_NumberOfValidPointsPerThread[i];
}
itkDebugMacro( "ImageToImageMetricv4: NumberOfValidPoints: "
<< this->m_Associate->m_NumberOfValidPoints );
/* For global transforms, sum the derivatives from each region. */
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
for (NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
/* Use a compensated sum to be ready for when there is a very large number of threads */
CompensatedDerivativeValueType sum;
sum.ResetToZero();
for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++)
{
sum += this->m_CompensatedDerivativesPerThread[i][p].GetSum();
}
(*(this->m_Associate->m_DerivativeResult))[p] += sum.GetSum();
}
}
/* Check the number of valid points. If there aren't enough,
* m_Value and m_DerivativeResult will get appropriate values assigned,
* and a warning will be output. */
if( this->m_Associate->VerifyNumberOfValidPoints( this->m_Associate->m_Value, *(this->m_Associate->m_DerivativeResult) ) )
{
this->m_Associate->m_Value = NumericTraits<MeasureType>::Zero;
/* Accumulate the metric value from threads and store the average. */
for(size_t i=0; i< this->m_MeasurePerThread.size(); i++)
{
this->m_Associate->m_Value += this->m_MeasurePerThread[i];
}
this->m_Associate->m_Value /= this->m_Associate->m_NumberOfValidPoints;
/* For global transforms, calculate the average values */
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
*(this->m_Associate->m_DerivativeResult) /= this->m_Associate->m_NumberOfValidPoints;
}
}
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
bool
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::ProcessVirtualPoint( const VirtualIndexType & virtualIndex,
const VirtualPointType & virtualPoint,
const ThreadIdType threadId )
{
FixedOutputPointType mappedFixedPoint;
FixedImagePixelType mappedFixedPixelValue;
FixedImageGradientType mappedFixedImageGradient;
MovingOutputPointType mappedMovingPoint;
MovingImagePixelType mappedMovingPixelValue;
MovingImageGradientType mappedMovingImageGradient;
bool pointIsValid = false;
MeasureType metricValueResult;
/* Transform the point into fixed and moving spaces, and evaluate.
* Do this in a try block to catch exceptions and print more useful info
* then we otherwise get when exceptions are caught in MultiThreader. */
try
{
pointIsValid = this->m_Associate->TransformAndEvaluateFixedPoint( virtualIndex,
virtualPoint,
this->m_Associate->GetGradientSourceIncludesFixed(),
mappedFixedPoint,
mappedFixedPixelValue,
mappedFixedImageGradient );
}
catch( ExceptionObject & exc )
{
//NOTE: there must be a cleaner way to do this:
std::string msg("Caught exception: \n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
if( !pointIsValid )
{
return pointIsValid;
}
try
{
pointIsValid = this->m_Associate->TransformAndEvaluateMovingPoint( virtualIndex,
virtualPoint,
this->m_Associate->GetGradientSourceIncludesMoving(),
mappedMovingPoint,
mappedMovingPixelValue,
mappedMovingImageGradient );
}
catch( ExceptionObject & exc )
{
std::string msg("Caught exception: \n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
if( !pointIsValid )
{
return pointIsValid;
}
/* Call the user method in derived classes to do the specific
* calculations for value and derivative. */
try
{
pointIsValid = this->ProcessPoint(
virtualIndex,
virtualPoint,
mappedFixedPoint, mappedFixedPixelValue,
mappedFixedImageGradient,
mappedMovingPoint, mappedMovingPixelValue,
mappedMovingImageGradient,
metricValueResult, this->m_LocalDerivativesPerThread[threadId],
threadId );
}
catch( ExceptionObject & exc )
{
//NOTE: there must be a cleaner way to do this:
std::string msg("Exception in GetValueAndDerivativeProcessPoint:\n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
if( pointIsValid )
{
this->m_NumberOfValidPointsPerThread[threadId]++;
this->m_MeasurePerThread[threadId] += metricValueResult;
this->StorePointDerivativeResult( virtualIndex, threadId );
}
return pointIsValid;
}
template< class TDomainPartitioner, class TImageToImageMetricv4 >
void
ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 >
::StorePointDerivativeResult( const VirtualIndexType & virtualIndex,
const ThreadIdType threadId )
{
if ( ! this->m_Associate->m_MovingTransform->HasLocalSupport() )
{
/* Global support */
if ( this->m_Associate->GetUseFloatingPointCorrection() )
{
DerivativeValueType correctionResolution = this->m_Associate->GetFloatingPointCorrectionResolution();
for (NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
intmax_t test = static_cast< intmax_t >( this->m_LocalDerivativesPerThread[threadId][p] * correctionResolution );
this->m_LocalDerivativesPerThread[threadId][p] = static_cast<DerivativeValueType>( test / correctionResolution );
}
}
for (NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ )
{
this->m_CompensatedDerivativesPerThread[threadId][p] += this->m_LocalDerivativesPerThread[threadId][p];
}
}
else
{
// Update derivative at some index
// this requires the moving image displacement field to be
// same size as virtual image, and that VirtualImage PixelType
// is scalar.
try
{
OffsetValueType offset =
this->m_Associate->ComputeParameterOffsetFromVirtualDomainIndex( virtualIndex, this->m_Associate->m_MovingTransform->GetNumberOfLocalParameters() );
for (NumberOfParametersType i=0;
i < this->m_Associate->m_MovingTransform->GetNumberOfLocalParameters(); i++)
{
/* Be sure to *add* here and not assign. Required for proper behavior
* with multi-variate metric. */
this->m_DerivativesPerThread[threadId][offset+i] += this->m_LocalDerivativesPerThread[threadId][i];
}
}
catch( ExceptionObject & exc )
{
std::string msg("Caught exception: \n");
msg += exc.what();
ExceptionObject err(__FILE__, __LINE__, msg);
throw err;
}
}
}
} // end namespace itk
#endif
<|endoftext|> |
<commit_before>// Author: Wim Lavrijsen, Jan 2005
// Bindings
#include "PyROOT.h"
#include "TemplateProxy.h"
#include "Utility.h"
namespace PyROOT {
namespace {
//= PyROOT template proxy construction/destruction ===========================
TemplateProxy* tpp_new( PyTypeObject*, PyObject*, PyObject* )
{
// Create a new empty template method proxy.
TemplateProxy* pytmpl = PyObject_GC_New( TemplateProxy, &TemplateProxy_Type );
pytmpl->fPyName = NULL;
pytmpl->fPyClass = NULL;
pytmpl->fSelf = NULL;
PyObject_GC_Track( pytmpl );
return pytmpl;
}
//____________________________________________________________________________
void tpp_dealloc( TemplateProxy* pytmpl )
{
// Destroy the given template method proxy.
PyObject_GC_UnTrack( pytmpl );
PyObject_GC_Del( pytmpl );
}
//____________________________________________________________________________
int tpp_traverse( TemplateProxy* pytmpl, visitproc visit, void* args )
{
// Garbage collector traverse of held python member objects.
if ( pytmpl->fPyName ) {
int err = visit( (PyObject*)pytmpl->fPyName, args );
if ( err )
return err;
}
if ( pytmpl->fPyClass ) {
int err = visit( (PyObject*)pytmpl->fPyClass, args );
if ( err )
return err;
}
if ( pytmpl->fSelf ) {
int err = visit( (PyObject*)pytmpl->fSelf, args );
if ( err )
return err;
}
return 0;
}
//____________________________________________________________________________
int tpp_clear( TemplateProxy* pytmpl )
{
// Garbage collector clear of held python member objects.
Py_XDECREF( (PyObject*)pytmpl->fPyName );
pytmpl->fPyName = NULL;
Py_XDECREF( (PyObject*)pytmpl->fPyClass );
pytmpl->fPyClass = NULL;
Py_XDECREF( (PyObject*)pytmpl->fSelf );
pytmpl->fSelf = NULL;
return 0;
}
//= PyROOT template proxy callable behavior ==================================
PyObject* tpp_call( TemplateProxy* pytmpl, PyObject* args, PyObject* kwds )
{
// dispatcher to the actual member method, args is self object + template arguments
// (as in a function call); build full instantiation
PyObject* pymeth = 0;
Py_ssize_t nArgs = PyTuple_GET_SIZE( args );
if ( 1 <= nArgs ) {
// build "< type, type, ... >" part of method name
Py_INCREF( pytmpl->fPyName );
PyObject* pyname = pytmpl->fPyName;
if ( Utility::BuildTemplateName( pyname, args, 0 ) ) {
// lookup method on self (to make sure it propagates), which is readily callable
pymeth = PyObject_GetAttr( pytmpl->fSelf, pyname );
}
Py_XDECREF( pyname );
}
if ( pymeth )
return pymeth; // templated, now called by the user
// if the method lookup fails, try to locate the "generic" version of the template
PyErr_Clear();
pymeth = PyObject_GetAttrString( pytmpl->fSelf, const_cast< char* >(
(std::string( "__generic_" ) + PyROOT_PyUnicode_AsString( pytmpl->fPyName )).c_str()) );
if ( pymeth ) {
PyObject* result = PyObject_Call( pymeth, args, kwds ); // non-templated, executed as-is
Py_DECREF( pymeth );
return result;
}
return pymeth;
}
//____________________________________________________________________________
TemplateProxy* tpp_descrget( TemplateProxy* pytmpl, PyObject* pyobj, PyObject* )
{
// create and use a new template proxy (language requirement)
TemplateProxy* newPyTmpl = (TemplateProxy*)TemplateProxy_Type.tp_alloc( &TemplateProxy_Type, 0 );
// copy name and class
Py_INCREF( pytmpl->fPyName );
newPyTmpl->fPyName = pytmpl->fPyName;
Py_XINCREF( pytmpl->fPyClass );
newPyTmpl->fPyClass = pytmpl->fPyClass;
// new method is to be bound to current object (may be NULL)
Py_XINCREF( pyobj );
newPyTmpl->fSelf = pyobj;
return newPyTmpl;
}
} // unnamed namespace
//= PyROOT template proxy type ===============================================
PyTypeObject TemplateProxy_Type = {
PyVarObject_HEAD_INIT( &PyType_Type, 0 )
(char*)"ROOT.TemplateProxy", // tp_name
sizeof(TemplateProxy), // tp_basicsize
0, // tp_itemsize
(destructor)tpp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
(ternaryfunc)tpp_call, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags
(char*)"PyROOT template proxy (internal)", // tp_doc
(traverseproc)tpp_traverse,// tp_traverse
(inquiry)tpp_clear, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
(descrgetfunc)tpp_descrget,// tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
(newfunc)tpp_new, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0 // tp_weaklist
#if PY_VERSION_HEX >= 0x02030000
, 0 // tp_del
#endif
#if PY_VERSION_HEX >= 0x02060000
, 0 // tp_version_tag
#endif
#if PY_VERSION_HEX >= 0x03040000
, 0 // tp_finalize
#endif
};
} // namespace PyROOT
<commit_msg>proper decrefs in tpp_dealloc (see ROOT-7112)<commit_after>// Author: Wim Lavrijsen, Jan 2005
// Bindings
#include "PyROOT.h"
#include "TemplateProxy.h"
#include "Utility.h"
namespace PyROOT {
namespace {
//= PyROOT template proxy construction/destruction ===========================
TemplateProxy* tpp_new( PyTypeObject*, PyObject*, PyObject* )
{
// Create a new empty template method proxy.
TemplateProxy* pytmpl = PyObject_GC_New( TemplateProxy, &TemplateProxy_Type );
pytmpl->fPyName = NULL;
pytmpl->fPyClass = NULL;
pytmpl->fSelf = NULL;
PyObject_GC_Track( pytmpl );
return pytmpl;
}
//____________________________________________________________________________
int tpp_clear( TemplateProxy* pytmpl )
{
// Garbage collector clear of held python member objects.
Py_CLEAR( pytmpl->fPyName );
Py_CLEAR( pytmpl->fPyClass );
Py_CLEAR( pytmpl->fSelf );
return 0;
}
//____________________________________________________________________________
void tpp_dealloc( TemplateProxy* pytmpl )
{
// Destroy the given template method proxy.
PyObject_GC_UnTrack( pytmpl );
tpp_clear( pytmpl );
PyObject_GC_Del( pytmpl );
}
//____________________________________________________________________________
int tpp_traverse( TemplateProxy* pytmpl, visitproc visit, void* args )
{
// Garbage collector traverse of held python member objects.
if ( pytmpl->fPyName ) {
int err = visit( (PyObject*)pytmpl->fPyName, args );
if ( err )
return err;
}
if ( pytmpl->fPyClass ) {
int err = visit( (PyObject*)pytmpl->fPyClass, args );
if ( err )
return err;
}
if ( pytmpl->fSelf ) {
int err = visit( (PyObject*)pytmpl->fSelf, args );
if ( err )
return err;
}
return 0;
}
//= PyROOT template proxy callable behavior ==================================
PyObject* tpp_call( TemplateProxy* pytmpl, PyObject* args, PyObject* kwds )
{
// dispatcher to the actual member method, args is self object + template arguments
// (as in a function call); build full instantiation
PyObject* pymeth = 0;
Py_ssize_t nArgs = PyTuple_GET_SIZE( args );
if ( 1 <= nArgs ) {
// build "< type, type, ... >" part of method name
Py_INCREF( pytmpl->fPyName );
PyObject* pyname = pytmpl->fPyName;
if ( Utility::BuildTemplateName( pyname, args, 0 ) ) {
// lookup method on self (to make sure it propagates), which is readily callable
pymeth = PyObject_GetAttr( pytmpl->fSelf, pyname );
}
Py_XDECREF( pyname );
}
if ( pymeth )
return pymeth; // templated, now called by the user
// if the method lookup fails, try to locate the "generic" version of the template
PyErr_Clear();
pymeth = PyObject_GetAttrString( pytmpl->fSelf, const_cast< char* >(
(std::string( "__generic_" ) + PyROOT_PyUnicode_AsString( pytmpl->fPyName )).c_str()) );
if ( pymeth ) {
PyObject* result = PyObject_Call( pymeth, args, kwds ); // non-templated, executed as-is
Py_DECREF( pymeth );
return result;
}
return pymeth;
}
//____________________________________________________________________________
TemplateProxy* tpp_descrget( TemplateProxy* pytmpl, PyObject* pyobj, PyObject* )
{
// create and use a new template proxy (language requirement)
TemplateProxy* newPyTmpl = (TemplateProxy*)TemplateProxy_Type.tp_alloc( &TemplateProxy_Type, 0 );
// copy name and class
Py_INCREF( pytmpl->fPyName );
newPyTmpl->fPyName = pytmpl->fPyName;
Py_XINCREF( pytmpl->fPyClass );
newPyTmpl->fPyClass = pytmpl->fPyClass;
// new method is to be bound to current object (may be NULL)
Py_XINCREF( pyobj );
newPyTmpl->fSelf = pyobj;
return newPyTmpl;
}
} // unnamed namespace
//= PyROOT template proxy type ===============================================
PyTypeObject TemplateProxy_Type = {
PyVarObject_HEAD_INIT( &PyType_Type, 0 )
(char*)"ROOT.TemplateProxy", // tp_name
sizeof(TemplateProxy), // tp_basicsize
0, // tp_itemsize
(destructor)tpp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
(ternaryfunc)tpp_call, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags
(char*)"PyROOT template proxy (internal)", // tp_doc
(traverseproc)tpp_traverse,// tp_traverse
(inquiry)tpp_clear, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
(descrgetfunc)tpp_descrget,// tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
(newfunc)tpp_new, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0 // tp_weaklist
#if PY_VERSION_HEX >= 0x02030000
, 0 // tp_del
#endif
#if PY_VERSION_HEX >= 0x02060000
, 0 // tp_version_tag
#endif
#if PY_VERSION_HEX >= 0x03040000
, 0 // tp_finalize
#endif
};
} // namespace PyROOT
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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
*
*****************************************************************************/
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/noncopyable.hpp>
// stl
#include <sstream>
#include <vector>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/query.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/memory_datasource.hpp>
using mapnik::datasource;
using mapnik::memory_datasource;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
namespace
{
//user-friendly wrapper that uses Python dictionary
using namespace boost::python;
std::shared_ptr<mapnik::datasource> create_datasource(dict const& d)
{
mapnik::parameters params;
boost::python::list keys=d.keys();
for (int i=0; i < len(keys); ++i)
{
std::string key = extract<std::string>(keys[i]);
object obj = d[key];
if (PyUnicode_Check(obj.ptr()))
{
PyObject* temp = PyUnicode_AsUTF8String(obj.ptr());
if (temp)
{
#if PY_VERSION_HEX >= 0x03000000
char* c_str = PyBytes_AsString(temp);
#else
char* c_str = PyString_AsString(temp);
#endif
params[key] = std::string(c_str);
Py_DecRef(temp);
}
continue;
}
extract<std::string> ex0(obj);
extract<mapnik::value_integer> ex1(obj);
extract<double> ex2(obj);
if (ex0.check())
{
params[key] = ex0();
}
else if (ex1.check())
{
params[key] = ex1();
}
else if (ex2.check())
{
params[key] = ex2();
}
}
return mapnik::datasource_cache::instance().create(params);
}
boost::python::dict describe(std::shared_ptr<mapnik::datasource> const& ds)
{
boost::python::dict description;
mapnik::layer_descriptor ld = ds->get_descriptor();
description["type"] = ds->type();
description["name"] = ld.get_name();
description["geometry_type"] = ds->get_geometry_type();
description["encoding"] = ld.get_encoding();
return description;
}
boost::python::list fields(std::shared_ptr<mapnik::datasource> const& ds)
{
boost::python::list flds;
if (ds)
{
layer_descriptor ld = ds->get_descriptor();
std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors();
std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_ar.end();
for (; it != end; ++it)
{
flds.append(it->get_name());
}
}
return flds;
}
boost::python::list field_types(std::shared_ptr<mapnik::datasource> const& ds)
{
boost::python::list fld_types;
if (ds)
{
layer_descriptor ld = ds->get_descriptor();
std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors();
std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_ar.end();
for (; it != end; ++it)
{
unsigned type = it->get_type();
if (type == mapnik::Integer)
// this crashes, so send back strings instead
//fld_types.append(boost::python::object(boost::python::handle<>(&PyInt_Type)));
fld_types.append(boost::python::str("int"));
else if (type == mapnik::Float)
fld_types.append(boost::python::str("float"));
else if (type == mapnik::Double)
fld_types.append(boost::python::str("float"));
else if (type == mapnik::String)
fld_types.append(boost::python::str("str"));
else if (type == mapnik::Boolean)
fld_types.append(boost::python::str("bool"));
else if (type == mapnik::Geometry)
fld_types.append(boost::python::str("geometry"));
else if (type == mapnik::Object)
fld_types.append(boost::python::str("object"));
else
fld_types.append(boost::python::str("unknown"));
}
}
return fld_types;
}}
mapnik::parameters const& (mapnik::datasource::*params_const)() const = &mapnik::datasource::params;
void export_datasource()
{
using namespace boost::python;
enum_<mapnik::datasource::datasource_t>("DataType")
.value("Vector",mapnik::datasource::Vector)
.value("Raster",mapnik::datasource::Raster)
;
enum_<mapnik::datasource::geometry_t>("DataGeometryType")
.value("Point",mapnik::datasource::Point)
.value("LineString",mapnik::datasource::LineString)
.value("Polygon",mapnik::datasource::Polygon)
.value("Collection",mapnik::datasource::Collection)
;
class_<datasource,std::shared_ptr<datasource>,
boost::noncopyable>("Datasource",no_init)
.def("type",&datasource::type)
.def("geometry_type",&datasource::get_geometry_type)
.def("describe",&describe)
.def("envelope",&datasource::envelope)
.def("features",&datasource::features)
.def("fields",&fields)
.def("field_types",&field_types)
.def("features_at_point",&datasource::features_at_point, (arg("coord"),arg("tolerance")=0))
.def("params",make_function(params_const,return_value_policy<copy_const_reference>()),
"The configuration parameters of the data source. "
"These vary depending on the type of data source.")
;
def("CreateDatasource",&create_datasource);
class_<memory_datasource,
bases<datasource>, std::shared_ptr<memory_datasource>,
boost::noncopyable>("MemoryDatasource", init<>())
.def("add_feature",&memory_datasource::push,
"Adds a Feature:\n"
">>> ms = MemoryDatasource()\n"
">>> feature = Feature(1)\n"
">>> ms.add_feature(Feature(1))\n")
.def("num_features",&memory_datasource::size)
;
implicitly_convertible<std::shared_ptr<memory_datasource>,std::shared_ptr<datasource> >();
}
<commit_msg>+ add get_pointer impl for std::shared_ptr<T> when building agaist boost version < 1.53<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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
*
*****************************************************************************/
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/noncopyable.hpp>
// stl
#include <sstream>
#include <vector>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/query.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/memory_datasource.hpp>
using mapnik::datasource;
using mapnik::memory_datasource;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
#if BOOST_VERSION < 105300
namespace boost
{
template<class T> T * get_pointer( std::shared_ptr<T> const& p )
{
return p.get();
}
}
#endif
namespace
{
//user-friendly wrapper that uses Python dictionary
using namespace boost::python;
std::shared_ptr<mapnik::datasource> create_datasource(dict const& d)
{
mapnik::parameters params;
boost::python::list keys=d.keys();
for (int i=0; i < len(keys); ++i)
{
std::string key = extract<std::string>(keys[i]);
object obj = d[key];
if (PyUnicode_Check(obj.ptr()))
{
PyObject* temp = PyUnicode_AsUTF8String(obj.ptr());
if (temp)
{
#if PY_VERSION_HEX >= 0x03000000
char* c_str = PyBytes_AsString(temp);
#else
char* c_str = PyString_AsString(temp);
#endif
params[key] = std::string(c_str);
Py_DecRef(temp);
}
continue;
}
extract<std::string> ex0(obj);
extract<mapnik::value_integer> ex1(obj);
extract<double> ex2(obj);
if (ex0.check())
{
params[key] = ex0();
}
else if (ex1.check())
{
params[key] = ex1();
}
else if (ex2.check())
{
params[key] = ex2();
}
}
return mapnik::datasource_cache::instance().create(params);
}
boost::python::dict describe(std::shared_ptr<mapnik::datasource> const& ds)
{
boost::python::dict description;
mapnik::layer_descriptor ld = ds->get_descriptor();
description["type"] = ds->type();
description["name"] = ld.get_name();
description["geometry_type"] = ds->get_geometry_type();
description["encoding"] = ld.get_encoding();
return description;
}
boost::python::list fields(std::shared_ptr<mapnik::datasource> const& ds)
{
boost::python::list flds;
if (ds)
{
layer_descriptor ld = ds->get_descriptor();
std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors();
std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_ar.end();
for (; it != end; ++it)
{
flds.append(it->get_name());
}
}
return flds;
}
boost::python::list field_types(std::shared_ptr<mapnik::datasource> const& ds)
{
boost::python::list fld_types;
if (ds)
{
layer_descriptor ld = ds->get_descriptor();
std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors();
std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_ar.end();
for (; it != end; ++it)
{
unsigned type = it->get_type();
if (type == mapnik::Integer)
// this crashes, so send back strings instead
//fld_types.append(boost::python::object(boost::python::handle<>(&PyInt_Type)));
fld_types.append(boost::python::str("int"));
else if (type == mapnik::Float)
fld_types.append(boost::python::str("float"));
else if (type == mapnik::Double)
fld_types.append(boost::python::str("float"));
else if (type == mapnik::String)
fld_types.append(boost::python::str("str"));
else if (type == mapnik::Boolean)
fld_types.append(boost::python::str("bool"));
else if (type == mapnik::Geometry)
fld_types.append(boost::python::str("geometry"));
else if (type == mapnik::Object)
fld_types.append(boost::python::str("object"));
else
fld_types.append(boost::python::str("unknown"));
}
}
return fld_types;
}}
mapnik::parameters const& (mapnik::datasource::*params_const)() const = &mapnik::datasource::params;
void export_datasource()
{
using namespace boost::python;
enum_<mapnik::datasource::datasource_t>("DataType")
.value("Vector",mapnik::datasource::Vector)
.value("Raster",mapnik::datasource::Raster)
;
enum_<mapnik::datasource::geometry_t>("DataGeometryType")
.value("Point",mapnik::datasource::Point)
.value("LineString",mapnik::datasource::LineString)
.value("Polygon",mapnik::datasource::Polygon)
.value("Collection",mapnik::datasource::Collection)
;
class_<datasource,std::shared_ptr<datasource>,
boost::noncopyable>("Datasource",no_init)
.def("type",&datasource::type)
.def("geometry_type",&datasource::get_geometry_type)
.def("describe",&describe)
.def("envelope",&datasource::envelope)
.def("features",&datasource::features)
.def("fields",&fields)
.def("field_types",&field_types)
.def("features_at_point",&datasource::features_at_point, (arg("coord"),arg("tolerance")=0))
.def("params",make_function(params_const,return_value_policy<copy_const_reference>()),
"The configuration parameters of the data source. "
"These vary depending on the type of data source.")
;
def("CreateDatasource",&create_datasource);
class_<memory_datasource,
bases<datasource>, std::shared_ptr<memory_datasource>,
boost::noncopyable>("MemoryDatasource", init<>())
.def("add_feature",&memory_datasource::push,
"Adds a Feature:\n"
">>> ms = MemoryDatasource()\n"
">>> feature = Feature(1)\n"
">>> ms.add_feature(Feature(1))\n")
.def("num_features",&memory_datasource::size)
;
implicitly_convertible<std::shared_ptr<memory_datasource>,std::shared_ptr<datasource> >();
}
<|endoftext|> |
<commit_before>#ifndef CONTEXT_HPP_
#define CONTEXT_HPP_
#include <string>
#include <atomic>
#include <memory>
#include <thread>
#include <cstdio>
std::string runCommand(std::string command) {
std::FILE* pipe = popen(command.c_str(), "r");
if(!pipe) return "";
char buffer[128];
std::string result;
while(!std::feof(pipe)) {
std::fgets(buffer, sizeof(buffer), pipe);
result += buffer;
}
pclose(pipe);
return result;
}
class Context: std::enable_shared_from_this<Context> {
std::atomic_bool isRunning;
std::string cwd;
std::atomic<std::shared_ptr<std::string>> currentResult;
public:
Context() {
isRunning.store(false);
currentResult.store(std::make_shared<std::string>(""));
}
void setCwd(std::string c) { cwd = std::move(c); }
const std::string& getCwd() const { return cwd; }
void run() {
isRunning = true;
std::thread t(
[&](){
currentResult.store(std::make_shared<std::string>(runCommand("ls -la")));
}
);
}
void stop() {
isRunning = false;
}
std::string getResult() const {
return *currentResult.load();
}
};
#endif /* CONTEXT_HPP_ */
<commit_msg>Add atomic_wrapper<commit_after>#ifndef CONTEXT_HPP_
#define CONTEXT_HPP_
#include <string>
#include <atomic>
#include <memory>
#include <thread>
#include <cstdio>
#include <mutex>
template<typename T>
class AtomicWrapper {
mutable std::mutex lock;
T value;
public:
template<typename U>
AtomicWrapper(U&& u) : lock() {
std::lock_guard<decltype(lock)>(lock);
value = T(u);
}
template<typename U>
AtomicWrapper& operator=(U&& newValue) {
std::lock_guard<decltype(lock)>(lock);
value = std::forward<U>(newValue);
}
operator T() const {
std::lock_guard<decltype(lock)>(lock);
T ret = value;
return ret;
}
};
std::string runCommand(std::string command) {
std::FILE* pipe = popen(command.c_str(), "r");
if(!pipe) return "";
char buffer[128];
std::string result;
while(!std::feof(pipe)) {
std::fgets(buffer, sizeof(buffer), pipe);
result += buffer;
}
pclose(pipe);
return result;
}
class Context: std::enable_shared_from_this<Context> {
std::atomic_bool isRunning;
std::string cwd;
std::atomic<std::shared_ptr<std::string>> currentResult;
public:
Context() {
isRunning.store(false);
currentResult.store(std::make_shared<std::string>(""));
}
void setCwd(std::string c) { cwd = std::move(c); }
const std::string& getCwd() const { return cwd; }
void run() {
isRunning = true;
std::thread t(
[&](){
currentResult.store(std::make_shared<std::string>(runCommand("ls -la")));
}
);
}
void stop() {
isRunning = false;
}
std::string getResult() const {
return *currentResult.load();
}
};
#endif /* CONTEXT_HPP_ */
<|endoftext|> |
<commit_before>#include "STBText.h"
#include "PrimitiveMode.h"
#include <string>
#include "image/TextureLoader.h"
#include "render/TextureManager.h"
#include "platform/Log.h"
#include "image/ColorType.h"
#include "FileData.h"
#include <codecvt>
using namespace Supernova;
STBText::STBText() {
atlasWidth = 0;
atlasHeight = 0;
lineHeight = 0;
}
STBText::~STBText() {
}
void STBText::tryFindBitmapSize(const stbtt_fontinfo *info, float scale){
atlasWidth = 512;
atlasHeight = 512;
int x0; int y0; int x1; int y1;
stbtt_GetFontBoundingBox(info, &x0, &y0, &x1, &y1);
int gfh = (y1-y0) * scale;
bool fitBitmap = false;
while (!fitBitmap && atlasWidth <= atlasLimit){
int xOffset = 0;
int yOffset = 0;
for (int i = firstChar; (i < lastChar && yOffset <= atlasHeight && xOffset <= atlasWidth); i++){
stbtt_GetCodepointBox(info, i, &x0, &y0, &x1, &y1);
int gw = (x1-x0) * scale;
xOffset += gw+1;
if (xOffset > atlasWidth){
xOffset = 0;
yOffset += gfh;
}
}
if (yOffset > atlasHeight || xOffset > atlasWidth){
atlasWidth = 2 * atlasWidth;
atlasHeight = 2 * atlasHeight;
}else {
fitBitmap = true;
}
}
}
bool STBText::load(const char* font, unsigned int fontSize){
FileData* fontData = new FileData();
fontData->open(font);
stbtt_fontinfo info;
if (!stbtt_InitFont(&info, fontData->getMemPtr(), 0)) {
Log::Error(LOG_TAG, "Failed to initialize font");
return false;
}
float scale = stbtt_ScaleForPixelHeight(&info, fontSize);
int ascent, descent, lineGap;
stbtt_GetFontVMetrics(&info, &ascent, &descent, &lineGap);
lineHeight = (ascent - descent + lineGap) * scale;
tryFindBitmapSize(&info, scale);
unsigned char *atlasData = NULL;
charInfo = new stbtt_packedchar[charCount];
stbtt_pack_context context;
bool fitBitmap = false;
while (!fitBitmap && atlasWidth <= atlasLimit) {
if (atlasData) delete[] atlasData;
atlasData = new unsigned char[atlasWidth * atlasHeight];
if (!stbtt_PackBegin(&context, atlasData, atlasWidth, atlasHeight, 0, 1, nullptr)){
Log::Error(LOG_TAG, "Failed to initialize font");
return false;
}
//stbtt_PackSetOversampling(&context, oversampleX, oversampleY);
if (!stbtt_PackFontRange(&context, fontData->getMemPtr(), 0, fontSize, firstChar, charCount, charInfo)){
atlasWidth = atlasWidth * 2;
atlasHeight = atlasHeight * 2;
}else{
fitBitmap = true;
}
}
if (atlasWidth > atlasLimit){
Log::Error(LOG_TAG, "Failed to pack font");
return false;
}
stbtt_PackEnd(&context);
unsigned int textureSize = atlasWidth * atlasHeight * sizeof(unsigned char);
TextureFile* textureFile = new TextureFile(atlasWidth, atlasHeight, textureSize, S_COLOR_ALPHA, 8, (void*)atlasData);
TextureManager::loadTexture(textureFile, font + std::to_string('-') + std::to_string(fontSize));
delete[] atlasData;
delete fontData;
return true;
}
void STBText::createText(std::string text, std::vector<Vector3>* vertices, std::vector<Vector3>* normals, std::vector<Vector2>* texcoords, std::vector<unsigned int>* indices, int* width, int* height, bool invert){
std::wstring_convert< std::codecvt_utf8_utf16<wchar_t> > convert;
std::wstring utf16String = convert.from_bytes( text );
(*width) = 0;
(*height) = 0;
float offsetX = 0;
float offsetY = 0;
int ind = 0;
for(auto c : utf16String) {
int intchar = uint_least32_t(c);
if (intchar >= firstChar && intchar <= lastChar) {
stbtt_aligned_quad quad;
stbtt_GetPackedQuad(charInfo, atlasWidth, atlasHeight, intchar - firstChar, &offsetX, &offsetY, &quad, 1);
if (invert) {
float auxt0 = quad.t0;
quad.t0 = quad.t1;
quad.t1 = auxt0;
float auxy0 = quad.y0;
quad.y0 = -quad.y1;
quad.y1 = -auxy0;
}
vertices->push_back(Vector3(quad.x0, quad.y0, 0));
vertices->push_back(Vector3(quad.x1, quad.y0, 0));
vertices->push_back(Vector3(quad.x1, quad.y1, 0));
vertices->push_back(Vector3(quad.x0, quad.y1, 0));
texcoords->push_back(Vector2(quad.s0, quad.t0));
texcoords->push_back(Vector2(quad.s1, quad.t0));
texcoords->push_back(Vector2(quad.s1, quad.t1));
texcoords->push_back(Vector2(quad.s0, quad.t1));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
indices->push_back(ind);
indices->push_back(ind+1);
indices->push_back(ind+2);
indices->push_back(ind);
indices->push_back(ind+2);
indices->push_back(ind+3);
ind = ind + 4;
if ((*height) < (quad.y1 - quad.y0)){
(*height) = (quad.y1 - quad.y0);
}
}
}
(*width) = offsetX;
}
<commit_msg>Testing with multiline text<commit_after>#include "STBText.h"
#include "PrimitiveMode.h"
#include <string>
#include "image/TextureLoader.h"
#include "render/TextureManager.h"
#include "platform/Log.h"
#include "image/ColorType.h"
#include "FileData.h"
#include <codecvt>
using namespace Supernova;
STBText::STBText() {
atlasWidth = 0;
atlasHeight = 0;
lineHeight = 0;
}
STBText::~STBText() {
}
void STBText::tryFindBitmapSize(const stbtt_fontinfo *info, float scale){
atlasWidth = 512;
atlasHeight = 512;
int x0; int y0; int x1; int y1;
stbtt_GetFontBoundingBox(info, &x0, &y0, &x1, &y1);
int gfh = (y1-y0) * scale;
bool fitBitmap = false;
while (!fitBitmap && atlasWidth <= atlasLimit){
int xOffset = 0;
int yOffset = 0;
for (int i = firstChar; (i < lastChar && yOffset <= atlasHeight && xOffset <= atlasWidth); i++){
stbtt_GetCodepointBox(info, i, &x0, &y0, &x1, &y1);
int gw = (x1-x0) * scale;
xOffset += gw+1;
if (xOffset > atlasWidth){
xOffset = 0;
yOffset += gfh;
}
}
if (yOffset > atlasHeight || xOffset > atlasWidth){
atlasWidth = 2 * atlasWidth;
atlasHeight = 2 * atlasHeight;
}else {
fitBitmap = true;
}
}
}
bool STBText::load(const char* font, unsigned int fontSize){
FileData* fontData = new FileData();
fontData->open(font);
stbtt_fontinfo info;
if (!stbtt_InitFont(&info, fontData->getMemPtr(), 0)) {
Log::Error(LOG_TAG, "Failed to initialize font");
return false;
}
float scale = stbtt_ScaleForPixelHeight(&info, fontSize);
int ascent, descent, lineGap;
stbtt_GetFontVMetrics(&info, &ascent, &descent, &lineGap);
lineHeight = (ascent - descent + lineGap) * scale;
tryFindBitmapSize(&info, scale);
unsigned char *atlasData = NULL;
charInfo = new stbtt_packedchar[charCount];
stbtt_pack_context context;
bool fitBitmap = false;
while (!fitBitmap && atlasWidth <= atlasLimit) {
if (atlasData) delete[] atlasData;
atlasData = new unsigned char[atlasWidth * atlasHeight];
if (!stbtt_PackBegin(&context, atlasData, atlasWidth, atlasHeight, 0, 1, nullptr)){
Log::Error(LOG_TAG, "Failed to initialize font");
return false;
}
//stbtt_PackSetOversampling(&context, oversampleX, oversampleY);
if (!stbtt_PackFontRange(&context, fontData->getMemPtr(), 0, fontSize, firstChar, charCount, charInfo)){
atlasWidth = atlasWidth * 2;
atlasHeight = atlasHeight * 2;
}else{
fitBitmap = true;
}
}
if (atlasWidth > atlasLimit){
Log::Error(LOG_TAG, "Failed to pack font");
return false;
}
stbtt_PackEnd(&context);
unsigned int textureSize = atlasWidth * atlasHeight * sizeof(unsigned char);
TextureFile* textureFile = new TextureFile(atlasWidth, atlasHeight, textureSize, S_COLOR_ALPHA, 8, (void*)atlasData);
TextureManager::loadTexture(textureFile, font + std::to_string('-') + std::to_string(fontSize));
delete[] atlasData;
delete fontData;
return true;
}
void STBText::createText(std::string text, std::vector<Vector3>* vertices, std::vector<Vector3>* normals, std::vector<Vector2>* texcoords, std::vector<unsigned int>* indices, int* width, int* height, bool invert){
std::wstring_convert< std::codecvt_utf8_utf16<wchar_t> > convert;
std::wstring utf16String = convert.from_bytes( text );
(*width) = 130;
(*height) = 0;
float offsetX = 0;
float offsetY = 0;
if (*width > 0){
int lastSpace = 0;
for (int i = 0; i < utf16String.size(); i++){
int intchar = uint_least32_t(utf16String[i]);
if (intchar == 32){ //space
lastSpace = i;
}
if (intchar == 10){ //\n
offsetY += lineHeight;
offsetX = 0;
}
if (intchar >= firstChar && intchar <= lastChar) {
stbtt_aligned_quad quad;
stbtt_GetPackedQuad(charInfo, atlasWidth, atlasHeight, intchar - firstChar, &offsetX, &offsetY, &quad, 1);
if (offsetX > (*width)){
if (lastSpace > 0){
utf16String[lastSpace] = '\n';
i = lastSpace;
lastSpace = 0;
offsetX = 0;
}else{
utf16String.insert(i, { '\n' });
offsetX = 0;
}
}
}
}
}
offsetX = 0;
offsetY = 0;
int minX0 = 0, maxX1 = 0, minY0 = 0, maxY1 = 0;
int ind = 0;
for (int i = 0; i < utf16String.size(); i++){
int intchar = uint_least32_t(utf16String[i]);
if (intchar == 32){ //space
lastSpace = i;
}
if (intchar == 10){ //\n
offsetY += lineHeight;
offsetX = 0;
}
if (intchar >= firstChar && intchar <= lastChar) {
stbtt_aligned_quad quad;
stbtt_GetPackedQuad(charInfo, atlasWidth, atlasHeight, intchar - firstChar, &offsetX, &offsetY, &quad, 1);
if (invert) {
float auxt0 = quad.t0;
quad.t0 = quad.t1;
quad.t1 = auxt0;
float auxy0 = quad.y0;
quad.y0 = -quad.y1;
quad.y1 = -auxy0;
}
if (quad.x0 < minX0)
minX0 = quad.x0;
if (quad.y0 < minY0)
minY0 = quad.y0;
if (quad.x1 > maxX1)
maxX1 = quad.x1;
if (quad.y1 > maxY1)
maxY1 = quad.y1;
if ((*width == 0 || offsetX <= *width) && (*height == 0 || offsetY <= *height)){
vertices->push_back(Vector3(quad.x0, quad.y0, 0));
vertices->push_back(Vector3(quad.x1, quad.y0, 0));
vertices->push_back(Vector3(quad.x1, quad.y1, 0));
vertices->push_back(Vector3(quad.x0, quad.y1, 0));
texcoords->push_back(Vector2(quad.s0, quad.t0));
texcoords->push_back(Vector2(quad.s1, quad.t0));
texcoords->push_back(Vector2(quad.s1, quad.t1));
texcoords->push_back(Vector2(quad.s0, quad.t1));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
normals->push_back(Vector3(0.0f, 0.0f, 1.0f));
indices->push_back(ind);
indices->push_back(ind+1);
indices->push_back(ind+2);
indices->push_back(ind);
indices->push_back(ind+2);
indices->push_back(ind+3);
ind = ind + 4;
}
//if (*width > 0 && offsetX > *width){
// offsetY += lineHeight;
// offsetX = 0;
// i--;
//}
}
}
if (*width == 0)
(*width) = maxX1 - minX0;
if (*height == 0)
(*height) = maxY1 - minY0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtTest/QSignalSpy>
#include <QtQml/qqmlcomponent.h>
#include <QtQml/qqmlcontext.h>
#include <QtQuick/qquickview.h>
#include <QtQuick/qquickitem.h>
#include "../../shared/util.h"
#include <QtGui/QWindow>
#include <QtCore/QDebug>
#include <QtQml/qqmlengine.h>
class tst_QQuickView : public QQmlDataTest
{
Q_OBJECT
public:
tst_QQuickView();
private slots:
void resizemodeitem();
void errors();
void engine();
};
tst_QQuickView::tst_QQuickView()
{
}
void tst_QQuickView::resizemodeitem()
{
QWindow window;
window.setGeometry(0, 0, 400, 400);
QQuickView *view = new QQuickView(&window);
QVERIFY(view);
view->setResizeMode(QQuickView::SizeRootObjectToView);
QCOMPARE(QSize(0,0), view->initialSize());
view->setSource(testFileUrl("resizemodeitem.qml"));
QQuickItem* item = qobject_cast<QQuickItem*>(view->rootObject());
QVERIFY(item);
window.show();
view->show();
// initial size from root object
QCOMPARE(item->width(), 200.0);
QCOMPARE(item->height(), 200.0);
QCOMPARE(view->size(), QSize(200, 200));
QCOMPARE(view->size(), view->sizeHint());
QCOMPARE(view->size(), view->initialSize());
// size update from view
view->resize(QSize(80,100));
QTRY_COMPARE(item->width(), 80.0);
QCOMPARE(item->height(), 100.0);
QCOMPARE(view->size(), QSize(80, 100));
QCOMPARE(view->size(), view->sizeHint());
view->setResizeMode(QQuickView::SizeViewToRootObject);
// size update from view disabled
view->resize(QSize(60,80));
QCOMPARE(item->width(), 80.0);
QCOMPARE(item->height(), 100.0);
QTest::qWait(50);
QCOMPARE(view->size(), QSize(60, 80));
// size update from root object
item->setWidth(250);
item->setHeight(350);
QCOMPARE(item->width(), 250.0);
QCOMPARE(item->height(), 350.0);
QTRY_COMPARE(view->size(), QSize(250, 350));
QCOMPARE(view->size(), QSize(250, 350));
QCOMPARE(view->size(), view->sizeHint());
// reset window
window.hide();
delete view;
view = new QQuickView(&window);
QVERIFY(view);
view->setResizeMode(QQuickView::SizeViewToRootObject);
view->setSource(testFileUrl("resizemodeitem.qml"));
item = qobject_cast<QQuickItem*>(view->rootObject());
QVERIFY(item);
window.show();
view->show();
// initial size for root object
QCOMPARE(item->width(), 200.0);
QCOMPARE(item->height(), 200.0);
QCOMPARE(view->size(), view->sizeHint());
QCOMPARE(view->size(), view->initialSize());
// size update from root object
item->setWidth(80);
item->setHeight(100);
QCOMPARE(item->width(), 80.0);
QCOMPARE(item->height(), 100.0);
QTRY_COMPARE(view->size(), QSize(80, 100));
QCOMPARE(view->size(), QSize(80, 100));
QCOMPARE(view->size(), view->sizeHint());
// size update from root object disabled
view->setResizeMode(QQuickView::SizeRootObjectToView);
item->setWidth(60);
item->setHeight(80);
QCOMPARE(view->width(), 80);
QCOMPARE(view->height(), 100);
QCOMPARE(QSize(item->width(), item->height()), view->sizeHint());
// size update from view
view->resize(QSize(200,300));
QTRY_COMPARE(item->width(), 200.0);
QCOMPARE(item->height(), 300.0);
QCOMPARE(view->size(), QSize(200, 300));
QCOMPARE(view->size(), view->sizeHint());
window.hide();
delete view;
// if we set a specific size for the view then it should keep that size
// for SizeRootObjectToView mode.
view = new QQuickView(&window);
view->resize(300, 300);
view->setResizeMode(QQuickView::SizeRootObjectToView);
QCOMPARE(QSize(0,0), view->initialSize());
view->setSource(testFileUrl("resizemodeitem.qml"));
view->resize(300, 300);
item = qobject_cast<QQuickItem*>(view->rootObject());
QVERIFY(item);
window.show();
view->show();
QTest::qWait(50);
// initial size from root object
QCOMPARE(item->width(), 300.0);
QCOMPARE(item->height(), 300.0);
QCOMPARE(view->size(), QSize(300, 300));
QCOMPARE(view->size(), view->sizeHint());
QCOMPARE(view->initialSize(), QSize(200, 200)); // initial object size
delete view;
}
static void silentErrorsMsgHandler(QtMsgType, const QMessageLogContext &, const QString &)
{
}
void tst_QQuickView::errors()
{
QQuickView *view = new QQuickView;
QVERIFY(view);
QQmlTestMessageHandler messageHandler;
view->setSource(testFileUrl("error1.qml"));
QVERIFY(view->status() == QQuickView::Error);
QVERIFY(view->errors().count() == 1);
delete view;
}
void tst_QQuickView::engine()
{
QQmlEngine *engine = new QQmlEngine;
QVERIFY(!engine->incubationController());
QQuickView *view = new QQuickView(engine, 0);
QVERIFY(view);
QVERIFY(engine->incubationController() == view->incubationController());
QQuickView *view2 = new QQuickView(engine, 0);
QVERIFY(view);
QVERIFY(engine->incubationController() == view->incubationController());
delete view;
QVERIFY(!engine->incubationController());
engine->setIncubationController(view2->incubationController());
QVERIFY(engine->incubationController() == view2->incubationController());
delete view2;
QVERIFY(!engine->incubationController());
QQuickView *view3 = new QQuickView;
QQuickView *view4 = new QQuickView(view3->engine(), 0);
QVERIFY(view3->engine());
QVERIFY(view4->engine());
QCOMPARE(view3->engine(), view4->engine());
delete view3;
QVERIFY(!view4->engine());
QTest::ignoreMessage(QtWarningMsg, "QQuickView: invalid qml engine. ");
view4->setSource(QUrl());
QCOMPARE(view4->status(), QQuickView::Error);
QVERIFY(!view4->errors().isEmpty());
QCOMPARE(view4->errors().back().description(), QLatin1String("QQuickView: invalid qml engine."));
delete view4;
}
QTEST_MAIN(tst_QQuickView)
#include "tst_qquickview.moc"
<commit_msg>Fix tst_qquickview for full screen platforms<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtTest/QSignalSpy>
#include <QtQml/qqmlcomponent.h>
#include <QtQml/qqmlcontext.h>
#include <QtQuick/qquickview.h>
#include <QtQuick/qquickitem.h>
#include "../../shared/util.h"
#include <QtGui/QWindow>
#include <QtCore/QDebug>
#include <QtQml/qqmlengine.h>
class tst_QQuickView : public QQmlDataTest
{
Q_OBJECT
public:
tst_QQuickView();
private slots:
void resizemodeitem();
void errors();
void engine();
};
tst_QQuickView::tst_QQuickView()
{
}
void tst_QQuickView::resizemodeitem()
{
QWindow window;
window.setGeometry(0, 0, 400, 400);
QQuickView *view = new QQuickView(&window);
QVERIFY(view);
view->setResizeMode(QQuickView::SizeRootObjectToView);
QCOMPARE(QSize(0,0), view->initialSize());
view->setSource(testFileUrl("resizemodeitem.qml"));
QQuickItem* item = qobject_cast<QQuickItem*>(view->rootObject());
QVERIFY(item);
window.show();
view->showNormal();
// initial size from root object
QCOMPARE(item->width(), 200.0);
QCOMPARE(item->height(), 200.0);
QCOMPARE(view->size(), QSize(200, 200));
QCOMPARE(view->size(), view->sizeHint());
QCOMPARE(view->size(), view->initialSize());
// size update from view
view->resize(QSize(80,100));
QTRY_COMPARE(item->width(), 80.0);
QCOMPARE(item->height(), 100.0);
QCOMPARE(view->size(), QSize(80, 100));
QCOMPARE(view->size(), view->sizeHint());
view->setResizeMode(QQuickView::SizeViewToRootObject);
// size update from view disabled
view->resize(QSize(60,80));
QCOMPARE(item->width(), 80.0);
QCOMPARE(item->height(), 100.0);
QTest::qWait(50);
QCOMPARE(view->size(), QSize(60, 80));
// size update from root object
item->setWidth(250);
item->setHeight(350);
QCOMPARE(item->width(), 250.0);
QCOMPARE(item->height(), 350.0);
QTRY_COMPARE(view->size(), QSize(250, 350));
QCOMPARE(view->size(), QSize(250, 350));
QCOMPARE(view->size(), view->sizeHint());
// reset window
window.hide();
delete view;
view = new QQuickView(&window);
QVERIFY(view);
view->setResizeMode(QQuickView::SizeViewToRootObject);
view->setSource(testFileUrl("resizemodeitem.qml"));
item = qobject_cast<QQuickItem*>(view->rootObject());
QVERIFY(item);
window.show();
view->showNormal();
// initial size for root object
QCOMPARE(item->width(), 200.0);
QCOMPARE(item->height(), 200.0);
QCOMPARE(view->size(), view->sizeHint());
QCOMPARE(view->size(), view->initialSize());
// size update from root object
item->setWidth(80);
item->setHeight(100);
QCOMPARE(item->width(), 80.0);
QCOMPARE(item->height(), 100.0);
QTRY_COMPARE(view->size(), QSize(80, 100));
QCOMPARE(view->size(), QSize(80, 100));
QCOMPARE(view->size(), view->sizeHint());
// size update from root object disabled
view->setResizeMode(QQuickView::SizeRootObjectToView);
item->setWidth(60);
item->setHeight(80);
QCOMPARE(view->width(), 80);
QCOMPARE(view->height(), 100);
QCOMPARE(QSize(item->width(), item->height()), view->sizeHint());
// size update from view
view->resize(QSize(200,300));
QTRY_COMPARE(item->width(), 200.0);
QCOMPARE(item->height(), 300.0);
QCOMPARE(view->size(), QSize(200, 300));
QCOMPARE(view->size(), view->sizeHint());
window.hide();
delete view;
// if we set a specific size for the view then it should keep that size
// for SizeRootObjectToView mode.
view = new QQuickView(&window);
view->resize(300, 300);
view->setResizeMode(QQuickView::SizeRootObjectToView);
QCOMPARE(QSize(0,0), view->initialSize());
view->setSource(testFileUrl("resizemodeitem.qml"));
view->resize(300, 300);
item = qobject_cast<QQuickItem*>(view->rootObject());
QVERIFY(item);
window.show();
view->showNormal();
QTest::qWait(50);
// initial size from root object
QCOMPARE(item->width(), 300.0);
QCOMPARE(item->height(), 300.0);
QCOMPARE(view->size(), QSize(300, 300));
QCOMPARE(view->size(), view->sizeHint());
QCOMPARE(view->initialSize(), QSize(200, 200)); // initial object size
delete view;
}
static void silentErrorsMsgHandler(QtMsgType, const QMessageLogContext &, const QString &)
{
}
void tst_QQuickView::errors()
{
QQuickView *view = new QQuickView;
QVERIFY(view);
QQmlTestMessageHandler messageHandler;
view->setSource(testFileUrl("error1.qml"));
QVERIFY(view->status() == QQuickView::Error);
QVERIFY(view->errors().count() == 1);
delete view;
}
void tst_QQuickView::engine()
{
QQmlEngine *engine = new QQmlEngine;
QVERIFY(!engine->incubationController());
QQuickView *view = new QQuickView(engine, 0);
QVERIFY(view);
QVERIFY(engine->incubationController() == view->incubationController());
QQuickView *view2 = new QQuickView(engine, 0);
QVERIFY(view);
QVERIFY(engine->incubationController() == view->incubationController());
delete view;
QVERIFY(!engine->incubationController());
engine->setIncubationController(view2->incubationController());
QVERIFY(engine->incubationController() == view2->incubationController());
delete view2;
QVERIFY(!engine->incubationController());
QQuickView *view3 = new QQuickView;
QQuickView *view4 = new QQuickView(view3->engine(), 0);
QVERIFY(view3->engine());
QVERIFY(view4->engine());
QCOMPARE(view3->engine(), view4->engine());
delete view3;
QVERIFY(!view4->engine());
QTest::ignoreMessage(QtWarningMsg, "QQuickView: invalid qml engine. ");
view4->setSource(QUrl());
QCOMPARE(view4->status(), QQuickView::Error);
QVERIFY(!view4->errors().isEmpty());
QCOMPARE(view4->errors().back().description(), QLatin1String("QQuickView: invalid qml engine."));
delete view4;
}
QTEST_MAIN(tst_QQuickView)
#include "tst_qquickview.moc"
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 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.
*/
#if !defined(XALANMAP_HEADER_GUARD_1357924680)
#define XALANMAP_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <cstddef>
#include <list>
#include <algorithm>
#include <functional>
#include <utility>
#include <xercesc/framework/MemoryManager.hpp>
#include <xalanc/Include/XalanVector.hpp>
XALAN_CPP_NAMESPACE_BEGIN
typedef size_t size_type;
template <class Key>
class XalanHash : public XALAN_STD_QUALIFIER unary_function<Key, size_type>
{
public:
size_type operator()(const Key& key) const
{
const char *byteArray = reinterpret_cast<const char*>(&key);
size_type result = 0;
for (size_type i = 0; i < sizeof(Key); ++i)
{
result = (result << 1) ^ byteArray[i];
}
return result;
}
};
template <class Key>
struct XalanHashMemberPointer
{
size_type operator() (const Key * key) const
{
assert (key != 0);
return key->hash();
}
};
template <class Key>
struct XalanHashMemberReference
{
size_type operator() (const Key& key) const
{
return key.hash();
}
};
template <
class Key,
class Value,
class Hash = XalanHash<Key>,
class Comparator = XALAN_STD_QUALIFIER equal_to<Key> >
class XalanMap
{
public:
typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager MemoryManagerType;
typedef Key key_type;
typedef Value data_type;
typedef size_t size_type;
typedef XALAN_STD_QUALIFIER pair<const key_type, data_type> value_type;
typedef XalanMap<Key, Value, Hash, Comparator> ThisType;
typedef size_t size_type;
struct Entry : public value_type
{
typedef value_type Parent;
size_type bucketIndex;
Entry(const key_type & key, const data_type& data, size_type index) :
value_type(key, data), bucketIndex(index)
{
}
Entry() :
value_type(key_type(),
data_type()),
bucketIndex(size_type())
{
}
};
typedef XALAN_STD_QUALIFIER list<Entry> EntryListType;
typedef typename EntryListType::iterator EntryListIterator;
typedef typename EntryListType::const_iterator EntryListConstIterator;
typedef XalanVector<typename EntryListType::iterator> EntryPosVectorType;
template<class ValueType, class Ref, class Ptr, class Iterator, class Map>
struct iterator_base
{
typedef ValueType value_type;
typedef Ref reference_type;
typedef Ptr pointer_type;
typedef ThisType MapType;
typedef iterator_base<value_type, reference_type, pointer_type, Iterator, Map> IteratorType;
typedef iterator_base<value_type, value_type&, value_type*, EntryListIterator, MapType> iterator;
iterator_base(
Map& map,
Iterator bucketPos) :
m_map(&map),
m_bucketPos(bucketPos)
{
}
iterator_base(const iterator& theRhs) :
m_map(theRhs.m_map),
m_bucketPos(theRhs.m_bucketPos)
{
}
const IteratorType & operator=(const IteratorType& theRhs)
{
m_map = theRhs.m_map;
m_bucketPos = theRhs.m_bucketPos;
return *this;
}
reference_type operator*() const
{
return *m_bucketPos;
}
int operator!=(const IteratorType& theRhs) const
{
return !operator==(theRhs);
}
int operator==(const IteratorType& theRhs) const
{
return (theRhs.m_map == m_map)
&& (theRhs.m_bucketPos == m_bucketPos);
}
IteratorType& operator++()
{
m_bucketPos++;
return *this;
}
Map* m_map;
Iterator m_bucketPos;
};
typedef iterator_base<
value_type,
value_type&,
value_type*,
EntryListIterator,
ThisType> iterator;
typedef iterator_base<
value_type,
const value_type&,
const value_type*,
EntryListConstIterator,
const ThisType> const_iterator;
XalanMap(
float loadFactor = 0.75,
MemoryManagerType* theMemoryManager = 0) :
m_memoryManager(theMemoryManager),
m_loadFactor(loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(10, m_entries.end(), m_memoryManager),
m_freeList()
{
}
XalanMap(const XalanMap &theRhs) :
m_memoryManager(theRhs.m_memoryManager),
m_loadFactor(theRhs.m_loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(size_type(m_loadFactor * theRhs.size())+ 1, m_entries.end(), m_memoryManager),
m_freeList()
{
const_iterator entry = theRhs.begin();
while(entry != theRhs.end())
{
insert(*entry);
++entry;
}
assert(m_size == theRhs.m_size);
}
~XalanMap()
{
}
XalanMap & operator=(const XalanMap& theRhs)
{
XalanMap theTemp(theRhs);
swap(theTemp);
return *this;
}
size_type size() const
{
return m_size;
}
bool empty() const {
return m_size == 0;
}
iterator begin()
{
return iterator(*this, m_entries.begin());
}
const_iterator begin() const
{
return const_iterator(*this, m_entries.begin());
}
iterator end()
{
return iterator(*this, m_entries.end());
}
const_iterator end() const
{
return const_iterator(*this, m_entries.end());
}
iterator find(const key_type& key)
{
size_type index = doHash(key);
EntryListIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
const_iterator find(const key_type& key) const
{
size_type index = doHash(key);
EntryListConstIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return const_iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
data_type & operator[](const key_type& key)
{
iterator pos = find(key);
if (pos == end())
{
pos = doCreateEntry(key, data_type());
}
return (*pos).second;
}
void insert(const value_type& value)
{
const key_type& key = value.first;
const data_type& data = value.second;
iterator pos = find(key);
if (pos == end())
{
doCreateEntry(key, data);
}
}
void erase(iterator pos)
{
if (pos != end())
{
doRemoveEntry(pos.m_bucketPos);
}
}
void erase(const key_type& key)
{
iterator pos = find(key);
erase(pos);
}
void clear()
{
m_size = 0;
XALAN_STD_QUALIFIER fill(
m_buckets.begin(),
m_buckets.end(),
m_entries.end());
m_freeList.splice(
m_freeList.begin(),
m_entries,
m_entries.begin(),
m_entries.end());
}
void swap(ThisType& theRhs)
{
size_type tempSize = m_size;
m_size = theRhs.m_size;
theRhs.m_size = tempSize;
MemoryManagerType* tempMemoryManager = m_memoryManager;
m_memoryManager = theRhs.m_memoryManager;
theRhs.m_memoryManager = tempMemoryManager;
m_entries.swap(theRhs.m_entries);
m_buckets.swap(theRhs.m_buckets);
m_freeList.swap(theRhs.m_freeList);
}
protected:
iterator doCreateEntry(const key_type & key, const data_type& data)
{
if (size_type(m_loadFactor * size()) > m_buckets.size())
{
rehash();
}
size_type index = doHash(key);
EntryListIterator & bucketStartPos = m_buckets[index];
if (m_freeList.empty() == true)
{
Entry newEntry = Entry(key, data, index);
if (bucketStartPos == m_entries.end())
{
bucketStartPos = m_entries.insert(m_entries.end(), newEntry);
}
else
{
bucketStartPos = m_entries.insert(bucketStartPos, newEntry);
}
}
else
{
(*m_freeList.begin()).~Entry();
new (&*m_freeList.begin()) Entry(key, data, index);
m_entries.splice(bucketStartPos, m_freeList, m_freeList.begin());
--bucketStartPos;
}
++m_size;
return iterator(*this, bucketStartPos);
}
void doRemoveEntry(const EntryListIterator & toRemoveIter)
{
size_type index = toRemoveIter->bucketIndex;
EntryListIterator nextPosition = ++(EntryListIterator(toRemoveIter));
if (m_buckets[index] == toRemoveIter)
{
if (nextPosition->bucketIndex == index)
{
m_buckets[index] = nextPosition;
}
else
{
m_buckets[index] = m_entries.end();
}
}
m_freeList.splice(m_freeList.begin(), m_entries, toRemoveIter, nextPosition);
--m_size;
}
size_type doHash(const Key & key) const
{
return m_hash(key) % m_buckets.size();
}
void rehash()
{
EntryPosVectorType temp(size_type(1.6 * size()), m_entries.end(), m_memoryManager);
m_buckets.swap(temp);
doRehashEntries();
}
void doRehashEntries()
{
EntryListType tempEntryList;
tempEntryList.splice(tempEntryList.begin(),m_entries, m_entries.begin(), m_entries.end());
while (tempEntryList.begin() != tempEntryList.end())
{
EntryListIterator entry = tempEntryList.begin();
entry->bucketIndex = doHash(entry->first);
EntryListIterator & bucketStartPos = m_buckets[entry->bucketIndex];
if (bucketStartPos == m_entries.end())
{
bucketStartPos = entry;
m_entries.splice(m_entries.begin(), tempEntryList, entry);
}
else
{
m_entries.splice(bucketStartPos, tempEntryList, entry);
--bucketStartPos;
}
}
}
// Data members...
Hash m_hash;
Comparator m_equals;
MemoryManagerType* m_memoryManager;
float m_loadFactor;
size_type m_size;
EntryListType m_entries;
EntryPosVectorType m_buckets;
EntryListType m_freeList;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANMAP_HEADER_GUARD_1357924680
<commit_msg>Remove redundant typedef to allow gcc compile<commit_after>/*
* Copyright 1999-2004 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.
*/
#if !defined(XALANMAP_HEADER_GUARD_1357924680)
#define XALANMAP_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <cstddef>
#include <list>
#include <algorithm>
#include <functional>
#include <utility>
#include <xercesc/framework/MemoryManager.hpp>
#include <xalanc/Include/XalanVector.hpp>
XALAN_CPP_NAMESPACE_BEGIN
typedef size_t size_type;
template <class Key>
class XalanHash : public XALAN_STD_QUALIFIER unary_function<Key, size_type>
{
public:
size_type operator()(const Key& key) const
{
const char *byteArray = reinterpret_cast<const char*>(&key);
size_type result = 0;
for (size_type i = 0; i < sizeof(Key); ++i)
{
result = (result << 1) ^ byteArray[i];
}
return result;
}
};
template <class Key>
struct XalanHashMemberPointer
{
size_type operator() (const Key * key) const
{
assert (key != 0);
return key->hash();
}
};
template <class Key>
struct XalanHashMemberReference
{
size_type operator() (const Key& key) const
{
return key.hash();
}
};
template <
class Key,
class Value,
class Hash = XalanHash<Key>,
class Comparator = XALAN_STD_QUALIFIER equal_to<Key> >
class XalanMap
{
public:
typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager MemoryManagerType;
typedef Key key_type;
typedef Value data_type;
typedef size_t size_type;
typedef XALAN_STD_QUALIFIER pair<const key_type, data_type> value_type;
typedef XalanMap<Key, Value, Hash, Comparator> ThisType;
struct Entry : public value_type
{
typedef value_type Parent;
size_type bucketIndex;
Entry(const key_type & key, const data_type& data, size_type index) :
value_type(key, data), bucketIndex(index)
{
}
Entry() :
value_type(key_type(),
data_type()),
bucketIndex(size_type())
{
}
};
typedef XALAN_STD_QUALIFIER list<Entry> EntryListType;
typedef typename EntryListType::iterator EntryListIterator;
typedef typename EntryListType::const_iterator EntryListConstIterator;
typedef XalanVector<typename EntryListType::iterator> EntryPosVectorType;
template<class ValueType, class Ref, class Ptr, class Iterator, class Map>
struct iterator_base
{
typedef ValueType value_type;
typedef Ref reference_type;
typedef Ptr pointer_type;
typedef ThisType MapType;
typedef iterator_base<value_type, reference_type, pointer_type, Iterator, Map> IteratorType;
typedef iterator_base<value_type, value_type&, value_type*, EntryListIterator, MapType> iterator;
iterator_base(
Map& map,
Iterator bucketPos) :
m_map(&map),
m_bucketPos(bucketPos)
{
}
iterator_base(const iterator& theRhs) :
m_map(theRhs.m_map),
m_bucketPos(theRhs.m_bucketPos)
{
}
const IteratorType & operator=(const IteratorType& theRhs)
{
m_map = theRhs.m_map;
m_bucketPos = theRhs.m_bucketPos;
return *this;
}
reference_type operator*() const
{
return *m_bucketPos;
}
int operator!=(const IteratorType& theRhs) const
{
return !operator==(theRhs);
}
int operator==(const IteratorType& theRhs) const
{
return (theRhs.m_map == m_map)
&& (theRhs.m_bucketPos == m_bucketPos);
}
IteratorType& operator++()
{
m_bucketPos++;
return *this;
}
Map* m_map;
Iterator m_bucketPos;
};
typedef iterator_base<
value_type,
value_type&,
value_type*,
EntryListIterator,
ThisType> iterator;
typedef iterator_base<
value_type,
const value_type&,
const value_type*,
EntryListConstIterator,
const ThisType> const_iterator;
XalanMap(
float loadFactor = 0.75,
MemoryManagerType* theMemoryManager = 0) :
m_memoryManager(theMemoryManager),
m_loadFactor(loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(10, m_entries.end(), m_memoryManager),
m_freeList()
{
}
XalanMap(const XalanMap &theRhs) :
m_memoryManager(theRhs.m_memoryManager),
m_loadFactor(theRhs.m_loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(size_type(m_loadFactor * theRhs.size())+ 1, m_entries.end(), m_memoryManager),
m_freeList()
{
const_iterator entry = theRhs.begin();
while(entry != theRhs.end())
{
insert(*entry);
++entry;
}
assert(m_size == theRhs.m_size);
}
~XalanMap()
{
}
XalanMap & operator=(const XalanMap& theRhs)
{
XalanMap theTemp(theRhs);
swap(theTemp);
return *this;
}
size_type size() const
{
return m_size;
}
bool empty() const {
return m_size == 0;
}
iterator begin()
{
return iterator(*this, m_entries.begin());
}
const_iterator begin() const
{
return const_iterator(*this, m_entries.begin());
}
iterator end()
{
return iterator(*this, m_entries.end());
}
const_iterator end() const
{
return const_iterator(*this, m_entries.end());
}
iterator find(const key_type& key)
{
size_type index = doHash(key);
EntryListIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
const_iterator find(const key_type& key) const
{
size_type index = doHash(key);
EntryListConstIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return const_iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
data_type & operator[](const key_type& key)
{
iterator pos = find(key);
if (pos == end())
{
pos = doCreateEntry(key, data_type());
}
return (*pos).second;
}
void insert(const value_type& value)
{
const key_type& key = value.first;
const data_type& data = value.second;
iterator pos = find(key);
if (pos == end())
{
doCreateEntry(key, data);
}
}
void erase(iterator pos)
{
if (pos != end())
{
doRemoveEntry(pos.m_bucketPos);
}
}
void erase(const key_type& key)
{
iterator pos = find(key);
erase(pos);
}
void clear()
{
m_size = 0;
XALAN_STD_QUALIFIER fill(
m_buckets.begin(),
m_buckets.end(),
m_entries.end());
m_freeList.splice(
m_freeList.begin(),
m_entries,
m_entries.begin(),
m_entries.end());
}
void swap(ThisType& theRhs)
{
size_type tempSize = m_size;
m_size = theRhs.m_size;
theRhs.m_size = tempSize;
MemoryManagerType* tempMemoryManager = m_memoryManager;
m_memoryManager = theRhs.m_memoryManager;
theRhs.m_memoryManager = tempMemoryManager;
m_entries.swap(theRhs.m_entries);
m_buckets.swap(theRhs.m_buckets);
m_freeList.swap(theRhs.m_freeList);
}
protected:
iterator doCreateEntry(const key_type & key, const data_type& data)
{
if (size_type(m_loadFactor * size()) > m_buckets.size())
{
rehash();
}
size_type index = doHash(key);
EntryListIterator & bucketStartPos = m_buckets[index];
if (m_freeList.empty() == true)
{
Entry newEntry = Entry(key, data, index);
if (bucketStartPos == m_entries.end())
{
bucketStartPos = m_entries.insert(m_entries.end(), newEntry);
}
else
{
bucketStartPos = m_entries.insert(bucketStartPos, newEntry);
}
}
else
{
(*m_freeList.begin()).~Entry();
new (&*m_freeList.begin()) Entry(key, data, index);
m_entries.splice(bucketStartPos, m_freeList, m_freeList.begin());
--bucketStartPos;
}
++m_size;
return iterator(*this, bucketStartPos);
}
void doRemoveEntry(const EntryListIterator & toRemoveIter)
{
size_type index = toRemoveIter->bucketIndex;
EntryListIterator nextPosition = ++(EntryListIterator(toRemoveIter));
if (m_buckets[index] == toRemoveIter)
{
if (nextPosition->bucketIndex == index)
{
m_buckets[index] = nextPosition;
}
else
{
m_buckets[index] = m_entries.end();
}
}
m_freeList.splice(m_freeList.begin(), m_entries, toRemoveIter, nextPosition);
--m_size;
}
size_type doHash(const Key & key) const
{
return m_hash(key) % m_buckets.size();
}
void rehash()
{
EntryPosVectorType temp(size_type(1.6 * size()), m_entries.end(), m_memoryManager);
m_buckets.swap(temp);
doRehashEntries();
}
void doRehashEntries()
{
EntryListType tempEntryList;
tempEntryList.splice(tempEntryList.begin(),m_entries, m_entries.begin(), m_entries.end());
while (tempEntryList.begin() != tempEntryList.end())
{
EntryListIterator entry = tempEntryList.begin();
entry->bucketIndex = doHash(entry->first);
EntryListIterator & bucketStartPos = m_buckets[entry->bucketIndex];
if (bucketStartPos == m_entries.end())
{
bucketStartPos = entry;
m_entries.splice(m_entries.begin(), tempEntryList, entry);
}
else
{
m_entries.splice(bucketStartPos, tempEntryList, entry);
--bucketStartPos;
}
}
}
// Data members...
Hash m_hash;
Comparator m_equals;
MemoryManagerType* m_memoryManager;
float m_loadFactor;
size_type m_size;
EntryListType m_entries;
EntryPosVectorType m_buckets;
EntryListType m_freeList;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANMAP_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.4 2002/11/04 15:17:00 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/10/15 18:11:02 knoaman
* [Bug 13489]: missing 'return' in Token.cpp
*
* Revision 1.2 2002/03/18 19:29:53 knoaman
* Change constant names to eliminate possible conflict with user defined ones.
*
* Revision 1.1.1.1 2002/02/01 22:22:31 peiyongz
* sane_include
*
* Revision 1.3 2001/05/11 13:26:50 tng
* Copyright update.
*
* Revision 1.2 2001/05/03 18:17:49 knoaman
* Some design changes:
* o Changed the TokenFactory from a single static instance, to a
* normal class. Each RegularExpression object will have its own
* instance of TokenFactory, and that instance will be passed to
* other classes that need to use a TokenFactory to create Token
* objects (with the exception of RangeTokenMap).
* o Added a new class RangeTokenMap to map a the different ranges
* in a given category to a specific RangeFactory object. In the old
* design RangeFactory had dual functionality (act as a Map, and as
* a factory for creating RangeToken(s)). The RangeTokenMap will
* have its own copy of the TokenFactory. There will be only one
* instance of the RangeTokenMap class, and that instance will be
* lazily deleted when XPlatformUtils::Terminate is called.
*
* Revision 1.1 2001/03/02 19:22:58 knoaman
* Schema: Regular expression handling part I
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/RangeToken.hpp>
#include <xercesc/util/regx/ModifierToken.hpp>
#include <xercesc/util/regx/RegularExpression.hpp>
#include <xercesc/util/regx/RegxUtil.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Static member data initialization
// ---------------------------------------------------------------------------
const XMLInt32 Token::UTF16_MAX = 0x10FFFF;
const unsigned short Token::FC_CONTINUE = 0;
const unsigned short Token::FC_TERMINAL = 1;
const unsigned short Token::FC_ANY = 2;
// ---------------------------------------------------------------------------
// Token: Constructors and Destructors
// ---------------------------------------------------------------------------
Token::Token(const unsigned short tokType) : fTokenType(tokType) {
}
Token::~Token() {
}
// ---------------------------------------------------------------------------
// Token: Getter mthods
// ---------------------------------------------------------------------------
int Token::getMinLength() const {
switch (fTokenType) {
case T_CONCAT:
{
int sum = 0;
unsigned int childSize = size();
for (unsigned int i=0; i<childSize; i++) {
sum += getChild(i)->getMinLength();
}
return sum;
}
case T_CONDITION:
case T_UNION:
{
unsigned int childSize = size();
if (childSize == 0) {
return 0;
}
int ret = getChild(0)->getMinLength();
for (unsigned int i=1; i < childSize; i++) {
int min = getChild(i)->getMinLength();
if (min < ret)
ret = min;
}
return ret;
}
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
if (getMin() >= 0)
return getMin() * getChild(0)->getMinLength();
return 0;
case T_EMPTY:
case T_ANCHOR:
return 0;
case T_DOT:
case T_CHAR:
case T_RANGE:
case T_NRANGE:
return 1;
case T_INDEPENDENT:
case T_PAREN:
case T_MODIFIERGROUP:
return getChild(0)->getMinLength();
case T_BACKREFERENCE:
return 0; // ***** - REVISIT
case T_STRING:
return XMLString::stringLen(getString());
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
return 0; // ***** - REVIST
// default:
// throw;
}
// We should not get here, but we have it to make some compilers happy
return -1;
}
int Token::getMaxLength() const {
switch (fTokenType) {
case T_CONCAT:
{
int sum = 0;
unsigned int childSize = size();
for (unsigned int i=0; i<childSize; i++) {
int val = getChild(i)->getMaxLength();
if (val < 0){
return -1;
}
sum += val;
}
return sum;
}
case T_CONDITION:
case T_UNION:
{
unsigned int childSize = size();
if (childSize == 0)
return 0;
int ret = getChild(0)->getMaxLength();
for (unsigned i = 1; ret > 0 && i < childSize; i++) {
int max = getChild(i)->getMaxLength();
if (max < 0) {
ret = -1;
break;
}
if (max > ret)
ret = max;
}
return ret;
}
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
if (getMax() >= 0) {
return getMax() * getChild(0)->getMaxLength();
}
return -1;
case T_EMPTY:
case T_ANCHOR:
return 0;
case T_CHAR:
return 1;
case T_DOT:
case T_RANGE:
case T_NRANGE:
return 2;
case T_INDEPENDENT:
case T_PAREN:
case T_MODIFIERGROUP:
return getChild(0)->getMaxLength();
case T_BACKREFERENCE:
return -1; // REVISIT
case T_STRING:
return XMLString::stringLen(getString());
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
return 0; // REVISIT
// default:
// throw; //ThrowXML(RuntimeException, ...)
} // end switch
return -1;
}
// ---------------------------------------------------------------------------
// Token: Helper mthods
// ---------------------------------------------------------------------------
int Token::analyzeFirstCharacter(RangeToken* const rangeTok,
const int options,
TokenFactory* const tokFactory)
{
switch(fTokenType) {
case T_CONCAT:
{
int ret = FC_CONTINUE;
for (int i=0; i<size(); i++) {
Token* tok = getChild(i);
if (tok
&& (ret=tok->analyzeFirstCharacter(rangeTok,
options, tokFactory))!= FC_CONTINUE)
break;
}
return ret;
}
case T_UNION:
{
unsigned int childSize = size();
if (childSize == 0)
return FC_CONTINUE;
int ret = FC_CONTINUE;
bool hasEmpty = false;
for (unsigned int i=0; i < childSize; i++) {
ret = getChild(i)->analyzeFirstCharacter(rangeTok, options, tokFactory);
if (ret == FC_ANY)
break;
else
hasEmpty = true;
}
return hasEmpty ? FC_CONTINUE : ret;
}
case T_CONDITION:
{
int ret1 = getChild(0)->analyzeFirstCharacter(rangeTok, options, tokFactory);
if (size() == 1)
return FC_CONTINUE;
int ret2;
if (ret1 != FC_ANY) {
ret2 = getChild(1)->analyzeFirstCharacter(rangeTok, options, tokFactory);
}
if (ret1 == FC_ANY || ret2 == FC_ANY)
return FC_ANY;
if (ret1 == FC_CONTINUE || ret2 == FC_CONTINUE)
return FC_CONTINUE;
return FC_TERMINAL;
}
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
{
Token* tok = getChild(0);
if (tok)
tok->analyzeFirstCharacter(rangeTok, options, tokFactory);
return FC_CONTINUE;
}
case T_DOT:
case T_EMPTY:
case T_ANCHOR:
return FC_CONTINUE;
case T_CHAR:
{
XMLInt32 ch = getChar();
rangeTok->addRange(ch, ch);
if (ch < 0x1000 && isSet(options,RegularExpression::IGNORE_CASE)) {
//REVISIT
}
}
return FC_TERMINAL;
case T_RANGE:
{
if (isSet(options, RegularExpression::IGNORE_CASE)) {
rangeTok->mergeRanges(((RangeToken*)
this)->getCaseInsensitiveToken(tokFactory));
}
else {
rangeTok->mergeRanges(this);
}
return FC_TERMINAL;
}
case T_NRANGE:
{
if (isSet(options, RegularExpression::IGNORE_CASE)) {
RangeToken* caseITok = (((RangeToken*)
this)->getCaseInsensitiveToken(tokFactory));
rangeTok->mergeRanges(RangeToken::complementRanges(caseITok, tokFactory));
}
else {
rangeTok->mergeRanges(
RangeToken::complementRanges((RangeToken*) this, tokFactory));
}
}
case T_INDEPENDENT:
case T_PAREN:
{
Token* tok = getChild(0);
if (tok)
return tok->analyzeFirstCharacter(rangeTok,options, tokFactory);
}
case T_MODIFIERGROUP:
case T_BACKREFERENCE:
rangeTok->addRange(0, UTF16_MAX);
return FC_ANY;
case T_STRING:
{
const XMLCh* str = getString();
XMLInt32 ch = str[0];
if (RegxUtil::isHighSurrogate((XMLCh) ch)) {
}
rangeTok->addRange(ch, ch);
if (ch<0x10000 && isSet(options,RegularExpression::IGNORE_CASE)) {
//REVISIT
}
}
return FC_TERMINAL;
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
return FC_CONTINUE;
// default:
// throw;
}
return 0;
}
Token* Token::findFixedString(int options, int& outOptions) {
switch(fTokenType) {
case T_CHAR:
return 0;
case T_STRING:
outOptions = options;
return this;
case T_UNION:
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
case T_EMPTY:
case T_ANCHOR:
case T_RANGE:
case T_NRANGE:
case T_DOT:
case T_BACKREFERENCE:
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
case T_CONDITION:
return 0;
case T_INDEPENDENT:
case T_PAREN:
return getChild(0)->findFixedString(options, outOptions);
case T_CONCAT:
{
Token* prevTok = 0;
int prevOptions = 0;
for (int i=0; i<size(); i++) {
Token* tok = getChild(i)->findFixedString(options, outOptions);
if (prevTok == 0 || prevTok->isShorterThan(tok)) {
prevTok = tok;
prevOptions = outOptions;
}
}
outOptions = prevOptions;
return prevTok;
}
case T_MODIFIERGROUP:
{
options |= ((ModifierToken *) this)->getOptions();
options &= ~((ModifierToken *) this)->getOptionsMask();
return getChild(0)->findFixedString(options, outOptions);
}
} // end switch
return 0;
}
bool Token::isShorterThan(Token* const tok) {
if (tok == 0)
return false;
if (getTokenType() != T_STRING && tok->getTokenType() != T_STRING)
return false; //Should we throw an exception?
int length = XMLString::stringLen(getString());
int tokLength = XMLString::stringLen(tok->getString());
return length < tokLength;
}
XERCES_CPP_NAMESPACE_END
/**
* End of file Token.cpp
*/
<commit_msg>Fixed bug in Token::analyzeFirstCharacter so that . matches new line with head character optimisation enabled. As per discussion Jennifer Schachter had with Khaled.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.5 2002/11/21 14:56:35 gareth
* Fixed bug in Token::analyzeFirstCharacter so that . matches new line with head character optimisation enabled. As per discussion Jennifer Schachter had with Khaled.
*
* Revision 1.4 2002/11/04 15:17:00 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/10/15 18:11:02 knoaman
* [Bug 13489]: missing 'return' in Token.cpp
*
* Revision 1.2 2002/03/18 19:29:53 knoaman
* Change constant names to eliminate possible conflict with user defined ones.
*
* Revision 1.1.1.1 2002/02/01 22:22:31 peiyongz
* sane_include
*
* Revision 1.3 2001/05/11 13:26:50 tng
* Copyright update.
*
* Revision 1.2 2001/05/03 18:17:49 knoaman
* Some design changes:
* o Changed the TokenFactory from a single static instance, to a
* normal class. Each RegularExpression object will have its own
* instance of TokenFactory, and that instance will be passed to
* other classes that need to use a TokenFactory to create Token
* objects (with the exception of RangeTokenMap).
* o Added a new class RangeTokenMap to map a the different ranges
* in a given category to a specific RangeFactory object. In the old
* design RangeFactory had dual functionality (act as a Map, and as
* a factory for creating RangeToken(s)). The RangeTokenMap will
* have its own copy of the TokenFactory. There will be only one
* instance of the RangeTokenMap class, and that instance will be
* lazily deleted when XPlatformUtils::Terminate is called.
*
* Revision 1.1 2001/03/02 19:22:58 knoaman
* Schema: Regular expression handling part I
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/RangeToken.hpp>
#include <xercesc/util/regx/ModifierToken.hpp>
#include <xercesc/util/regx/RegularExpression.hpp>
#include <xercesc/util/regx/RegxUtil.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Static member data initialization
// ---------------------------------------------------------------------------
const XMLInt32 Token::UTF16_MAX = 0x10FFFF;
const unsigned short Token::FC_CONTINUE = 0;
const unsigned short Token::FC_TERMINAL = 1;
const unsigned short Token::FC_ANY = 2;
// ---------------------------------------------------------------------------
// Token: Constructors and Destructors
// ---------------------------------------------------------------------------
Token::Token(const unsigned short tokType) : fTokenType(tokType) {
}
Token::~Token() {
}
// ---------------------------------------------------------------------------
// Token: Getter mthods
// ---------------------------------------------------------------------------
int Token::getMinLength() const {
switch (fTokenType) {
case T_CONCAT:
{
int sum = 0;
unsigned int childSize = size();
for (unsigned int i=0; i<childSize; i++) {
sum += getChild(i)->getMinLength();
}
return sum;
}
case T_CONDITION:
case T_UNION:
{
unsigned int childSize = size();
if (childSize == 0) {
return 0;
}
int ret = getChild(0)->getMinLength();
for (unsigned int i=1; i < childSize; i++) {
int min = getChild(i)->getMinLength();
if (min < ret)
ret = min;
}
return ret;
}
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
if (getMin() >= 0)
return getMin() * getChild(0)->getMinLength();
return 0;
case T_EMPTY:
case T_ANCHOR:
return 0;
case T_DOT:
case T_CHAR:
case T_RANGE:
case T_NRANGE:
return 1;
case T_INDEPENDENT:
case T_PAREN:
case T_MODIFIERGROUP:
return getChild(0)->getMinLength();
case T_BACKREFERENCE:
return 0; // ***** - REVISIT
case T_STRING:
return XMLString::stringLen(getString());
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
return 0; // ***** - REVIST
// default:
// throw;
}
// We should not get here, but we have it to make some compilers happy
return -1;
}
int Token::getMaxLength() const {
switch (fTokenType) {
case T_CONCAT:
{
int sum = 0;
unsigned int childSize = size();
for (unsigned int i=0; i<childSize; i++) {
int val = getChild(i)->getMaxLength();
if (val < 0){
return -1;
}
sum += val;
}
return sum;
}
case T_CONDITION:
case T_UNION:
{
unsigned int childSize = size();
if (childSize == 0)
return 0;
int ret = getChild(0)->getMaxLength();
for (unsigned i = 1; ret > 0 && i < childSize; i++) {
int max = getChild(i)->getMaxLength();
if (max < 0) {
ret = -1;
break;
}
if (max > ret)
ret = max;
}
return ret;
}
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
if (getMax() >= 0) {
return getMax() * getChild(0)->getMaxLength();
}
return -1;
case T_EMPTY:
case T_ANCHOR:
return 0;
case T_CHAR:
return 1;
case T_DOT:
case T_RANGE:
case T_NRANGE:
return 2;
case T_INDEPENDENT:
case T_PAREN:
case T_MODIFIERGROUP:
return getChild(0)->getMaxLength();
case T_BACKREFERENCE:
return -1; // REVISIT
case T_STRING:
return XMLString::stringLen(getString());
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
return 0; // REVISIT
// default:
// throw; //ThrowXML(RuntimeException, ...)
} // end switch
return -1;
}
// ---------------------------------------------------------------------------
// Token: Helper mthods
// ---------------------------------------------------------------------------
int Token::analyzeFirstCharacter(RangeToken* const rangeTok,
const int options,
TokenFactory* const tokFactory)
{
switch(fTokenType) {
case T_CONCAT:
{
int ret = FC_CONTINUE;
for (int i=0; i<size(); i++) {
Token* tok = getChild(i);
if (tok
&& (ret=tok->analyzeFirstCharacter(rangeTok,
options, tokFactory))!= FC_CONTINUE)
break;
}
return ret;
}
case T_UNION:
{
unsigned int childSize = size();
if (childSize == 0)
return FC_CONTINUE;
int ret = FC_CONTINUE;
bool hasEmpty = false;
for (unsigned int i=0; i < childSize; i++) {
ret = getChild(i)->analyzeFirstCharacter(rangeTok, options, tokFactory);
if (ret == FC_ANY)
break;
else
hasEmpty = true;
}
return hasEmpty ? FC_CONTINUE : ret;
}
case T_CONDITION:
{
int ret1 = getChild(0)->analyzeFirstCharacter(rangeTok, options, tokFactory);
if (size() == 1)
return FC_CONTINUE;
int ret2;
if (ret1 != FC_ANY) {
ret2 = getChild(1)->analyzeFirstCharacter(rangeTok, options, tokFactory);
}
if (ret1 == FC_ANY || ret2 == FC_ANY)
return FC_ANY;
if (ret1 == FC_CONTINUE || ret2 == FC_CONTINUE)
return FC_CONTINUE;
return FC_TERMINAL;
}
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
{
Token* tok = getChild(0);
if (tok)
tok->analyzeFirstCharacter(rangeTok, options, tokFactory);
return FC_CONTINUE;
}
case T_DOT:
return FC_ANY;
case T_EMPTY:
case T_ANCHOR:
return FC_CONTINUE;
case T_CHAR:
{
XMLInt32 ch = getChar();
rangeTok->addRange(ch, ch);
if (ch < 0x1000 && isSet(options,RegularExpression::IGNORE_CASE)) {
//REVISIT
}
}
return FC_TERMINAL;
case T_RANGE:
{
if (isSet(options, RegularExpression::IGNORE_CASE)) {
rangeTok->mergeRanges(((RangeToken*)
this)->getCaseInsensitiveToken(tokFactory));
}
else {
rangeTok->mergeRanges(this);
}
return FC_TERMINAL;
}
case T_NRANGE:
{
if (isSet(options, RegularExpression::IGNORE_CASE)) {
RangeToken* caseITok = (((RangeToken*)
this)->getCaseInsensitiveToken(tokFactory));
rangeTok->mergeRanges(RangeToken::complementRanges(caseITok, tokFactory));
}
else {
rangeTok->mergeRanges(
RangeToken::complementRanges((RangeToken*) this, tokFactory));
}
}
case T_INDEPENDENT:
case T_PAREN:
{
Token* tok = getChild(0);
if (tok)
return tok->analyzeFirstCharacter(rangeTok,options, tokFactory);
}
case T_MODIFIERGROUP:
case T_BACKREFERENCE:
rangeTok->addRange(0, UTF16_MAX);
return FC_ANY;
case T_STRING:
{
const XMLCh* str = getString();
XMLInt32 ch = str[0];
if (RegxUtil::isHighSurrogate((XMLCh) ch)) {
}
rangeTok->addRange(ch, ch);
if (ch<0x10000 && isSet(options,RegularExpression::IGNORE_CASE)) {
//REVISIT
}
}
return FC_TERMINAL;
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
return FC_CONTINUE;
// default:
// throw;
}
return 0;
}
Token* Token::findFixedString(int options, int& outOptions) {
switch(fTokenType) {
case T_CHAR:
return 0;
case T_STRING:
outOptions = options;
return this;
case T_UNION:
case T_CLOSURE:
case T_NONGREEDYCLOSURE:
case T_EMPTY:
case T_ANCHOR:
case T_RANGE:
case T_NRANGE:
case T_DOT:
case T_BACKREFERENCE:
case T_LOOKAHEAD:
case T_NEGATIVELOOKAHEAD:
case T_LOOKBEHIND:
case T_NEGATIVELOOKBEHIND:
case T_CONDITION:
return 0;
case T_INDEPENDENT:
case T_PAREN:
return getChild(0)->findFixedString(options, outOptions);
case T_CONCAT:
{
Token* prevTok = 0;
int prevOptions = 0;
for (int i=0; i<size(); i++) {
Token* tok = getChild(i)->findFixedString(options, outOptions);
if (prevTok == 0 || prevTok->isShorterThan(tok)) {
prevTok = tok;
prevOptions = outOptions;
}
}
outOptions = prevOptions;
return prevTok;
}
case T_MODIFIERGROUP:
{
options |= ((ModifierToken *) this)->getOptions();
options &= ~((ModifierToken *) this)->getOptionsMask();
return getChild(0)->findFixedString(options, outOptions);
}
} // end switch
return 0;
}
bool Token::isShorterThan(Token* const tok) {
if (tok == 0)
return false;
if (getTokenType() != T_STRING && tok->getTokenType() != T_STRING)
return false; //Should we throw an exception?
int length = XMLString::stringLen(getString());
int tokLength = XMLString::stringLen(tok->getString());
return length < tokLength;
}
XERCES_CPP_NAMESPACE_END
/**
* End of file Token.cpp
*/
<|endoftext|> |
<commit_before>//
// Created by Scott Stark on 4/7/15.
//
#include "LcdDisplay.h"
#include <wiringPi.h>
#include <lcd.h>
void LcdDisplay::displayBeacon(const Beacon &beacon) {
char tmp[80];
sprintf(tmp, "Beacon(%d):", beacon.getMinor());
lcdPosition(lcdHandle, 0, 0) ;
lcdPuts(lcdHandle, tmp);
sprintf(tmp, "rssi=%d", beacon.getRssi());
lcdPosition(lcdHandle, 2, 1) ;
lcdPuts(lcdHandle, tmp) ;
sprintf(tmp, "time=%lld", beacon.getTime());
lcdPosition(lcdHandle, 2, 2) ;
lcdPuts(lcdHandle, tmp) ;
sprintf(tmp, "Hello Scott");
lcdPosition(lcdHandle, 2, 3) ;
lcdPuts(lcdHandle, tmp) ;
}
void LcdDisplay::displayText(const string &text, int col, int row) {
lcdPosition(lcdHandle, col, row);
lcdPuts(lcdHandle, text.c_str());
// Clear the rest of the line
size_t length = text.size();
for(int c = length; c < nCols; c++) {
lcdPutchar(lcdHandle, ' ');
}
}
int LcdDisplay::init(int rows, int cols) {
nCols = cols;
wiringPiSetup () ;
lcdHandle = lcdInit (rows, cols, 4, 11,10, 4,5,6,7,0,0,0,0) ;
if (lcdHandle < 0)
{
fprintf (stderr, "lcdInit failed\n") ;
return -1 ;
}
return 0;
}
void LcdDisplay::clear() {
lcdClear(lcdHandle);
}
<commit_msg>Use diplayText to ensure line is updated to the eol<commit_after>//
// Created by Scott Stark on 4/7/15.
//
#include "LcdDisplay.h"
#include <wiringPi.h>
#include <lcd.h>
void LcdDisplay::displayBeacon(const Beacon &beacon) {
char tmp[80];
sprintf(tmp, "Beacon(%d):", beacon.getMinor());
displayText(tmp, 0, 0);
sprintf(tmp, "rssi=%d", beacon.getRssi());
displayText(tmp, 2, 1);
sprintf(tmp, "time=%lld", beacon.getTime());
displayText(tmp, 2, 2);
sprintf(tmp, "Hello Scott");
displayText(tmp, 2, 3);
}
void LcdDisplay::displayText(const string &text, int col, int row) {
lcdPosition(lcdHandle, col, row);
lcdPuts(lcdHandle, text.c_str());
// Clear the rest of the line
size_t length = text.size();
for(int c = length; c < nCols; c++) {
lcdPutchar(lcdHandle, ' ');
}
}
int LcdDisplay::init(int rows, int cols) {
nCols = cols;
wiringPiSetup () ;
lcdHandle = lcdInit (rows, cols, 4, 11,10, 4,5,6,7,0,0,0,0) ;
if (lcdHandle < 0)
{
fprintf (stderr, "lcdInit failed\n") ;
return -1 ;
}
return 0;
}
void LcdDisplay::clear() {
lcdClear(lcdHandle);
}
<|endoftext|> |
<commit_before><commit_msg>Change platform_file_unittest.cc to report the time values when an assertion fails.<commit_after><|endoftext|> |
<commit_before>#include "incoherent.h"
#include "spiMaster.h"
IncoherentDetector incoherentDetector;
IncoherentDetector::IncoherentDetector() {
// Real setup is in incoherentSetup, in setup() function
for (int i = 0; i < buffer_length; i++) {
buff[i] = 0;
}
}
void IncoherentDetector::incoherentSetup() {
sample = 0;
//Fill in initial values of the buffer
for(int i = 0; i < buffer_length; i++){
buff[i] = 0;
}
for(int i = 0; i < 2*numCells; i++){
rolling_detectors[i] = 0;
}
}
void IncoherentDetector::incoherentProcess(const volatile adcSample& s, adcSample& output) {
//Retrieve latest sample values;
int32_t latest[numCells] = {(int32_t) s.a, (int32_t) s.b, (int32_t) s.c, (int32_t) s.d};
//Ensures the sample does not exceed the buffer index
sample = sample % samples_per_cell;
//Determines square wave value for our "sine" and "cosine" waves
int sinVal = envelope[sample%4];
int cosVal = envelope[(sample + 1)%4];
//Replaces previous adc sample with new sample, and saves the previous sample for each quad cell
for(int i = 0; i < numCells; i++){
int32_t previous = buff[sample * numCells + i];
buff[sample * numCells + i] = latest[i];
//Updates the rolling detector sums wihtout having to recalculate the entire function (subtracts previous and adds new)
rolling_detectors[i * 2] += sinVal*(latest[i] - previous);
rolling_detectors[i * 2 + 1] += cosVal*(latest[i] - previous);
}
sample++;
//Calculates and sets the four axis incoherent values
for(int i = 0; i < numCells; i++){
output.a = sqrt(sq(rolling_detectors[0]/samples_per_cell) + sq(rolling_detectors[1]/samples_per_cell));
output.b = sqrt(sq(rolling_detectors[2]/samples_per_cell) + sq(rolling_detectors[3]/samples_per_cell));
output.c = sqrt(sq(rolling_detectors[4]/samples_per_cell) + sq(rolling_detectors[5]/samples_per_cell));
output.d = sqrt(sq(rolling_detectors[6]/samples_per_cell) + sq(rolling_detectors[7]/samples_per_cell));
}
}
void IncoherentDetector::incoherentDisplacement(const adcSample& incoherentOutput, double& xpos, double& ypos, double theta){
//Assuming axis number maps to quadrant number
double quadA = incoherentOutput.a;
double quadB = incoherentOutput.b;
double quadC = incoherentOutput.c;
double quadD = incoherentOutput.d;
double xposIntermediate = ((quadA + quadD) - (quadB + quadC))/(quadA + quadB + quadC + quadD);
double yposIntermediate = ((quadA + quadB) - (quadC + quadD))/(quadA + quadB + quadC + quadD);
xpos = cos(theta) * xposIntermediate - sin(theta) * yposIntermediate;
ypos = sin(theta) * xposIntermediate + cos(theta) * yposIntermediate;
}
<commit_msg>Fix minor divide by zero bug in incoherentDisplacement<commit_after>#include "incoherent.h"
#include "spiMaster.h"
IncoherentDetector incoherentDetector;
IncoherentDetector::IncoherentDetector() {
// Real setup is in incoherentSetup, in setup() function
for (int i = 0; i < buffer_length; i++) {
buff[i] = 0;
}
}
void IncoherentDetector::incoherentSetup() {
sample = 0;
//Fill in initial values of the buffer
for(int i = 0; i < buffer_length; i++){
buff[i] = 0;
}
for(int i = 0; i < 2*numCells; i++){
rolling_detectors[i] = 0;
}
}
void IncoherentDetector::incoherentProcess(const volatile adcSample& s, adcSample& output) {
//Retrieve latest sample values;
int32_t latest[numCells] = {(int32_t) s.a, (int32_t) s.b, (int32_t) s.c, (int32_t) s.d};
//Ensures the sample does not exceed the buffer index
sample = sample % samples_per_cell;
//Determines square wave value for our "sine" and "cosine" waves
int sinVal = envelope[sample%4];
int cosVal = envelope[(sample + 1)%4];
//Replaces previous adc sample with new sample, and saves the previous sample for each quad cell
for(int i = 0; i < numCells; i++){
int32_t previous = buff[sample * numCells + i];
buff[sample * numCells + i] = latest[i];
//Updates the rolling detector sums wihtout having to recalculate the entire function (subtracts previous and adds new)
rolling_detectors[i * 2] += sinVal*(latest[i] - previous);
rolling_detectors[i * 2 + 1] += cosVal*(latest[i] - previous);
}
sample++;
//Calculates and sets the four axis incoherent values
for(int i = 0; i < numCells; i++){
output.a = sqrt(sq(rolling_detectors[0]/samples_per_cell) + sq(rolling_detectors[1]/samples_per_cell));
output.b = sqrt(sq(rolling_detectors[2]/samples_per_cell) + sq(rolling_detectors[3]/samples_per_cell));
output.c = sqrt(sq(rolling_detectors[4]/samples_per_cell) + sq(rolling_detectors[5]/samples_per_cell));
output.d = sqrt(sq(rolling_detectors[6]/samples_per_cell) + sq(rolling_detectors[7]/samples_per_cell));
}
}
void IncoherentDetector::incoherentDisplacement(const adcSample& incoherentOutput, double& xpos, double& ypos, double theta){
//Assuming axis number maps to quadrant number
double quadA = incoherentOutput.a;
double quadB = incoherentOutput.b;
double quadC = incoherentOutput.c;
double quadD = incoherentOutput.d;
if (quadA + quadB + quadC + quadD == 0) {
xpos = 0;
ypos = 0;
} else {
double xposIntermediate = ((quadA + quadD) - (quadB + quadC))/(quadA + quadB + quadC + quadD);
double yposIntermediate = ((quadA + quadB) - (quadC + quadD))/(quadA + quadB + quadC + quadD);
xpos = cos(theta) * xposIntermediate - sin(theta) * yposIntermediate;
ypos = sin(theta) * xposIntermediate + cos(theta) * yposIntermediate;
}
}
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <cstring>
#include <iostream>
#include <vector>
#include <set>
#include <bh.h>
#include "bh_vem_cluster.h"
#include "mapping.h"
#include "array.h"
#include "pgrid.h"
#include "dispatch.h"
#include "comm.h"
#include "except.h"
#include "ufunc_reduce.h"
#include "batch.h"
#include "tmp.h"
#include "timing.h"
//Function pointers to the Node VEM.
static bh_init vem_init;
static bh_shutdown vem_shutdown;
static bh_reg_func vem_reg_func;
//Public function pointer to the Node VEM
bh_execute exec_vem_execute;
//The VE components
static bh_component **my_components;
//Our self
static bh_component *myself;
//Number of user-defined functions registered.
static bh_intp userfunc_count = 0;
//User-defined function IDs.
static bh_userfunc_impl reduce_impl = NULL;
static bh_intp reduce_impl_id = 0;
static bh_userfunc_impl random_impl = NULL;
static bh_intp random_impl_id = 0;
//Number of instruction fallbacks
static bh_intp fallback_count = 0;
/* Initialize the VEM
*
* @return Error codes (BH_SUCCESS)
*/
bh_error exec_init(const char *component_name)
{
bh_intp children_count;
bh_error err;
myself = bh_component_setup(component_name);
if(myself == NULL)
return BH_ERROR;
err = bh_component_children(myself, &children_count, &my_components);
if (children_count != 1)
{
std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
return BH_ERROR;
}
if (err != BH_SUCCESS)
return err;
vem_init = my_components[0]->init;
exec_vem_execute = my_components[0]->execute;
vem_shutdown = my_components[0]->shutdown;
vem_reg_func = my_components[0]->reg_func;
//Let us initiate the Node VEM.
if((err = vem_init(my_components[0])) != 0)
return err;
return BH_SUCCESS;
}
/* Shutdown the VEM, which include a instruction flush
*
* @return Error codes (BH_SUCCESS)
*/
bh_error exec_shutdown(void)
{
bh_error err;
if((err = vem_shutdown()) != BH_SUCCESS)
return err;
bh_component_free(my_components[0]);//Only got one child.
vem_init = NULL;
exec_vem_execute = NULL;
vem_shutdown = NULL;
vem_reg_func = NULL;
bh_component_free_ptr(my_components);
my_components = NULL;
//Finalize the process grid
pgrid_finalize();
//Finalize the process grid
dispatch_finalize();
if(fallback_count > 0)
fprintf(stderr, "[CLUSTER-VEM] Warning - fallen back to "
"sequential executing %ld times.\n", fallback_count);
return BH_SUCCESS;
}
/* Register a new user-defined function.
*
* @lib Name of the shared library e.g. libmyfunc.so
* When NULL the default library is used.
* @fun Name of the function e.g. myfunc
* @id Identifier for the new function. The bridge should set the
* initial value to Zero. (in/out-put)
* @return Error codes (BH_SUCCESS)
*/
bh_error exec_reg_func(char *fun, bh_intp *id)
{
bh_error e;
if(*id == 0)//Only if parent didn't set the ID.
{
*id = ++userfunc_count;
assert(pgrid_myrank == 0);
}
if((e = vem_reg_func(fun, id)) != BH_SUCCESS)
{
*id = 0;
return e;
}
//NB: For now all user-defined functions are hardcoded
if(strcmp("bh_reduce", fun) == 0)
{
if(reduce_impl == NULL)
{
reduce_impl_id = *id;
return BH_SUCCESS;
}
}
else if(strcmp("bh_random", fun) == 0)
{
if(random_impl == NULL)
{
random_impl_id = *id;
return BH_SUCCESS;
}
}
return BH_SUCCESS;
}
/* Execute to instruction locally at the master-process
*
* @instruction The instructionto execute
*/
static void fallback_exec(bh_instruction *inst)
{
int nop = bh_operands_in_instruction(inst);
std::set<bh_array*> arys2discard;
batch_flush();
++fallback_count;
//Gather all data at the master-process
bh_array **oprands = bh_inst_operands(inst);
for(bh_intp o=0; o < nop; ++o)
{
bh_array *op = oprands[o];
if(bh_is_constant(op))
continue;
bh_array *base = bh_base_array(op);
comm_slaves2master(base);
}
//Do global instruction
if(pgrid_myrank == 0)
{
batch_schedule(*inst);
}
//Scatter all data back to all processes
for(bh_intp o=0; o < nop; ++o)
{
bh_array *op = oprands[o];
if(bh_is_constant(op))
continue;
bh_array *base = bh_base_array(op);
//We have to make sure that the master-process has allocated memory
//because the slaves cannot determine it.
if(pgrid_myrank == 0)
bh_data_malloc(base);
comm_master2slaves(base);
//All local arrays should be discarded
arys2discard.insert(op);
arys2discard.insert(base);
}
//Discard all local views
for(std::set<bh_array*>::iterator it=arys2discard.begin();
it != arys2discard.end(); ++it)
{
if((*it)->base != NULL)
{
batch_schedule(BH_DISCARD, *it);
}
}
//Free and discard all local base arrays
for(std::set<bh_array*>::iterator it=arys2discard.begin();
it != arys2discard.end(); ++it)
{
if((*it)->base == NULL)
{
batch_schedule(BH_FREE, *it);
batch_schedule(BH_DISCARD, *it);
}
}
}
/* Execute a regular computation instruction
*
* @instruction The regular computation instruction
*/
static void execute_regular(bh_instruction *inst)
{
std::vector<ary_chunk> chunks;
int nop = bh_operands_in_instruction(inst);
bh_array **operands = bh_inst_operands(inst);
mapping_chunks(nop, operands, chunks);
assert(chunks.size() > 0);
//Handle one chunk at a time.
for(std::vector<ary_chunk>::size_type c=0; c < chunks.size();c += nop)
{
assert(bh_nelements(chunks[0].ary->ndim, chunks[0].ary->shape) > 0);
//The process where the output chunk is located will do the computation.
int owner_rank = chunks[0+c].rank;
//Create a local instruction based on the array-chunks
bh_instruction local_inst = *inst;
for(bh_intp k=0; k < nop; ++k)
{
if(!bh_is_constant(inst->operand[k]))
{
ary_chunk *chunk = &chunks[k+c];
local_inst.operand[k] = chunk->ary;
comm_array_data(chunk, owner_rank);
}
}
//Check if we should do the computation
if(pgrid_myrank != owner_rank)
continue;
//Schedule task
batch_schedule(local_inst);
//Free and discard all local chunk arrays
for(bh_intp k=0; k < nop; ++k)
{
if(bh_is_constant(inst->operand[k]))
continue;
bh_array *ary = chunks[k+c].ary;
if(ary->base == NULL)
batch_schedule(BH_FREE, ary);
batch_schedule(BH_DISCARD, ary);
}
}
}
/* Execute a list of instructions where all operands are global arrays
*
* @instruction A list of instructions to execute
* @return Error codes
*/
bh_error exec_execute(bh_intp count, bh_instruction inst_list[])
{
if(count <= 0)
return BH_SUCCESS;
// bh_pprint_instr_list(inst_list, count, "GLOBAL");
bh_uint64 stime = bh_timing();
for(bh_intp i=0; i < count; ++i)
{
bh_instruction* inst = &inst_list[i];
assert(inst->opcode >= 0);
switch(inst->opcode)
{
case BH_USERFUNC:
{
if (inst->userfunc->id == reduce_impl_id)
{
bh_uint64 stime_reduce = bh_timing();
//TODO: the bh_reduce is hardcoded for now.
if(bh_reduce(inst->userfunc, NULL) != BH_SUCCESS)
EXCEPT("[CLUSTER-VEM] The user-defined function bh_reduce failed.");
bh_timing_save(timing_reduce, stime_reduce, bh_timing());
}else if (inst->userfunc->id == random_impl_id)
{
//TODO: the bh_random is hardcoded for now.
if(bh_random(inst->userfunc, NULL) != BH_SUCCESS)
EXCEPT("[CLUSTER-VEM] The user-defined function bh_random failed.");
}
else
{
fallback_exec(inst);
}
break;
}
case BH_ADD_REDUCE:
case BH_MUL_REDUCE:
{
bh_reduce_type reduce_data;
reduce_data.id = 0;
reduce_data.nout = 1;
reduce_data.nin = 1;
reduce_data.struct_size = sizeof(bh_reduce_type);
reduce_data.opcode = inst->opcode == BH_ADD_REDUCE ? BH_ADD : BH_MULTIPLY;
reduce_data.operand[0] = inst->operand[0];
reduce_data.operand[1] = inst->operand[1];
if (inst->constant.type == BH_INT64) {
bh_uint64 stime_reduce = bh_timing();
reduce_data.axis = inst->constant.value.int64;
res = bh_reduce((bh_userfunc *)&reduce_data, NULL);
bh_timing_save(timing_reduce, stime_reduce, bh_timing());
}
else
res = BH_TYPE_NOT_SUPPORTED;
break;
}
case BH_DISCARD:
{
bh_array *g_ary = inst->operand[0];
if(g_ary->base == NULL)
{
bh_array *l_ary = array_get_existing_local(g_ary);
if(l_ary != NULL)
{
batch_schedule(BH_DISCARD, l_ary);
}
}
dispatch_slave_known_remove(g_ary);
break;
}
case BH_FREE:
{
bh_array *g_ary = bh_base_array(inst->operand[0]);
bh_array *l_ary = array_get_existing_local(g_ary);
bh_data_free(g_ary);
if(l_ary != NULL)
batch_schedule(BH_FREE, l_ary);
break;
}
case BH_SYNC:
{
bh_array *base = bh_base_array(inst->operand[0]);
comm_slaves2master(base);
break;
}
case BH_NONE:
{
break;
}
default:
{
execute_regular(inst);
}
}
}
//Lets flush all scheduled tasks
batch_flush();
//And remove all tmp data structures
tmp_clear();
bh_timing_save(timing_exec_execute, stime, bh_timing());
return BH_SUCCESS;
}
bh_error bh_reduce( bh_userfunc *arg, void* ve_arg)
{
bh_reduce_type *a = (bh_reduce_type *) arg; // Grab function arguments
bh_opcode opcode = a->opcode; // Opcode
bh_index axis = a->axis; // The axis to reduce
return ufunc_reduce(opcode, axis, a->operand, reduce_impl_id);
}
bh_error bh_random( bh_userfunc *arg, void* ve_arg)
{
bh_array *op = arg->operand[0];
std::vector<ary_chunk> chunks;
mapping_chunks(1, &op, chunks);
assert(chunks.size() > 0);
//Handle one chunk at a time.
for(std::vector<ary_chunk>::size_type c=0; c < chunks.size(); ++c)
{
assert(bh_nelements(chunks[0].ary->ndim, chunks[0].ary->shape) > 0);
//The process where the output chunk is located will do the computation.
if(pgrid_myrank == chunks[c].rank)
{
bh_random_type *ufunc = (bh_random_type*)tmp_get_misc(sizeof(bh_random_type));
ufunc->id = random_impl_id;
ufunc->nout = 1;
ufunc->nin = 0;
ufunc->struct_size = sizeof(bh_random_type);
ufunc->operand[0] = chunks[c].ary;
batch_schedule(BH_USERFUNC, NULL, (bh_userfunc*)(ufunc));
batch_schedule(BH_DISCARD, chunks[c].ary);
}
}
return BH_SUCCESS;
}
<commit_msg>Revert "Implementation of the BH_ADD_REDUCE and BH_MUL_REDUCE in cluster VEM"<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <cstring>
#include <iostream>
#include <vector>
#include <set>
#include <bh.h>
#include "bh_vem_cluster.h"
#include "mapping.h"
#include "array.h"
#include "pgrid.h"
#include "dispatch.h"
#include "comm.h"
#include "except.h"
#include "ufunc_reduce.h"
#include "batch.h"
#include "tmp.h"
#include "timing.h"
//Function pointers to the Node VEM.
static bh_init vem_init;
static bh_shutdown vem_shutdown;
static bh_reg_func vem_reg_func;
//Public function pointer to the Node VEM
bh_execute exec_vem_execute;
//The VE components
static bh_component **my_components;
//Our self
static bh_component *myself;
//Number of user-defined functions registered.
static bh_intp userfunc_count = 0;
//User-defined function IDs.
static bh_userfunc_impl reduce_impl = NULL;
static bh_intp reduce_impl_id = 0;
static bh_userfunc_impl random_impl = NULL;
static bh_intp random_impl_id = 0;
//Number of instruction fallbacks
static bh_intp fallback_count = 0;
/* Initialize the VEM
*
* @return Error codes (BH_SUCCESS)
*/
bh_error exec_init(const char *component_name)
{
bh_intp children_count;
bh_error err;
myself = bh_component_setup(component_name);
if(myself == NULL)
return BH_ERROR;
err = bh_component_children(myself, &children_count, &my_components);
if (children_count != 1)
{
std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
return BH_ERROR;
}
if (err != BH_SUCCESS)
return err;
vem_init = my_components[0]->init;
exec_vem_execute = my_components[0]->execute;
vem_shutdown = my_components[0]->shutdown;
vem_reg_func = my_components[0]->reg_func;
//Let us initiate the Node VEM.
if((err = vem_init(my_components[0])) != 0)
return err;
return BH_SUCCESS;
}
/* Shutdown the VEM, which include a instruction flush
*
* @return Error codes (BH_SUCCESS)
*/
bh_error exec_shutdown(void)
{
bh_error err;
if((err = vem_shutdown()) != BH_SUCCESS)
return err;
bh_component_free(my_components[0]);//Only got one child.
vem_init = NULL;
exec_vem_execute = NULL;
vem_shutdown = NULL;
vem_reg_func = NULL;
bh_component_free_ptr(my_components);
my_components = NULL;
//Finalize the process grid
pgrid_finalize();
//Finalize the process grid
dispatch_finalize();
if(fallback_count > 0)
fprintf(stderr, "[CLUSTER-VEM] Warning - fallen back to "
"sequential executing %ld times.\n", fallback_count);
return BH_SUCCESS;
}
/* Register a new user-defined function.
*
* @lib Name of the shared library e.g. libmyfunc.so
* When NULL the default library is used.
* @fun Name of the function e.g. myfunc
* @id Identifier for the new function. The bridge should set the
* initial value to Zero. (in/out-put)
* @return Error codes (BH_SUCCESS)
*/
bh_error exec_reg_func(char *fun, bh_intp *id)
{
bh_error e;
if(*id == 0)//Only if parent didn't set the ID.
{
*id = ++userfunc_count;
assert(pgrid_myrank == 0);
}
if((e = vem_reg_func(fun, id)) != BH_SUCCESS)
{
*id = 0;
return e;
}
//NB: For now all user-defined functions are hardcoded
if(strcmp("bh_reduce", fun) == 0)
{
if(reduce_impl == NULL)
{
reduce_impl_id = *id;
return BH_SUCCESS;
}
}
else if(strcmp("bh_random", fun) == 0)
{
if(random_impl == NULL)
{
random_impl_id = *id;
return BH_SUCCESS;
}
}
return BH_SUCCESS;
}
/* Execute to instruction locally at the master-process
*
* @instruction The instructionto execute
*/
static void fallback_exec(bh_instruction *inst)
{
int nop = bh_operands_in_instruction(inst);
std::set<bh_array*> arys2discard;
batch_flush();
++fallback_count;
//Gather all data at the master-process
bh_array **oprands = bh_inst_operands(inst);
for(bh_intp o=0; o < nop; ++o)
{
bh_array *op = oprands[o];
if(bh_is_constant(op))
continue;
bh_array *base = bh_base_array(op);
comm_slaves2master(base);
}
//Do global instruction
if(pgrid_myrank == 0)
{
batch_schedule(*inst);
}
//Scatter all data back to all processes
for(bh_intp o=0; o < nop; ++o)
{
bh_array *op = oprands[o];
if(bh_is_constant(op))
continue;
bh_array *base = bh_base_array(op);
//We have to make sure that the master-process has allocated memory
//because the slaves cannot determine it.
if(pgrid_myrank == 0)
bh_data_malloc(base);
comm_master2slaves(base);
//All local arrays should be discarded
arys2discard.insert(op);
arys2discard.insert(base);
}
//Discard all local views
for(std::set<bh_array*>::iterator it=arys2discard.begin();
it != arys2discard.end(); ++it)
{
if((*it)->base != NULL)
{
batch_schedule(BH_DISCARD, *it);
}
}
//Free and discard all local base arrays
for(std::set<bh_array*>::iterator it=arys2discard.begin();
it != arys2discard.end(); ++it)
{
if((*it)->base == NULL)
{
batch_schedule(BH_FREE, *it);
batch_schedule(BH_DISCARD, *it);
}
}
}
/* Execute a regular computation instruction
*
* @instruction The regular computation instruction
*/
static void execute_regular(bh_instruction *inst)
{
std::vector<ary_chunk> chunks;
int nop = bh_operands_in_instruction(inst);
bh_array **operands = bh_inst_operands(inst);
mapping_chunks(nop, operands, chunks);
assert(chunks.size() > 0);
//Handle one chunk at a time.
for(std::vector<ary_chunk>::size_type c=0; c < chunks.size();c += nop)
{
assert(bh_nelements(chunks[0].ary->ndim, chunks[0].ary->shape) > 0);
//The process where the output chunk is located will do the computation.
int owner_rank = chunks[0+c].rank;
//Create a local instruction based on the array-chunks
bh_instruction local_inst = *inst;
for(bh_intp k=0; k < nop; ++k)
{
if(!bh_is_constant(inst->operand[k]))
{
ary_chunk *chunk = &chunks[k+c];
local_inst.operand[k] = chunk->ary;
comm_array_data(chunk, owner_rank);
}
}
//Check if we should do the computation
if(pgrid_myrank != owner_rank)
continue;
//Schedule task
batch_schedule(local_inst);
//Free and discard all local chunk arrays
for(bh_intp k=0; k < nop; ++k)
{
if(bh_is_constant(inst->operand[k]))
continue;
bh_array *ary = chunks[k+c].ary;
if(ary->base == NULL)
batch_schedule(BH_FREE, ary);
batch_schedule(BH_DISCARD, ary);
}
}
}
/* Execute a list of instructions where all operands are global arrays
*
* @instruction A list of instructions to execute
* @return Error codes
*/
bh_error exec_execute(bh_intp count, bh_instruction inst_list[])
{
if(count <= 0)
return BH_SUCCESS;
// bh_pprint_instr_list(inst_list, count, "GLOBAL");
bh_uint64 stime = bh_timing();
for(bh_intp i=0; i < count; ++i)
{
bh_instruction* inst = &inst_list[i];
assert(inst->opcode >= 0);
switch(inst->opcode)
{
case BH_USERFUNC:
{
if (inst->userfunc->id == reduce_impl_id)
{
bh_uint64 stime_reduce = bh_timing();
//TODO: the bh_reduce is hardcoded for now.
if(bh_reduce(inst->userfunc, NULL) != BH_SUCCESS)
EXCEPT("[CLUSTER-VEM] The user-defined function bh_reduce failed.");
bh_timing_save(timing_reduce, stime_reduce, bh_timing());
}else if (inst->userfunc->id == random_impl_id)
{
//TODO: the bh_random is hardcoded for now.
if(bh_random(inst->userfunc, NULL) != BH_SUCCESS)
EXCEPT("[CLUSTER-VEM] The user-defined function bh_random failed.");
}
else
{
fallback_exec(inst);
}
break;
}
case BH_DISCARD:
{
bh_array *g_ary = inst->operand[0];
if(g_ary->base == NULL)
{
bh_array *l_ary = array_get_existing_local(g_ary);
if(l_ary != NULL)
{
batch_schedule(BH_DISCARD, l_ary);
}
}
dispatch_slave_known_remove(g_ary);
break;
}
case BH_FREE:
{
bh_array *g_ary = bh_base_array(inst->operand[0]);
bh_array *l_ary = array_get_existing_local(g_ary);
bh_data_free(g_ary);
if(l_ary != NULL)
batch_schedule(BH_FREE, l_ary);
break;
}
case BH_SYNC:
{
bh_array *base = bh_base_array(inst->operand[0]);
comm_slaves2master(base);
break;
}
case BH_NONE:
{
break;
}
default:
{
execute_regular(inst);
}
}
}
//Lets flush all scheduled tasks
batch_flush();
//And remove all tmp data structures
tmp_clear();
bh_timing_save(timing_exec_execute, stime, bh_timing());
return BH_SUCCESS;
}
bh_error bh_reduce( bh_userfunc *arg, void* ve_arg)
{
bh_reduce_type *a = (bh_reduce_type *) arg; // Grab function arguments
bh_opcode opcode = a->opcode; // Opcode
bh_index axis = a->axis; // The axis to reduce
return ufunc_reduce(opcode, axis, a->operand, reduce_impl_id);
}
bh_error bh_random( bh_userfunc *arg, void* ve_arg)
{
bh_array *op = arg->operand[0];
std::vector<ary_chunk> chunks;
mapping_chunks(1, &op, chunks);
assert(chunks.size() > 0);
//Handle one chunk at a time.
for(std::vector<ary_chunk>::size_type c=0; c < chunks.size(); ++c)
{
assert(bh_nelements(chunks[0].ary->ndim, chunks[0].ary->shape) > 0);
//The process where the output chunk is located will do the computation.
if(pgrid_myrank == chunks[c].rank)
{
bh_random_type *ufunc = (bh_random_type*)tmp_get_misc(sizeof(bh_random_type));
ufunc->id = random_impl_id;
ufunc->nout = 1;
ufunc->nin = 0;
ufunc->struct_size = sizeof(bh_random_type);
ufunc->operand[0] = chunks[c].ary;
batch_schedule(BH_USERFUNC, NULL, (bh_userfunc*)(ufunc));
batch_schedule(BH_DISCARD, chunks[c].ary);
}
}
return BH_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2015
* Unit tests for the gas estimator.
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <libevmasm/GasMeter.h>
#include <libevmasm/KnownState.h>
#include <libevmasm/PathGasMeter.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/interface/GasEstimator.h>
#include <libsolidity/interface/SourceReferenceFormatter.h>
using namespace std;
using namespace dev::eth;
using namespace dev::solidity;
namespace dev
{
namespace solidity
{
namespace test
{
class GasMeterTestFramework: public ExecutionFramework
{
public:
GasMeterTestFramework() { }
void compile(string const& _sourceCode)
{
m_compiler.setSource(_sourceCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
AssemblyItems const* items = m_compiler.runtimeAssemblyItems("");
ASTNode const& sourceUnit = m_compiler.ast();
BOOST_REQUIRE(items != nullptr);
m_gasCosts = GasEstimator::breakToStatementLevel(
GasEstimator::structuralEstimation(*items, vector<ASTNode const*>({&sourceUnit})),
{&sourceUnit}
);
}
void testCreationTimeGas(string const& _sourceCode)
{
EVMSchedule schedule;
compileAndRun(_sourceCode);
auto state = make_shared<KnownState>();
PathGasMeter meter(*m_compiler.assemblyItems());
GasMeter::GasConsumption gas = meter.estimateMax(0, state);
u256 bytecodeSize(m_compiler.runtimeObject().bytecode.size());
gas += bytecodeSize * schedule.createDataGas;
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK(gas.value == m_gasUsed);
}
/// Compares the gas computed by PathGasMeter for the given signature (but unknown arguments)
/// against the actual gas usage computed by the VM on the given set of argument variants.
void testRunTimeGas(string const& _sig, vector<bytes> _argumentVariants)
{
u256 gasUsed = 0;
FixedHash<4> hash(dev::sha3(_sig));
for (bytes const& arguments: _argumentVariants)
{
sendMessage(hash.asBytes() + arguments, false, 0);
gasUsed = max(gasUsed, m_gasUsed);
}
GasMeter::GasConsumption gas = GasEstimator::functionalEstimation(
*m_compiler.runtimeAssemblyItems(),
_sig
);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK(gas.value == m_gasUsed);
}
protected:
map<ASTNode const*, eth::GasMeter::GasConsumption> m_gasCosts;
};
BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework)
BOOST_AUTO_TEST_CASE(non_overlapping_filtered_costs)
{
char const* sourceCode = R"(
contract test {
bytes x;
function f(uint a) returns (uint b) {
x.length = a;
for (; a < 200; ++a) {
x[a] = 9;
b = a * a;
}
return f(a - 1);
}
}
)";
compile(sourceCode);
for (auto first = m_gasCosts.cbegin(); first != m_gasCosts.cend(); ++first)
{
auto second = first;
for (++second; second != m_gasCosts.cend(); ++second)
if (first->first->location().intersects(second->first->location()))
{
BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!");
auto scannerFromSource = [&](string const&) -> Scanner const& { return m_compiler.scanner(); };
SourceReferenceFormatter::printSourceLocation(cout, &first->first->location(), scannerFromSource);
SourceReferenceFormatter::printSourceLocation(cout, &second->first->location(), scannerFromSource);
}
}
}
BOOST_AUTO_TEST_CASE(simple_contract)
{
// Tests a simple "deploy contract" code without constructor. The actual contract is not relevant.
char const* sourceCode = R"(
contract test {
bytes32 public shaValue;
function f(uint a) {
shaValue = sha3(a);
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(store_sha3)
{
char const* sourceCode = R"(
contract test {
bytes32 public shaValue;
function test(uint a) {
shaValue = sha3(a);
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(updating_store)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function test() {
data = 1;
data = 2;
data2 = 0;
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(branches)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) {
if (x > 7)
data2 = 1;
else
data = 1;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
}
BOOST_AUTO_TEST_CASE(function_calls)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) {
if (x > 7)
data2 = g(x**8) + 1;
else
data = 1;
}
function g(uint x) internal returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
}
BOOST_AUTO_TEST_CASE(multiple_external_functions)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) {
if (x > 7)
data2 = g(x**8) + 1;
else
data = 1;
}
function g(uint x) returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
testRunTimeGas("g(uint256)", vector<bytes>{encodeArgs(2)});
}
BOOST_AUTO_TEST_SUITE_END()
}
}
}
<commit_msg>Fixes for gas tests.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2015
* Unit tests for the gas estimator.
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <libevmasm/GasMeter.h>
#include <libevmasm/KnownState.h>
#include <libevmasm/PathGasMeter.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/interface/GasEstimator.h>
#include <libsolidity/interface/SourceReferenceFormatter.h>
using namespace std;
using namespace dev::eth;
using namespace dev::solidity;
namespace dev
{
namespace solidity
{
namespace test
{
class GasMeterTestFramework: public ExecutionFramework
{
public:
GasMeterTestFramework() { }
void compile(string const& _sourceCode)
{
m_compiler.setSource(_sourceCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
AssemblyItems const* items = m_compiler.runtimeAssemblyItems("");
ASTNode const& sourceUnit = m_compiler.ast();
BOOST_REQUIRE(items != nullptr);
m_gasCosts = GasEstimator::breakToStatementLevel(
GasEstimator::structuralEstimation(*items, vector<ASTNode const*>({&sourceUnit})),
{&sourceUnit}
);
}
void testCreationTimeGas(string const& _sourceCode)
{
EVMSchedule schedule;
compileAndRun(_sourceCode);
auto state = make_shared<KnownState>();
PathGasMeter meter(*m_compiler.assemblyItems());
GasMeter::GasConsumption gas = meter.estimateMax(0, state);
u256 bytecodeSize(m_compiler.runtimeObject().bytecode.size());
// costs for deployment
gas += bytecodeSize * schedule.createDataGas;
// costs for transaction
gas += gasForTransaction(m_compiler.object().bytecode, true);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK(gas.value == m_gasUsed);
}
/// Compares the gas computed by PathGasMeter for the given signature (but unknown arguments)
/// against the actual gas usage computed by the VM on the given set of argument variants.
void testRunTimeGas(string const& _sig, vector<bytes> _argumentVariants)
{
u256 gasUsed = 0;
GasMeter::GasConsumption gas;
FixedHash<4> hash(dev::sha3(_sig));
for (bytes const& arguments: _argumentVariants)
{
sendMessage(hash.asBytes() + arguments, false, 0);
gasUsed = max(gasUsed, m_gasUsed);
gas = max(gas, gasForTransaction(hash.asBytes() + arguments, false));
}
gas += GasEstimator::functionalEstimation(
*m_compiler.runtimeAssemblyItems(),
_sig
);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK(gas.value == m_gasUsed);
}
static GasMeter::GasConsumption gasForTransaction(bytes const& _data, bool _isCreation)
{
EVMSchedule schedule;
GasMeter::GasConsumption gas = _isCreation ? schedule.txCreateGas : schedule.txGas;
for (auto i: _data)
gas += i != 0 ? schedule.txDataNonZeroGas : schedule.txDataZeroGas;
return gas;
}
protected:
map<ASTNode const*, eth::GasMeter::GasConsumption> m_gasCosts;
};
BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework)
BOOST_AUTO_TEST_CASE(non_overlapping_filtered_costs)
{
char const* sourceCode = R"(
contract test {
bytes x;
function f(uint a) returns (uint b) {
x.length = a;
for (; a < 200; ++a) {
x[a] = 9;
b = a * a;
}
return f(a - 1);
}
}
)";
compile(sourceCode);
for (auto first = m_gasCosts.cbegin(); first != m_gasCosts.cend(); ++first)
{
auto second = first;
for (++second; second != m_gasCosts.cend(); ++second)
if (first->first->location().intersects(second->first->location()))
{
BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!");
auto scannerFromSource = [&](string const&) -> Scanner const& { return m_compiler.scanner(); };
SourceReferenceFormatter::printSourceLocation(cout, &first->first->location(), scannerFromSource);
SourceReferenceFormatter::printSourceLocation(cout, &second->first->location(), scannerFromSource);
}
}
}
BOOST_AUTO_TEST_CASE(simple_contract)
{
// Tests a simple "deploy contract" code without constructor. The actual contract is not relevant.
char const* sourceCode = R"(
contract test {
bytes32 public shaValue;
function f(uint a) {
shaValue = sha3(a);
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(store_sha3)
{
char const* sourceCode = R"(
contract test {
bytes32 public shaValue;
function test(uint a) {
shaValue = sha3(a);
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(updating_store)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function test() {
data = 1;
data = 2;
data2 = 0;
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(branches)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) {
if (x > 7)
data2 = 1;
else
data = 1;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
}
BOOST_AUTO_TEST_CASE(function_calls)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) {
if (x > 7)
data2 = g(x**8) + 1;
else
data = 1;
}
function g(uint x) internal returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
}
BOOST_AUTO_TEST_CASE(multiple_external_functions)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) {
if (x > 7)
data2 = g(x**8) + 1;
else
data = 1;
}
function g(uint x) returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
testRunTimeGas("g(uint256)", vector<bytes>{encodeArgs(2)});
}
BOOST_AUTO_TEST_SUITE_END()
}
}
}
<|endoftext|> |
<commit_before><commit_msg>[libcxx] [test] Allow a standard library that implements LWG 1203 in istream.rvalue/rvalue.pass.cpp<commit_after><|endoftext|> |
<commit_before>/* =======================================================================
Copyright (c) 2010, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
license: MIT (X11), see file LICENSE in the ViennaGrid base directory
======================================================================= */
/************** All the code for a generic Point-Object ********************/
#ifndef VIENNAGRID_POINT_HPP
#define VIENNAGRID_POINT_HPP
#include <math.h>
#include "viennagrid/forwards.h"
namespace viennagrid
{
/***************************** Point Type ************************/
template <typename CoordType, dim_type d>
struct point_filler;
template <typename CoordType>
struct point_filler<CoordType, 1>
{
static void apply(CoordType * coords, CoordType x, CoordType y, CoordType z)
{
coords[0] = x;
}
};
template <typename CoordType>
struct point_filler<CoordType, 2>
{
static void apply(CoordType * coords, CoordType x, CoordType y, CoordType z)
{
coords[0] = x;
coords[1] = y;
}
};
template <typename CoordType>
struct point_filler<CoordType, 3>
{
static void apply(CoordType * coords, CoordType x, CoordType y, CoordType z)
{
coords[0] = x;
coords[1] = y;
coords[2] = z;
}
};
template <typename CoordType, dim_type d, typename CoordinateSystem>
class point
{
public:
typedef CoordType value_type;
point() {}
point(CoordType x, CoordType y = 0, CoordType z = 0)
{
point_filler<CoordType, d>::apply(coords, x, y, z);
}
CoordType & operator[](dim_type index) { return coords[index]; }
CoordType const & operator[](dim_type index) const { return coords[index]; }
CoordType at(dim_type index)
{
if (index < 0 || index >= d)
throw "out of bounds!";
return coords[index];
}
CoordType const & at(dim_type index) const
{
if (index < 0 || index >= d)
throw "out of bounds!";
return coords[index];
}
dim_type size() const { return d; }
//
// operators:
//
//with point:
point operator+(point const & other) const
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] + other[i];
return ret;
}
point & operator+=(point const & other)
{
for (dim_type i=0; i<d; ++i)
coords[i] += other[i];
return *this;
}
point operator-(point const & other) const
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] - other[i];
return ret;
}
point & operator-=(point const & other)
{
for (dim_type i=0; i<d; ++i)
coords[i] -= other[i];
return *this;
}
//with CoordType
point & operator*=(CoordType factor)
{
for (dim_type i=0; i<d; ++i)
coords[i] *= factor;
return *this;
}
point & operator/=(CoordType factor)
{
for (dim_type i=0; i<d; ++i)
coords[i] /= factor;
return *this;
}
point operator*(CoordType factor)
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] * factor;
return ret;
}
point operator/(CoordType factor)
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] / factor;
return ret;
}
private:
CoordType coords[d];
};
template <typename CoordType, dim_type d, typename CoordinateSystem>
std::ostream& operator << (std::ostream & os, point<CoordType, d, CoordinateSystem> const & p)
{
for (dim_type i=0; i<d; ++i)
os << p[i] << ", ";
os << std::endl;
return os;
}
}
#endif
<commit_msg>revisited point stream operator: removed ',' after each point component and the newline<commit_after>/* =======================================================================
Copyright (c) 2010, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
license: MIT (X11), see file LICENSE in the ViennaGrid base directory
======================================================================= */
/************** All the code for a generic Point-Object ********************/
#ifndef VIENNAGRID_POINT_HPP
#define VIENNAGRID_POINT_HPP
#include <math.h>
#include "viennagrid/forwards.h"
namespace viennagrid
{
/***************************** Point Type ************************/
template <typename CoordType, dim_type d>
struct point_filler;
template <typename CoordType>
struct point_filler<CoordType, 1>
{
static void apply(CoordType * coords, CoordType x, CoordType y, CoordType z)
{
coords[0] = x;
}
};
template <typename CoordType>
struct point_filler<CoordType, 2>
{
static void apply(CoordType * coords, CoordType x, CoordType y, CoordType z)
{
coords[0] = x;
coords[1] = y;
}
};
template <typename CoordType>
struct point_filler<CoordType, 3>
{
static void apply(CoordType * coords, CoordType x, CoordType y, CoordType z)
{
coords[0] = x;
coords[1] = y;
coords[2] = z;
}
};
template <typename CoordType, dim_type d, typename CoordinateSystem>
class point
{
public:
typedef CoordType value_type;
point() {}
point(CoordType x, CoordType y = 0, CoordType z = 0)
{
point_filler<CoordType, d>::apply(coords, x, y, z);
}
CoordType & operator[](dim_type index) { return coords[index]; }
CoordType const & operator[](dim_type index) const { return coords[index]; }
CoordType at(dim_type index)
{
if (index < 0 || index >= d)
throw "out of bounds!";
return coords[index];
}
CoordType const & at(dim_type index) const
{
if (index < 0 || index >= d)
throw "out of bounds!";
return coords[index];
}
dim_type size() const { return d; }
//
// operators:
//
//with point:
point operator+(point const & other) const
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] + other[i];
return ret;
}
point & operator+=(point const & other)
{
for (dim_type i=0; i<d; ++i)
coords[i] += other[i];
return *this;
}
point operator-(point const & other) const
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] - other[i];
return ret;
}
point & operator-=(point const & other)
{
for (dim_type i=0; i<d; ++i)
coords[i] -= other[i];
return *this;
}
//with CoordType
point & operator*=(CoordType factor)
{
for (dim_type i=0; i<d; ++i)
coords[i] *= factor;
return *this;
}
point & operator/=(CoordType factor)
{
for (dim_type i=0; i<d; ++i)
coords[i] /= factor;
return *this;
}
point operator*(CoordType factor)
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] * factor;
return ret;
}
point operator/(CoordType factor)
{
point ret;
for (dim_type i=0; i<d; ++i)
ret[i] = coords[i] / factor;
return ret;
}
private:
CoordType coords[d];
};
template <typename CoordType, dim_type d, typename CoordinateSystem>
std::ostream& operator << (std::ostream & os, point<CoordType, d, CoordinateSystem> const & p)
{
for (dim_type i=0; i<d; ++i)
os << p[i] << " ";
return os;
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __VARIABLES_H
#define __VARIABLES_H
#include "mozartcore.hh"
#ifndef MOZART_GENERATOR
namespace mozart {
//////////////
// Variable //
//////////////
#include "Variable-implem.hh"
Implementation<Variable>::Implementation(VM vm, GR gr, Self from):
WithHome(vm, gr, from->home()) {
for (auto iter = from->pendings.begin();
iter != from->pendings.end();
++iter) {
pendings.push_back(vm, *iter);
gr->copyStableRef(pendings.back(), pendings.back());
}
}
OpResult Implementation<Variable>::wakeUp(Self self, VM vm) {
UnstableNode temp = SmallInt::build(vm, 0); // TODO Replace by unit
return bind(self, vm, temp);
}
bool Implementation<Variable>::shouldWakeUpUnderSpace(VM vm, Space* space) {
return home()->isAncestor(space);
}
void Implementation<Variable>::addToSuspendList(Self self, VM vm,
RichNode variable) {
pendings.push_back(vm, variable.getStableRef(vm));
}
void Implementation<Variable>::markNeeded(Self self, VM vm) {
// TODO What's supposed to happen if we're in a subspace?
if (!_needed) {
_needed = true;
wakeUpPendings(vm);
}
}
OpResult Implementation<Variable>::bind(Self self, VM vm, RichNode src) {
if (vm->isOnTopLevel()) {
// The simple, fast binding when on top-level
RichNode(self).reinit(vm, src);
/* If the value we were bound to is a Variable too, we have to transfer the
* variables waiting for this so that they wait for the other Variable.
* Otherwise, we wake up the variables.
*/
src.update();
if (src.is<Variable>()) {
src.as<Variable>().transferPendings(vm, pendings);
} else {
wakeUpPendings(vm);
}
return OpResult::proceed();
} else {
// The complicated, slow binding when in a subspace
return bindSubSpace(self, vm, src);
}
}
OpResult Implementation<Variable>::bindSubSpace(Self self, VM vm,
RichNode src) {
Space* currentSpace = vm->getCurrentSpace();
// Is it a speculative binding?
if (home() != currentSpace) {
currentSpace->makeBackupForSpeculativeBinding(
RichNode(self).getStableRef(vm));
}
// Actual binding
RichNode(self).reinit(vm, src);
/* If the value we were bound to is a Variable too, we have to transfer the
* variables waiting for this so that they wait for the other Variable.
* Otherwise, we wake up the variables.
*/
src.update();
if (src.is<Variable>()) {
src.as<Variable>().transferPendingsSubSpace(vm, currentSpace, pendings);
} else {
wakeUpPendingsSubSpace(vm, currentSpace);
}
return OpResult::proceed();
}
void Implementation<Variable>::transferPendings(
VM vm, VMAllocatedList<StableNode*>& src) {
pendings.splice(vm, src);
}
void Implementation<Variable>::transferPendingsSubSpace(
VM vm, Space* currentSpace, VMAllocatedList<StableNode*>& src) {
for (auto iter = src.removable_begin();
iter != src.removable_end(); ) {
if (Wakeable(**iter).shouldWakeUpUnderSpace(vm, currentSpace))
pendings.splice(vm, src, iter);
else
++iter;
}
}
void Implementation<Variable>::wakeUpPendings(VM vm) {
VMAllocatedList<StableNode*> pendings;
std::swap(pendings, this->pendings);
for (auto iter = pendings.begin();
iter != pendings.end(); iter++) {
Wakeable(**iter).wakeUp(vm);
}
pendings.clear(vm);
}
void Implementation<Variable>::wakeUpPendingsSubSpace(VM vm,
Space* currentSpace) {
/* The general idea here is to wake up things whose home space is the current
* space or any of its children, but not the others.
*/
VMAllocatedList<StableNode*> pendings;
std::swap(pendings, this->pendings);
for (auto iter = pendings.begin();
iter != pendings.end(); iter++) {
Wakeable pending = **iter;
if (pending.shouldWakeUpUnderSpace(vm, currentSpace))
pending.wakeUp(vm);
}
pendings.clear(vm);
}
/////////////
// Unbound //
/////////////
#include "Unbound-implem.hh"
void Implementation<Unbound>::build(SpaceRef& self, VM vm, GR gr, Self from) {
gr->copySpace(self, from.get().home());
}
void Implementation<Unbound>::addToSuspendList(Self self, VM vm,
RichNode variable) {
self.remake<Variable>(vm);
DataflowVariable(self).addToSuspendList(vm, variable);
}
void Implementation<Unbound>::markNeeded(Self self, VM vm) {
self.remake<Variable>(vm);
DataflowVariable(self).markNeeded(vm);
}
OpResult Implementation<Unbound>::bind(Self self, VM vm, RichNode src) {
// Is it a speculative binding?
Space* currentSpace = vm->getCurrentSpace();
if (home() != currentSpace) {
currentSpace->makeBackupForSpeculativeBinding(
RichNode(self).getStableRef(vm));
}
// Actual binding
RichNode(self).reinit(vm, src);
return OpResult::proceed();
}
//////////////
// ReadOnly //
//////////////
#include "ReadOnly-implem.hh"
void Implementation<ReadOnly>::build(StableNode*& self, VM vm, GR gr,
Self from) {
gr->copyStableRef(self, from.get().getUnderlying());
}
OpResult Implementation<ReadOnly>::wakeUp(Self self, VM vm) {
RichNode underlying = *_underlying;
// TODO Test on something more generic than Variable and Unbound
if (underlying.is<Variable>() || underlying.is<Unbound>()) {
// Aaah, no. I was waken up for nothing
DataflowVariable(underlying).addToSuspendList(vm, self);
} else {
RichNode(self).reinit(vm, underlying);
}
return OpResult::proceed();
}
bool Implementation<ReadOnly>::shouldWakeUpUnderSpace(VM vm, Space* space) {
return true;
}
void Implementation<ReadOnly>::addToSuspendList(Self self, VM vm,
RichNode variable) {
DataflowVariable(*_underlying).addToSuspendList(vm, variable);
}
bool Implementation<ReadOnly>::isNeeded(VM vm) {
return DataflowVariable(*_underlying).isNeeded(vm);
}
void Implementation<ReadOnly>::markNeeded(Self self, VM vm) {
DataflowVariable(*_underlying).markNeeded(vm);
}
OpResult Implementation<ReadOnly>::bind(Self self, VM vm, RichNode src) {
return OpResult::waitFor(vm, *_underlying);
}
/////////////////
// FailedValue //
/////////////////
#include "FailedValue-implem.hh"
void Implementation<FailedValue>::build(StableNode*& self, VM vm, GR gr,
Self from) {
gr->copyStableRef(self, from.get().getUnderlying());
}
OpResult Implementation<FailedValue>::raiseUnderlying(VM vm) {
return OpResult::raise(vm, *_underlying);
}
void Implementation<FailedValue>::addToSuspendList(Self self, VM vm,
RichNode variable) {
assert(false);
}
bool Implementation<FailedValue>::isNeeded(VM vm) {
return true;
}
void Implementation<FailedValue>::markNeeded(Self self, VM vm) {
// Nothing to do
}
OpResult Implementation<FailedValue>::bind(Self self, VM vm, RichNode src) {
return raiseUnderlying(vm);
}
}
#endif // MOZART_GENERATOR
#endif // __VARIABLES_H
<commit_msg>Slight performance gain in checking for speculative bindings.<commit_after>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __VARIABLES_H
#define __VARIABLES_H
#include "mozartcore.hh"
#ifndef MOZART_GENERATOR
namespace mozart {
//////////////
// Variable //
//////////////
#include "Variable-implem.hh"
Implementation<Variable>::Implementation(VM vm, GR gr, Self from):
WithHome(vm, gr, from->home()) {
for (auto iter = from->pendings.begin();
iter != from->pendings.end();
++iter) {
pendings.push_back(vm, *iter);
gr->copyStableRef(pendings.back(), pendings.back());
}
}
OpResult Implementation<Variable>::wakeUp(Self self, VM vm) {
UnstableNode temp = SmallInt::build(vm, 0); // TODO Replace by unit
return bind(self, vm, temp);
}
bool Implementation<Variable>::shouldWakeUpUnderSpace(VM vm, Space* space) {
return home()->isAncestor(space);
}
void Implementation<Variable>::addToSuspendList(Self self, VM vm,
RichNode variable) {
pendings.push_back(vm, variable.getStableRef(vm));
}
void Implementation<Variable>::markNeeded(Self self, VM vm) {
// TODO What's supposed to happen if we're in a subspace?
if (!_needed) {
_needed = true;
wakeUpPendings(vm);
}
}
OpResult Implementation<Variable>::bind(Self self, VM vm, RichNode src) {
if (vm->isOnTopLevel()) {
// The simple, fast binding when on top-level
RichNode(self).reinit(vm, src);
/* If the value we were bound to is a Variable too, we have to transfer the
* variables waiting for this so that they wait for the other Variable.
* Otherwise, we wake up the variables.
*/
src.update();
if (src.is<Variable>()) {
src.as<Variable>().transferPendings(vm, pendings);
} else {
wakeUpPendings(vm);
}
return OpResult::proceed();
} else {
// The complicated, slow binding when in a subspace
return bindSubSpace(self, vm, src);
}
}
OpResult Implementation<Variable>::bindSubSpace(Self self, VM vm,
RichNode src) {
Space* currentSpace = vm->getCurrentSpace();
// Is it a speculative binding?
if (!vm->isOnTopLevel() && (home() != currentSpace)) {
currentSpace->makeBackupForSpeculativeBinding(
RichNode(self).getStableRef(vm));
}
// Actual binding
RichNode(self).reinit(vm, src);
/* If the value we were bound to is a Variable too, we have to transfer the
* variables waiting for this so that they wait for the other Variable.
* Otherwise, we wake up the variables.
*/
src.update();
if (src.is<Variable>()) {
src.as<Variable>().transferPendingsSubSpace(vm, currentSpace, pendings);
} else {
wakeUpPendingsSubSpace(vm, currentSpace);
}
return OpResult::proceed();
}
void Implementation<Variable>::transferPendings(
VM vm, VMAllocatedList<StableNode*>& src) {
pendings.splice(vm, src);
}
void Implementation<Variable>::transferPendingsSubSpace(
VM vm, Space* currentSpace, VMAllocatedList<StableNode*>& src) {
for (auto iter = src.removable_begin();
iter != src.removable_end(); ) {
if (Wakeable(**iter).shouldWakeUpUnderSpace(vm, currentSpace))
pendings.splice(vm, src, iter);
else
++iter;
}
}
void Implementation<Variable>::wakeUpPendings(VM vm) {
VMAllocatedList<StableNode*> pendings;
std::swap(pendings, this->pendings);
for (auto iter = pendings.begin();
iter != pendings.end(); iter++) {
Wakeable(**iter).wakeUp(vm);
}
pendings.clear(vm);
}
void Implementation<Variable>::wakeUpPendingsSubSpace(VM vm,
Space* currentSpace) {
/* The general idea here is to wake up things whose home space is the current
* space or any of its children, but not the others.
*/
VMAllocatedList<StableNode*> pendings;
std::swap(pendings, this->pendings);
for (auto iter = pendings.begin();
iter != pendings.end(); iter++) {
Wakeable pending = **iter;
if (pending.shouldWakeUpUnderSpace(vm, currentSpace))
pending.wakeUp(vm);
}
pendings.clear(vm);
}
/////////////
// Unbound //
/////////////
#include "Unbound-implem.hh"
void Implementation<Unbound>::build(SpaceRef& self, VM vm, GR gr, Self from) {
gr->copySpace(self, from.get().home());
}
void Implementation<Unbound>::addToSuspendList(Self self, VM vm,
RichNode variable) {
self.remake<Variable>(vm);
DataflowVariable(self).addToSuspendList(vm, variable);
}
void Implementation<Unbound>::markNeeded(Self self, VM vm) {
self.remake<Variable>(vm);
DataflowVariable(self).markNeeded(vm);
}
OpResult Implementation<Unbound>::bind(Self self, VM vm, RichNode src) {
// Is it a speculative binding?
if (!vm->isOnTopLevel()) {
Space* currentSpace = vm->getCurrentSpace();
if (home() != currentSpace) {
currentSpace->makeBackupForSpeculativeBinding(
RichNode(self).getStableRef(vm));
}
}
// Actual binding
RichNode(self).reinit(vm, src);
return OpResult::proceed();
}
//////////////
// ReadOnly //
//////////////
#include "ReadOnly-implem.hh"
void Implementation<ReadOnly>::build(StableNode*& self, VM vm, GR gr,
Self from) {
gr->copyStableRef(self, from.get().getUnderlying());
}
OpResult Implementation<ReadOnly>::wakeUp(Self self, VM vm) {
RichNode underlying = *_underlying;
// TODO Test on something more generic than Variable and Unbound
if (underlying.is<Variable>() || underlying.is<Unbound>()) {
// Aaah, no. I was waken up for nothing
DataflowVariable(underlying).addToSuspendList(vm, self);
} else {
RichNode(self).reinit(vm, underlying);
}
return OpResult::proceed();
}
bool Implementation<ReadOnly>::shouldWakeUpUnderSpace(VM vm, Space* space) {
return true;
}
void Implementation<ReadOnly>::addToSuspendList(Self self, VM vm,
RichNode variable) {
DataflowVariable(*_underlying).addToSuspendList(vm, variable);
}
bool Implementation<ReadOnly>::isNeeded(VM vm) {
return DataflowVariable(*_underlying).isNeeded(vm);
}
void Implementation<ReadOnly>::markNeeded(Self self, VM vm) {
DataflowVariable(*_underlying).markNeeded(vm);
}
OpResult Implementation<ReadOnly>::bind(Self self, VM vm, RichNode src) {
return OpResult::waitFor(vm, *_underlying);
}
/////////////////
// FailedValue //
/////////////////
#include "FailedValue-implem.hh"
void Implementation<FailedValue>::build(StableNode*& self, VM vm, GR gr,
Self from) {
gr->copyStableRef(self, from.get().getUnderlying());
}
OpResult Implementation<FailedValue>::raiseUnderlying(VM vm) {
return OpResult::raise(vm, *_underlying);
}
void Implementation<FailedValue>::addToSuspendList(Self self, VM vm,
RichNode variable) {
assert(false);
}
bool Implementation<FailedValue>::isNeeded(VM vm) {
return true;
}
void Implementation<FailedValue>::markNeeded(Self self, VM vm) {
// Nothing to do
}
OpResult Implementation<FailedValue>::bind(Self self, VM vm, RichNode src) {
return raiseUnderlying(vm);
}
}
#endif // MOZART_GENERATOR
#endif // __VARIABLES_H
<|endoftext|> |
<commit_before>#include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include "dict.h"
typedef std::unordered_map<std::string, std::string> Dict;
typedef unsigned long IdentificatorType;
// consider map<unsigned long, unordered_map>
std::map<IdentificatorType, Dict> dictionaries;
IdentificatorType dictCounter = 0;
IdentificatorType dict_new() {
dictionaries.insert(std::pair<IdentificatorType, Dict>(++dictCounter, Dict()));
return dictCounter;
}
void dict_remove(IdentificatorType id, const char* key) {
// maybe special version for dictglobal
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
dictionaryIt->second.erase(key);
}
}
const char* dict_find(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
auto stringIt = dictionaryIt->second.find(key);
if (stringIt != dictionaryIt->second.end()) {
return stringIt->second.c_str();
}
}
/*
if (there exists value under key in global dictionary) {
return that value
}
*/
return NULL;
}
void dict_clear(IdentificatorType id) {
// maybe special version for dictglobal
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
dictionaryIt->second.clear();
}
}
void dict_copy(IdentificatorType src_id, IdentificatorType dst_id) {
auto srcDictionaryIt = dictionaries.find(src_id);
auto dstDictionaryIt = dictionaries.find(dst_id);
if (srcDictionaryIt != dictionaries.end() &&
dstDictionaryIt != dictionaries.end()) {
// do not copy if destination dictionary is dictglobal and amount of keys exceeds size
// copy contents
}
}<commit_msg>Added dictglobal handling in several methods<commit_after>#include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include "dict.h"
typedef std::unordered_map<std::string, std::string> Dict;
typedef unsigned long IdentificatorType;
// consider map<unsigned long, unordered_map>
// somehow initialize the dictglobal
std::map<IdentificatorType, Dict> dictionaries;
IdentificatorType dictCounter = 0;
IdentificatorType dict_new() {
dictionaries.insert(std::pair<IdentificatorType, Dict>(++dictCounter, Dict()));
return dictCounter;
}
void dict_remove(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
dictionaryIt->second.erase(key);
}
}
const char* dict_find(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
auto stringIt = dictionaryIt->second.find(key);
if (stringIt != dictionaryIt->second.end()) {
return stringIt->second.c_str();
}
}
auto stringIt = dictionaries.at(0).find(key);
if (stringIt != dictionaries.at(0).end()) {
return stringIt->second.c_str();
}
return NULL;
}
void dict_clear(IdentificatorType id) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
dictionaryIt->second.clear();
}
}
void dict_copy(IdentificatorType src_id, IdentificatorType dst_id) {
auto srcDictionaryIt = dictionaries.find(src_id);
auto dstDictionaryIt = dictionaries.find(dst_id);
if (srcDictionaryIt != dictionaries.end() &&
dstDictionaryIt != dictionaries.end()) {
// do not copy if destination dictionary is dictglobal and amount of keys exceeds size
// copy contents
}
}<|endoftext|> |
<commit_before>#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include "dict.h"
#include "dictglobal.h"
using Dict = std::unordered_map<std::string, std::string>;
using IdentifierType = unsigned long;
namespace jnp1 {
namespace {
#ifdef NDEBUG
const bool debug = false;
#else
const bool debug = true;
#endif
IdentifierType dictCounter = 0;
std::map<IdentifierType, Dict>& dicts() {
static std::map<IdentifierType, Dict> dicts;
return dicts;
}
std::string parse_char_param(const char* param) {
if (param != NULL) {
std::string paramStr(param);
return "\"" + paramStr + "\"";
}
else
return "NULL";
}
void function_called_msg(std::string funcName,
std::string params) {
if (debug)
std::cerr << funcName << "(" << params << ")" << std::endl;
}
void dict_new_msg(IdentifierType id) {
if (debug)
std::cerr << "dict_new: dict " << id
<< " has been created" << std::endl;
}
void dict_delete_success_msg(IdentifierType id) {
if (debug)
std::cerr << "dict_delete: dict " << id
<< " has been deleted" << std::endl;
}
void dict_delete_error_msg() {
if (debug)
std::cerr << "dict_delete: an attempt to remove the Global Dictionary"
<< std::endl;
}
void dict_description_msg(IdentifierType id) {
if (debug) {
if (id != dict_global())
std::cerr << "dict " << id;
else
std::cerr << "the Global Dictionary";
}
}
void dict_size_msg(IdentifierType id, size_t size) {
if (debug) {
std::cerr << "dict_size: ";
dict_description_msg(id);
std::cerr << " contains " << size << " element(s)" << std::endl;
}
}
void dict_insert_global_dict_msg() {
if (debug)
std::cerr << "dict_insert: attempt to overfill the Global Dictionary" << std::endl;
}
void dict_insert_success_msg(IdentifierType id,
std::string key,
std::string value) {
if (debug) {
std::cerr << "dict_insert: ";
dict_description_msg(id);
std::cerr << ", the pair (" << key << ", " << value << ")"
<< " has been inserted" << std::endl;
}
}
void dict_insert_error_msg(IdentifierType id, std::string param) {
if (debug)
std::cerr << "dict_insert: dict " << id
<< " an attempt to insert NULL " << param << std::endl;
}
void dict_not_found_msg(std::string funcName, IdentifierType id) {
if (debug)
std::cerr << funcName << ": dict " << id << " does not exist" << "\n";
}
void key_not_found_msg(std::string funcName,
IdentifierType id,
const char* key) {
if (debug)
std::cerr << funcName << ": dict " << id
<< " does not contain the key \"" << key << "\"\n";
}
void key_removed_msg(std::string funcName,
IdentifierType id,
const char* key) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(id);
std::cerr << " , the key \"" << key
<< "\" has been removed" << std::endl;
}
}
void value_found_msg(std::string funcName,
IdentifierType id,
const char* key,
std::string value) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(id);
std::cerr << ", the key \"" << key
<< "\" has the value \"" << value
<< "\"" << std::endl;
}
}
void dict_copied_msg(std::string funcName,
IdentifierType src_id,
IdentifierType dst_id) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(src_id);
std::cerr << " has been copied into ";
dict_description_msg(dst_id);
std::cerr << std::endl;
}
}
void search_global_dict_msg(std::string funcName) {
if (debug)
std::cerr << funcName << ": looking up the Global Dictionary\n";
}
void dict_cleared_msg(std::string funcName, IdentifierType id) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(id);
std::cerr << " has been cleared" << std::endl;
}
}
}
IdentifierType dict_new() {
function_called_msg("dict_new", "");
dicts().insert(std::make_pair(dictCounter, Dict()));
dict_new_msg(dictCounter);
return dictCounter++;
}
void dict_delete(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_delete", ss.str());
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
if (id == dict_global()) {
dict_delete_error_msg();
}
else {
dicts().erase(id);
dict_delete_success_msg(id);
}
}
}
size_t dict_size(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_size", ss.str());
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
size_t dictSize = dictionaryIt->second.size();
dict_size_msg(id, dictSize);
return dictSize;
}
else {
dict_not_found_msg("dict_size", id);
return 0;
}
}
void dict_insert(unsigned long id, const char* key, const char* value) {
std::stringstream ss;
const std::string keyDescription = parse_char_param(key);
const std::string valueDescription = parse_char_param(value);
ss << id << ", " << keyDescription << ", " << valueDescription;
function_called_msg("dict_insert", ss.str());
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
if (key == NULL) {
dict_insert_error_msg(id, "key");
}
else if (value == NULL) {
dict_insert_error_msg(id, "value");
}
else {
IdentifierType globalDictId = dict_global();
if ((id == globalDictId)
&& (dict_size(globalDictId) == MAX_GLOBAL_DICT_SIZE)) {
dict_insert_global_dict_msg();
return;
}
const std::string keyStr(key);
const std::string valueStr(value);
Dict& dict = dictionaryIt->second;
auto dictIt = dict.find(keyStr);
if (dictIt != dict.end())
dictIt->second = valueStr;
else
dict.insert(std::make_pair(keyStr, valueStr));
dict_insert_success_msg(id, keyDescription, valueDescription);
}
}
else
dict_not_found_msg("dict_insert", id);
}
void dict_remove(IdentifierType id, const char* key) {
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
if (dictionaryIt->second.erase(key) > 0) {
key_removed_msg("dict_remove", id, key);
}
else
key_not_found_msg("dict_remove", id, key);
}
else
dict_not_found_msg("dict_remove", id);
}
const char* dict_find(IdentifierType id, const char* key) {
if (key == NULL) {
return NULL;
}
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
const Dict& dict = dictionaryIt->second;
const auto stringIt = dict.find(key);
if (stringIt != dict.end()) {
const std::string value = stringIt->second;
value_found_msg("dict_find", id, key, value);
return value.c_str();
}
else
key_not_found_msg("dict_find", id, key);
}
else
dict_not_found_msg("dict_find", id);
if (id != dict_global()) {
search_global_dict_msg("dict_find");
return dict_find(dict_global(), key);
}
return NULL;
}
void dict_clear(IdentifierType id) {
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
dictionaryIt->second.clear();
dict_cleared_msg("dict_clear", id);
}
else
dict_not_found_msg("dict_clear", id);
}
void dict_copy(IdentifierType src_id, IdentifierType dst_id) {
if (src_id == dst_id)
return;
const auto srcDictionaryIt = dicts().find(src_id);
const auto dstDictionaryIt = dicts().find(dst_id);
if (srcDictionaryIt != dicts().end() &&
dstDictionaryIt != dicts().end()) {
Dict& srcDict = srcDictionaryIt->second;
Dict& dstDict = dstDictionaryIt->second;
const bool isGlobalDict = dst_id == dict_global();
for (auto srcIt = srcDict.begin(); srcIt != srcDict.end(); ++srcIt) {
std::string srcKey = srcIt->first;
std::string srcValue = srcIt->second;
auto dstIt = dstDict.find(srcKey);
if (dstIt != dstDict.end())
dstIt->second = srcValue;
else {
dstDict.insert(make_pair(srcKey, srcValue));
if (isGlobalDict
&& (dstDict.size() == MAX_GLOBAL_DICT_SIZE))
break;
}
}
dict_copied_msg("dict_copy", src_id, dst_id);
}
else if (srcDictionaryIt != dicts().end())
dict_not_found_msg("dict_copy", src_id);
else
dict_not_found_msg("dict_copy", dst_id);
}
}<commit_msg>Added checking for nullptr in dict_remove<commit_after>#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include "dict.h"
#include "dictglobal.h"
using Dict = std::unordered_map<std::string, std::string>;
using IdentifierType = unsigned long;
namespace jnp1 {
namespace {
#ifdef NDEBUG
const bool debug = false;
#else
const bool debug = true;
#endif
IdentifierType dictCounter = 0;
std::map<IdentifierType, Dict>& dicts() {
static std::map<IdentifierType, Dict> dicts;
return dicts;
}
std::string parse_char_param(const char* param) {
if (param != NULL) {
std::string paramStr(param);
return "\"" + paramStr + "\"";
}
else
return "NULL";
}
void function_called_msg(std::string funcName,
std::string params) {
if (debug)
std::cerr << funcName << "(" << params << ")" << std::endl;
}
void dict_new_msg(IdentifierType id) {
if (debug)
std::cerr << "dict_new: dict " << id
<< " has been created" << std::endl;
}
void dict_delete_success_msg(IdentifierType id) {
if (debug)
std::cerr << "dict_delete: dict " << id
<< " has been deleted" << std::endl;
}
void dict_delete_error_msg() {
if (debug)
std::cerr << "dict_delete: an attempt to remove the Global Dictionary"
<< std::endl;
}
void dict_description_msg(IdentifierType id) {
if (debug) {
if (id != dict_global())
std::cerr << "dict " << id;
else
std::cerr << "the Global Dictionary";
}
}
void dict_size_msg(IdentifierType id, size_t size) {
if (debug) {
std::cerr << "dict_size: ";
dict_description_msg(id);
std::cerr << " contains " << size << " element(s)" << std::endl;
}
}
void dict_insert_global_dict_msg() {
if (debug)
std::cerr << "dict_insert: attempt to overfill the Global Dictionary" << std::endl;
}
void dict_insert_success_msg(IdentifierType id,
std::string key,
std::string value) {
if (debug) {
std::cerr << "dict_insert: ";
dict_description_msg(id);
std::cerr << ", the pair (" << key << ", " << value << ")"
<< " has been inserted" << std::endl;
}
}
void dict_insert_error_msg(IdentifierType id, std::string param) {
if (debug)
std::cerr << "dict_insert: dict " << id
<< " an attempt to insert NULL " << param << std::endl;
}
void dict_not_found_msg(std::string funcName, IdentifierType id) {
if (debug)
std::cerr << funcName << ": dict " << id << " does not exist" << "\n";
}
void key_not_found_msg(std::string funcName,
IdentifierType id,
const char* key) {
if (debug)
std::cerr << funcName << ": dict " << id
<< " does not contain the key \"" << key << "\"\n";
}
void key_removed_msg(std::string funcName,
IdentifierType id,
const char* key) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(id);
std::cerr << " , the key \"" << key
<< "\" has been removed" << std::endl;
}
}
void value_found_msg(std::string funcName,
IdentifierType id,
const char* key,
std::string value) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(id);
std::cerr << ", the key \"" << key
<< "\" has the value \"" << value
<< "\"" << std::endl;
}
}
void dict_copied_msg(std::string funcName,
IdentifierType src_id,
IdentifierType dst_id) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(src_id);
std::cerr << " has been copied into ";
dict_description_msg(dst_id);
std::cerr << std::endl;
}
}
void search_global_dict_msg(std::string funcName) {
if (debug)
std::cerr << funcName << ": looking up the Global Dictionary\n";
}
void dict_cleared_msg(std::string funcName, IdentifierType id) {
if (debug) {
std::cerr << funcName << ": ";
dict_description_msg(id);
std::cerr << " has been cleared" << std::endl;
}
}
}
IdentifierType dict_new() {
function_called_msg("dict_new", "");
dicts().insert(std::make_pair(dictCounter, Dict()));
dict_new_msg(dictCounter);
return dictCounter++;
}
void dict_delete(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_delete", ss.str());
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
if (id == dict_global()) {
dict_delete_error_msg();
}
else {
dicts().erase(id);
dict_delete_success_msg(id);
}
}
}
size_t dict_size(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_size", ss.str());
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
size_t dictSize = dictionaryIt->second.size();
dict_size_msg(id, dictSize);
return dictSize;
}
else {
dict_not_found_msg("dict_size", id);
return 0;
}
}
void dict_insert(unsigned long id, const char* key, const char* value) {
std::stringstream ss;
const std::string keyDescription = parse_char_param(key);
const std::string valueDescription = parse_char_param(value);
ss << id << ", " << keyDescription << ", " << valueDescription;
function_called_msg("dict_insert", ss.str());
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
if (key == NULL) {
dict_insert_error_msg(id, "key");
}
else if (value == NULL) {
dict_insert_error_msg(id, "value");
}
else {
IdentifierType globalDictId = dict_global();
if ((id == globalDictId)
&& (dict_size(globalDictId) == MAX_GLOBAL_DICT_SIZE)) {
dict_insert_global_dict_msg();
return;
}
const std::string keyStr(key);
const std::string valueStr(value);
Dict& dict = dictionaryIt->second;
auto dictIt = dict.find(keyStr);
if (dictIt != dict.end())
dictIt->second = valueStr;
else
dict.insert(std::make_pair(keyStr, valueStr));
dict_insert_success_msg(id, keyDescription, valueDescription);
}
}
else
dict_not_found_msg("dict_insert", id);
}
void dict_remove(IdentifierType id, const char* key) {
// TODO: add error message
if (key == NULL) {
return;
}
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
if (dictionaryIt->second.erase(key) > 0) {
key_removed_msg("dict_remove", id, key);
}
else
key_not_found_msg("dict_remove", id, key);
}
else
dict_not_found_msg("dict_remove", id);
}
const char* dict_find(IdentifierType id, const char* key) {
// TODO: add error message
if (key == NULL) {
return NULL;
}
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
const Dict& dict = dictionaryIt->second;
const auto stringIt = dict.find(key);
if (stringIt != dict.end()) {
const std::string value = stringIt->second;
value_found_msg("dict_find", id, key, value);
return value.c_str();
}
else
key_not_found_msg("dict_find", id, key);
}
else
dict_not_found_msg("dict_find", id);
if (id != dict_global()) {
search_global_dict_msg("dict_find");
return dict_find(dict_global(), key);
}
return NULL;
}
void dict_clear(IdentifierType id) {
const auto dictionaryIt = dicts().find(id);
if (dictionaryIt != dicts().end()) {
dictionaryIt->second.clear();
dict_cleared_msg("dict_clear", id);
}
else
dict_not_found_msg("dict_clear", id);
}
void dict_copy(IdentifierType src_id, IdentifierType dst_id) {
if (src_id == dst_id)
return;
const auto srcDictionaryIt = dicts().find(src_id);
const auto dstDictionaryIt = dicts().find(dst_id);
if (srcDictionaryIt != dicts().end() &&
dstDictionaryIt != dicts().end()) {
Dict& srcDict = srcDictionaryIt->second;
Dict& dstDict = dstDictionaryIt->second;
const bool isGlobalDict = dst_id == dict_global();
for (auto srcIt = srcDict.begin(); srcIt != srcDict.end(); ++srcIt) {
std::string srcKey = srcIt->first;
std::string srcValue = srcIt->second;
auto dstIt = dstDict.find(srcKey);
if (dstIt != dstDict.end())
dstIt->second = srcValue;
else {
dstDict.insert(make_pair(srcKey, srcValue));
if (isGlobalDict
&& (dstDict.size() == MAX_GLOBAL_DICT_SIZE))
break;
}
}
dict_copied_msg("dict_copy", src_id, dst_id);
}
else if (srcDictionaryIt != dicts().end())
dict_not_found_msg("dict_copy", src_id);
else
dict_not_found_msg("dict_copy", dst_id);
}
}<|endoftext|> |
<commit_before>#include "dir.hpp"
namespace spn {
// -------------------------- Dir --------------------------
const char Dir::SC('/'),
Dir::DOT('.'),
Dir::EOS('\0'),
*Dir::SC_P(u8"/"),
Dir::LBK('['),
Dir::RBK(']');
Dir::Dir(Dir&& d): PathBlock(std::move(d)) {}
Dir& Dir::operator = (Dir&& d) {
static_cast<PathBlock&>(*this) = std::move(static_cast<PathBlock&>(d));
return *this;
}
std::string Dir::GetCurrentDir() {
return To8Str(DirDep::GetCurrentDir()).moveTo();
}
std::string Dir::GetProgramDir() {
return To8Str(DirDep::GetProgramDir()).moveTo();
}
void Dir::SetCurrentDir(const std::string& path) {
PathStr ps;
if(path.length() > 1) {
if(::isalpha(path[0]) && path[1] == ':')
ps = ToPathStr(path.substr(2)).moveTo();
} else
ps = ToPathStr(path).moveTo();
DirDep::SetCurrentDir(ps);
}
std::string Dir::ToRegEx(const std::string& s) {
// ワイルドカード記述の置き換え
// * -> ([_ \-\w]+)
// ? -> ([_ \-\w])
// . -> (\.)
// バックスラッシュをスラッシュに置き換え
// \ -> /
boost::regex re[4] = {boost::regex(R"(\\)"), boost::regex(R"(\*)"), boost::regex(R"(\?)"), boost::regex(R"(\.)")};
std::string s2 = boost::regex_replace(s, re[0], R"(/)");
s2 = boost::regex_replace(s2, re[1], R"([_ \\-\\w]+)");
s2 = boost::regex_replace(s2, re[2], R"([_ \\-\\w])");
s2 = boost::regex_replace(s2, re[3], R"(\\.)");
return s2;
}
std::string Dir::setCurrentDir() const {
std::string prev = GetCurrentDir();
SetCurrentDir(plain_utf8());
return prev;
}
Dir::StrList Dir::EnumEntryRegEx(const std::string& r) {
StrList res;
EnumEntryRegEx(r, [&res](const Dir& dir){
res.push_back(dir.plain_utf8());
});
return res;
}
Dir::StrList Dir::EnumEntryWildCard(const std::string& s) {
return EnumEntryRegEx(ToRegEx(s));
}
void Dir::EnumEntryWildCard(const std::string& s, EnumCB cb) {
EnumEntryRegEx(ToRegEx(s), cb);
}
Dir::RegexL Dir::_ParseRegEx(const std::string& r) {
RegexL rl;
auto itr = r.begin(),
itrE = r.end(),
itr0 = itr;
bool bSkip = false;
while(itr != itrE) {
auto c = *itr;
if(bSkip) {
if(c == RBK)
bSkip = false;
} else {
if(c == LBK)
bSkip = true;
else if(c == SC) {
auto diff = itr - itr0;
bool bIgnore = false;
if(diff == 0)
bIgnore = true;
else if(diff >= 2) {
if(*itr0 == '\\' && *(itr0+1) == '.') {
if(diff == 2) {
// セグメントをスキップ
bIgnore = true;
} else if(diff == 4 && (*(itr0+2) == '\\' && *(itr0+3) == '.')) {
// セグメントを1つ戻す
Assert(Trap, !rl.empty())
rl.pop_back();
bIgnore = true;
}
}
}
if(!bIgnore)
rl.emplace_back(itr0, itr);
itr0 = ++itr;
continue;
}
}
++itr;
}
if(itr0 != itr)
rl.emplace_back(itr0, itr);
return rl;
}
void Dir::_EnumEntryRegEx(RegexItr itr, RegexItr itrE, std::string& lpath, size_t baseLen, EnumCB cb) {
if(itr == itrE)
return;
size_t pl = lpath.size();
DirDep::EnumEntry(lpath, [=, &lpath, &cb](const PathCh* name, bool) {
if(name[0]==PathCh(DOT)) {
if(name[1]==PathCh(EOS) || name[1]==PathCh(DOT))
return;
}
std::string s(To8Str(name).moveTo());
boost::smatch m;
if(boost::regex_match(s, m, *itr)) {
if(lpath.back() != SC)
lpath += SC;
lpath += s;
if(DirDep::IsDirectory(ToPathStr(lpath))) {
if(itr+1 != itrE)
_EnumEntryRegEx(itr+1, itrE, lpath, baseLen, cb);
else
cb(Dir(lpath));
} else
cb(Dir(lpath));
lpath.resize(pl);
}
});
}
void Dir::_EnumEntry(const std::string& /*s*/, const std::string& path, EnumCB cb) {
DirDep::EnumEntry(path, [&cb](const PathCh* name, bool /*bDir*/) {
PathStr s(ToPathStr(name).moveTo());
if(s == name)
cb(Dir(s));
});
}
void Dir::EnumEntryRegEx(const std::string& r, EnumCB cb) {
if(r.empty())
return;
std::string path;
// 絶対パスの時は内部パスを無視する
int ofs = 0;
bool bAbs = false;
if(r[0] == '/') {
#ifdef WIN32
Assert(Throw, false, "invalid absolute path")
#endif
path += '/';
ofs = 1;
bAbs = true;
} else if(auto letter = _GetDriveLetter(&r[0], &r[0] + r.length())) {
// windowsの場合のみドライブ文字を出力
#ifdef WIN32
path += *letter;
path += ':';
#else
path += '/';
#endif
ofs = 2;
bAbs = true;
}
if(!bAbs)
path += "./";
try {
RegexL rl = _ParseRegEx(r.substr(ofs));
_EnumEntryRegEx(rl.begin(), rl.end(), path, path.size()+1, cb);
} catch(const boost::regex_error& e) {
// 正規表現に何かエラーがある時は単純に文字列比較とする
_EnumEntry(r, path, cb);
}
}
bool Dir::isFile() const {
return DirDep::IsFile(plain_utf32());
}
bool Dir::isDirectory() const {
return DirDep::IsDirectory(plain_utf32());
}
void Dir::remove() const {
DirDep::Remove(plain_utf32());
}
void Dir::copy(const std::string& to) const {
DirDep::Copy(plain_utf32(), to);
}
void Dir::move(const std::string& to) const {
DirDep::Move(plain_utf32(), to);
}
void Dir::mkdir(uint32_t mode) const {
PathReset preset;
if(isAbsolute())
DirDep::Chdir(SC_P);
mode |= FStatus::UserRWX;
auto path32 = plain_utf32(false);
const char32_t* ptr = &path32[0];
int nsg = segments();
std::string ns;
int i;
// 最初のパスから1つずつ存在確認
for(i=0 ; i<nsg ; i++) {
int seg = _segment[i];
ns = Text::UTFConvertTo8(c32Str(ptr, seg));
ptr += seg+1;
if(!DirDep::Chdir_nt(ns))
break;
}
if(i == nsg)
return;
// パスがファイルだったら失敗とする
Assert(Throw, !DirDep::IsFile(ns), "there is file at the path")
for(;;) {
DirDep::Mkdir(ns, mode);
DirDep::Chdir(ns);
if(++i == nsg)
break;
int seg = _segment[i] + 1;
ns = Text::UTFConvertTo8(c32Str(ptr, seg));
ptr += seg;
}
}
void Dir::_chmod(PathBlock& lpath, ModCB cb) {
DirDep::EnumEntry(lpath.plain_utf32(), [&lpath, this, cb](const PathCh* name, bool) {
lpath <<= name;
if(ChMod(lpath, cb))
_chmod(lpath, cb);
lpath.popBack();
});
}
bool Dir::ChMod(const PathBlock& pb, ModCB cb) {
ToPathStr path = pb.plain_utf32();
FStatus fstat = DirDep::Status(path);
bool bDir = fstat.flag & FStatus::DirectoryType;
if(bDir)
fstat.flag |= FStatus::UserExec;
bool bRecr = cb(pb, fstat);
DirDep::Chmod(path, fstat.flag);
return bDir && bRecr;
}
void Dir::chmod(ModCB cb) {
PathBlock pb(*this);
if(ChMod(pb, cb))
_chmod(pb, cb);
}
void Dir::chmod(uint32_t mode) {
chmod([mode](const PathBlock&, FStatus& fs) {
fs.flag = mode;
return false;
});
}
FILE* Dir::openAsFP(const char* mode) const {
return std::fopen(To8Str(plain_utf32()).getStringPtr(), mode);
}
FStatus Dir::status() const {
return DirDep::Status(plain_utf8());
}
// -------------------------- URI --------------------------
const std::string URI::SEP(u8"://");
const std::u32string URI::SEP32(U"://");
URI::URI() {}
URI::URI(URI&& u): PathBlock(std::move(u)), _type(std::move(u._type)) {}
URI::URI(To8Str p) {
setPath(p);
}
URI::URI(To8Str typ, To8Str path): PathBlock(path), _type(typ.moveTo()) {}
URI::URI(To8Str typ, const PathBlock& pb): PathBlock(pb), _type(typ.moveTo()) {}
URI& URI::operator = (URI&& u) {
static_cast<PathBlock&>(*this) = std::move(u);
_type = std::move(u._type);
return *this;
}
void URI::setPath(To8Str p) {
std::string path(p.moveTo());
boost::regex re("^([\\w\\d_]+)://");
boost::smatch m;
if(boost::regex_search(path, m, re)) {
_type = m.str(1);
PathBlock::setPath(path.substr(m[0].length()));
} else
PathBlock::setPath(std::move(path));
}
const std::string& URI::getType_utf8() const {
return _type;
}
void URI::setType(To8Str typ) {
_type = typ.moveTo();
}
const PathBlock& URI::path() const {
return *this;
}
PathBlock& URI::path() {
return *this;
}
std::string URI::plainUri_utf8() const {
auto ret = _type;
ret.append(SEP);
ret.append(plain_utf8());
return ret;
}
std::u32string URI::plainUri_utf32() const {
auto ret = To32Str(_type).moveTo();
ret.append(SEP32);
ret.append(plain_utf32());
return ret;
}
bool URI::operator == (const URI& u) const {
return _type == u._type
&& static_cast<const PathBlock&>(*this) == u;
}
bool URI::operator != (const URI& u) const {
return !(this->operator == (u));
}
}
<commit_msg>Dir::SetCurrentDirにて相対パスを与えるとDirDep::SetCurrentDirに空文字列がセットされる問題を修正<commit_after>#include "dir.hpp"
namespace spn {
// -------------------------- Dir --------------------------
const char Dir::SC('/'),
Dir::DOT('.'),
Dir::EOS('\0'),
*Dir::SC_P(u8"/"),
Dir::LBK('['),
Dir::RBK(']');
Dir::Dir(Dir&& d): PathBlock(std::move(d)) {}
Dir& Dir::operator = (Dir&& d) {
static_cast<PathBlock&>(*this) = std::move(static_cast<PathBlock&>(d));
return *this;
}
std::string Dir::GetCurrentDir() {
return To8Str(DirDep::GetCurrentDir()).moveTo();
}
std::string Dir::GetProgramDir() {
return To8Str(DirDep::GetProgramDir()).moveTo();
}
void Dir::SetCurrentDir(const std::string& path) {
PathStr ps;
// Windows環境において先頭のドライブ文字を削る
if(path.length() > 1 &&
::isalpha(path[0]) && path[1] == ':')
{
ps = ToPathStr(path.substr(2)).moveTo();
} else
ps = ToPathStr(path).moveTo();
DirDep::SetCurrentDir(ps);
}
std::string Dir::ToRegEx(const std::string& s) {
// ワイルドカード記述の置き換え
// * -> ([_ \-\w]+)
// ? -> ([_ \-\w])
// . -> (\.)
// バックスラッシュをスラッシュに置き換え
// \ -> /
boost::regex re[4] = {boost::regex(R"(\\)"), boost::regex(R"(\*)"), boost::regex(R"(\?)"), boost::regex(R"(\.)")};
std::string s2 = boost::regex_replace(s, re[0], R"(/)");
s2 = boost::regex_replace(s2, re[1], R"([_ \\-\\w]+)");
s2 = boost::regex_replace(s2, re[2], R"([_ \\-\\w])");
s2 = boost::regex_replace(s2, re[3], R"(\\.)");
return s2;
}
std::string Dir::setCurrentDir() const {
std::string prev = GetCurrentDir();
SetCurrentDir(plain_utf8());
return prev;
}
Dir::StrList Dir::EnumEntryRegEx(const std::string& r) {
StrList res;
EnumEntryRegEx(r, [&res](const Dir& dir){
res.push_back(dir.plain_utf8());
});
return res;
}
Dir::StrList Dir::EnumEntryWildCard(const std::string& s) {
return EnumEntryRegEx(ToRegEx(s));
}
void Dir::EnumEntryWildCard(const std::string& s, EnumCB cb) {
EnumEntryRegEx(ToRegEx(s), cb);
}
Dir::RegexL Dir::_ParseRegEx(const std::string& r) {
RegexL rl;
auto itr = r.begin(),
itrE = r.end(),
itr0 = itr;
bool bSkip = false;
while(itr != itrE) {
auto c = *itr;
if(bSkip) {
if(c == RBK)
bSkip = false;
} else {
if(c == LBK)
bSkip = true;
else if(c == SC) {
auto diff = itr - itr0;
bool bIgnore = false;
if(diff == 0)
bIgnore = true;
else if(diff >= 2) {
if(*itr0 == '\\' && *(itr0+1) == '.') {
if(diff == 2) {
// セグメントをスキップ
bIgnore = true;
} else if(diff == 4 && (*(itr0+2) == '\\' && *(itr0+3) == '.')) {
// セグメントを1つ戻す
Assert(Trap, !rl.empty())
rl.pop_back();
bIgnore = true;
}
}
}
if(!bIgnore)
rl.emplace_back(itr0, itr);
itr0 = ++itr;
continue;
}
}
++itr;
}
if(itr0 != itr)
rl.emplace_back(itr0, itr);
return rl;
}
void Dir::_EnumEntryRegEx(RegexItr itr, RegexItr itrE, std::string& lpath, size_t baseLen, EnumCB cb) {
if(itr == itrE)
return;
size_t pl = lpath.size();
DirDep::EnumEntry(lpath, [=, &lpath, &cb](const PathCh* name, bool) {
if(name[0]==PathCh(DOT)) {
if(name[1]==PathCh(EOS) || name[1]==PathCh(DOT))
return;
}
std::string s(To8Str(name).moveTo());
boost::smatch m;
if(boost::regex_match(s, m, *itr)) {
if(lpath.back() != SC)
lpath += SC;
lpath += s;
if(DirDep::IsDirectory(ToPathStr(lpath))) {
if(itr+1 != itrE)
_EnumEntryRegEx(itr+1, itrE, lpath, baseLen, cb);
else
cb(Dir(lpath));
} else
cb(Dir(lpath));
lpath.resize(pl);
}
});
}
void Dir::_EnumEntry(const std::string& /*s*/, const std::string& path, EnumCB cb) {
DirDep::EnumEntry(path, [&cb](const PathCh* name, bool /*bDir*/) {
PathStr s(ToPathStr(name).moveTo());
if(s == name)
cb(Dir(s));
});
}
void Dir::EnumEntryRegEx(const std::string& r, EnumCB cb) {
if(r.empty())
return;
std::string path;
// 絶対パスの時は内部パスを無視する
int ofs = 0;
bool bAbs = false;
if(r[0] == '/') {
#ifdef WIN32
Assert(Throw, false, "invalid absolute path")
#endif
path += '/';
ofs = 1;
bAbs = true;
} else if(auto letter = _GetDriveLetter(&r[0], &r[0] + r.length())) {
// windowsの場合のみドライブ文字を出力
#ifdef WIN32
path += *letter;
path += ':';
#else
path += '/';
#endif
ofs = 2;
bAbs = true;
}
if(!bAbs)
path += "./";
try {
RegexL rl = _ParseRegEx(r.substr(ofs));
_EnumEntryRegEx(rl.begin(), rl.end(), path, path.size()+1, cb);
} catch(const boost::regex_error& e) {
// 正規表現に何かエラーがある時は単純に文字列比較とする
_EnumEntry(r, path, cb);
}
}
bool Dir::isFile() const {
return DirDep::IsFile(plain_utf32());
}
bool Dir::isDirectory() const {
return DirDep::IsDirectory(plain_utf32());
}
void Dir::remove() const {
DirDep::Remove(plain_utf32());
}
void Dir::copy(const std::string& to) const {
DirDep::Copy(plain_utf32(), to);
}
void Dir::move(const std::string& to) const {
DirDep::Move(plain_utf32(), to);
}
void Dir::mkdir(uint32_t mode) const {
PathReset preset;
if(isAbsolute())
DirDep::Chdir(SC_P);
mode |= FStatus::UserRWX;
auto path32 = plain_utf32(false);
const char32_t* ptr = &path32[0];
int nsg = segments();
std::string ns;
int i;
// 最初のパスから1つずつ存在確認
for(i=0 ; i<nsg ; i++) {
int seg = _segment[i];
ns = Text::UTFConvertTo8(c32Str(ptr, seg));
ptr += seg+1;
if(!DirDep::Chdir_nt(ns))
break;
}
if(i == nsg)
return;
// パスがファイルだったら失敗とする
Assert(Throw, !DirDep::IsFile(ns), "there is file at the path")
for(;;) {
DirDep::Mkdir(ns, mode);
DirDep::Chdir(ns);
if(++i == nsg)
break;
int seg = _segment[i] + 1;
ns = Text::UTFConvertTo8(c32Str(ptr, seg));
ptr += seg;
}
}
void Dir::_chmod(PathBlock& lpath, ModCB cb) {
DirDep::EnumEntry(lpath.plain_utf32(), [&lpath, this, cb](const PathCh* name, bool) {
lpath <<= name;
if(ChMod(lpath, cb))
_chmod(lpath, cb);
lpath.popBack();
});
}
bool Dir::ChMod(const PathBlock& pb, ModCB cb) {
ToPathStr path = pb.plain_utf32();
FStatus fstat = DirDep::Status(path);
bool bDir = fstat.flag & FStatus::DirectoryType;
if(bDir)
fstat.flag |= FStatus::UserExec;
bool bRecr = cb(pb, fstat);
DirDep::Chmod(path, fstat.flag);
return bDir && bRecr;
}
void Dir::chmod(ModCB cb) {
PathBlock pb(*this);
if(ChMod(pb, cb))
_chmod(pb, cb);
}
void Dir::chmod(uint32_t mode) {
chmod([mode](const PathBlock&, FStatus& fs) {
fs.flag = mode;
return false;
});
}
FILE* Dir::openAsFP(const char* mode) const {
return std::fopen(To8Str(plain_utf32()).getStringPtr(), mode);
}
FStatus Dir::status() const {
return DirDep::Status(plain_utf8());
}
// -------------------------- URI --------------------------
const std::string URI::SEP(u8"://");
const std::u32string URI::SEP32(U"://");
URI::URI() {}
URI::URI(URI&& u): PathBlock(std::move(u)), _type(std::move(u._type)) {}
URI::URI(To8Str p) {
setPath(p);
}
URI::URI(To8Str typ, To8Str path): PathBlock(path), _type(typ.moveTo()) {}
URI::URI(To8Str typ, const PathBlock& pb): PathBlock(pb), _type(typ.moveTo()) {}
URI& URI::operator = (URI&& u) {
static_cast<PathBlock&>(*this) = std::move(u);
_type = std::move(u._type);
return *this;
}
void URI::setPath(To8Str p) {
std::string path(p.moveTo());
boost::regex re("^([\\w\\d_]+)://");
boost::smatch m;
if(boost::regex_search(path, m, re)) {
_type = m.str(1);
PathBlock::setPath(path.substr(m[0].length()));
} else
PathBlock::setPath(std::move(path));
}
const std::string& URI::getType_utf8() const {
return _type;
}
void URI::setType(To8Str typ) {
_type = typ.moveTo();
}
const PathBlock& URI::path() const {
return *this;
}
PathBlock& URI::path() {
return *this;
}
std::string URI::plainUri_utf8() const {
auto ret = _type;
ret.append(SEP);
ret.append(plain_utf8());
return ret;
}
std::u32string URI::plainUri_utf32() const {
auto ret = To32Str(_type).moveTo();
ret.append(SEP32);
ret.append(plain_utf32());
return ret;
}
bool URI::operator == (const URI& u) const {
return _type == u._type
&& static_cast<const PathBlock&>(*this) == u;
}
bool URI::operator != (const URI& u) const {
return !(this->operator == (u));
}
}
<|endoftext|> |
<commit_before>/* $Id$ */
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//--------------------------------------------------------------------//
// //
// AliCFDataGrid Class //
// Class to handle observed data and correct them //
// //
// -- Author : S.Arcelli //
// //
// //
// //
//--------------------------------------------------------------------//
//
//
#include "TMath.h"
#include "AliLog.h"
#include "AliCFDataGrid.h"
//____________________________________________________________________
ClassImp(AliCFDataGrid)
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid() :
AliCFGridSparse(),
fSelData(-1),
fContainer(0x0)
{
//
// default constructor
//
SumW2(); //errors saved
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const Char_t* name,const Char_t* title) :
AliCFGridSparse(name,title),
fSelData(-1),
fContainer(0x0)
{
//
// default constructor
//
SumW2(); //errors saved
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const Char_t* name, const Char_t* title, const Int_t nVarIn, const Int_t * nBinIn, const Double_t *binLimitsIn) :
AliCFGridSparse(name,title,nVarIn,nBinIn,binLimitsIn),
fSelData(-1),
fContainer(0x0)
{
//
// main constructor
//
SumW2();// errors saved
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const Char_t* name, const Char_t* title, const AliCFContainer &c) :
AliCFGridSparse(name,title,c.GetNVar(),c.GetNBins(),c.GetBinLimits()),
fSelData(-1),
fContainer(0x0)
{
//
// main constructor
//
SumW2();
//assign the container;
fContainer=&c;
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const AliCFDataGrid& data) : AliCFGridSparse(),
fSelData(-1),
fContainer(0x0)
{
//
// copy constructor
//
((AliCFDataGrid &)data).Copy(*this);
}
//____________________________________________________________________
AliCFDataGrid::~AliCFDataGrid()
{
//
// destructor
//
}
//____________________________________________________________________
AliCFDataGrid &AliCFDataGrid::operator=(const AliCFDataGrid &c)
{
//
// assigment operator
//
if (this != &c)
((AliCFDataGrid &) c).Copy(*this);
return *this;
}
//____________________________________________________________________
void AliCFDataGrid::SetMeasured(Int_t istep)
{
//
// Deposit observed data over the grid
//
Int_t nEmptyBins=0;
fSelData=istep;
//Initially, set the corrected data to the measured data
for(Int_t i=0;i<fNDim;i++){
Float_t meas=fContainer->GetGrid(fSelData)->GetElement(i);
Float_t dmeas=fContainer->GetGrid(fSelData)->GetElementError(i);
SetElement(i,meas);
SetElementError(i,dmeas);
if(meas <=0)nEmptyBins++;
}
//fNentriesTot=fNDim;
GetGrid()->SetEntries(GetData()->GetEntries());
//
AliInfo(Form("retrieving measured data from Container %s at selection step %i: %i empty bins were found.",fContainer->GetName(),fSelData,nEmptyBins));
}
//____________________________________________________________________
void AliCFDataGrid::ApplyEffCorrection(const AliCFEffGrid &c)
{
//
// Apply the efficiency correction
//
if(c.GetNVar()!=fNVar){
AliInfo("Different number of variables, cannot apply correction");
return;
}
if(c.GetNDim()!=fNDim){
AliInfo("Different number of dimension, cannot apply correction");
return;
}
//Get the data
Int_t ncorr=0;
Int_t nnocorr=0;
Float_t eff,deff,unc,dunc,corr,dcorr;
//Apply the correction
for(Int_t i=0;i<fNDim;i++){
eff =c.GetElement(i);
deff =c.GetElementError(i);
unc =GetElement(i);
dunc =GetElementError(i);
if(eff>0 && unc>0){
ncorr++;
corr=unc/eff;
dcorr=TMath::Sqrt(dunc*dunc/unc/unc+deff*deff/eff/eff)*corr;
SetElement(i,corr);
SetElementError(i,dcorr);
} else{
if(unc>0)nnocorr++;
SetElement(i,0);
SetElementError(i,0);
}
}
AliInfo(Form("correction applied for %i cells in correction matrix of Container %s, having entries in Data Container %s.",ncorr,c.GetName(),GetName()));
AliInfo(Form("No correction applied for %i empty bins in correction matrix of Container %s, having entries in Data Container %s. Their content in the corrected data container was set to zero",nnocorr,c.GetName(),GetName()));
}
//____________________________________________________________________
void AliCFDataGrid::ApplyBGCorrection(const AliCFDataGrid &c)
{
//
// Apply correction for background
//
if(c.GetNVar()!=fNVar){
AliInfo("Different number of variables, cannot apply correction");
return;
}
if(c.GetNDim()!=fNDim){
AliInfo("Different number of dimension, cannot apply correction");
return;
}
//Get the data
Float_t bkg,dbkg,unc,dunc,corr,dcorr;
//Apply the correction
for(Int_t i=0;i<fNDim;i++){
bkg =c.GetElement(i);
dbkg =c.GetElementError(i);
unc =GetElement(i);
dunc =GetElementError(i);
corr=unc-bkg;
dcorr=TMath::Sqrt(unc+bkg); //stat err only...
SetElement(i,corr);
SetElementError(i,dcorr);
}
}
//____________________________________________________________________
void AliCFDataGrid::Copy(TObject& eff) const
{
// copy function
Copy(eff);
AliCFDataGrid& target = (AliCFDataGrid &) eff;
target.fContainer=fContainer;
target.fSelData=fSelData;
}
<commit_msg>corrected bad default constructor (A. Gheata)<commit_after>/* $Id$ */
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//--------------------------------------------------------------------//
// //
// AliCFDataGrid Class //
// Class to handle observed data and correct them //
// //
// -- Author : S.Arcelli //
// //
// //
// //
//--------------------------------------------------------------------//
//
//
#include "TMath.h"
#include "AliLog.h"
#include "AliCFDataGrid.h"
//____________________________________________________________________
ClassImp(AliCFDataGrid)
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid() :
AliCFGridSparse(),
fSelData(-1),
fContainer(0x0)
{
//
// default constructor
//
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const Char_t* name,const Char_t* title) :
AliCFGridSparse(name,title),
fSelData(-1),
fContainer(0x0)
{
//
// default constructor
//
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const Char_t* name, const Char_t* title, const Int_t nVarIn, const Int_t * nBinIn, const Double_t *binLimitsIn) :
AliCFGridSparse(name,title,nVarIn,nBinIn,binLimitsIn),
fSelData(-1),
fContainer(0x0)
{
//
// main constructor
//
SumW2();// errors saved
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const Char_t* name, const Char_t* title, const AliCFContainer &c) :
AliCFGridSparse(name,title,c.GetNVar(),c.GetNBins(),c.GetBinLimits()),
fSelData(-1),
fContainer(0x0)
{
//
// main constructor
//
SumW2();
//assign the container;
fContainer=&c;
}
//____________________________________________________________________
AliCFDataGrid::AliCFDataGrid(const AliCFDataGrid& data) : AliCFGridSparse(),
fSelData(-1),
fContainer(0x0)
{
//
// copy constructor
//
((AliCFDataGrid &)data).Copy(*this);
}
//____________________________________________________________________
AliCFDataGrid::~AliCFDataGrid()
{
//
// destructor
//
}
//____________________________________________________________________
AliCFDataGrid &AliCFDataGrid::operator=(const AliCFDataGrid &c)
{
//
// assigment operator
//
if (this != &c)
((AliCFDataGrid &) c).Copy(*this);
return *this;
}
//____________________________________________________________________
void AliCFDataGrid::SetMeasured(Int_t istep)
{
//
// Deposit observed data over the grid
//
Int_t nEmptyBins=0;
fSelData=istep;
//Initially, set the corrected data to the measured data
for(Int_t i=0;i<fNDim;i++){
Float_t meas=fContainer->GetGrid(fSelData)->GetElement(i);
Float_t dmeas=fContainer->GetGrid(fSelData)->GetElementError(i);
SetElement(i,meas);
SetElementError(i,dmeas);
if(meas <=0)nEmptyBins++;
}
//fNentriesTot=fNDim;
GetGrid()->SetEntries(GetData()->GetEntries());
//
AliInfo(Form("retrieving measured data from Container %s at selection step %i: %i empty bins were found.",fContainer->GetName(),fSelData,nEmptyBins));
}
//____________________________________________________________________
void AliCFDataGrid::ApplyEffCorrection(const AliCFEffGrid &c)
{
//
// Apply the efficiency correction
//
if(c.GetNVar()!=fNVar){
AliInfo("Different number of variables, cannot apply correction");
return;
}
if(c.GetNDim()!=fNDim){
AliInfo("Different number of dimension, cannot apply correction");
return;
}
//Get the data
Int_t ncorr=0;
Int_t nnocorr=0;
Float_t eff,deff,unc,dunc,corr,dcorr;
//Apply the correction
for(Int_t i=0;i<fNDim;i++){
eff =c.GetElement(i);
deff =c.GetElementError(i);
unc =GetElement(i);
dunc =GetElementError(i);
if(eff>0 && unc>0){
ncorr++;
corr=unc/eff;
dcorr=TMath::Sqrt(dunc*dunc/unc/unc+deff*deff/eff/eff)*corr;
SetElement(i,corr);
SetElementError(i,dcorr);
} else{
if(unc>0)nnocorr++;
SetElement(i,0);
SetElementError(i,0);
}
}
AliInfo(Form("correction applied for %i cells in correction matrix of Container %s, having entries in Data Container %s.",ncorr,c.GetName(),GetName()));
AliInfo(Form("No correction applied for %i empty bins in correction matrix of Container %s, having entries in Data Container %s. Their content in the corrected data container was set to zero",nnocorr,c.GetName(),GetName()));
}
//____________________________________________________________________
void AliCFDataGrid::ApplyBGCorrection(const AliCFDataGrid &c)
{
//
// Apply correction for background
//
if(c.GetNVar()!=fNVar){
AliInfo("Different number of variables, cannot apply correction");
return;
}
if(c.GetNDim()!=fNDim){
AliInfo("Different number of dimension, cannot apply correction");
return;
}
//Get the data
Float_t bkg,dbkg,unc,dunc,corr,dcorr;
//Apply the correction
for(Int_t i=0;i<fNDim;i++){
bkg =c.GetElement(i);
dbkg =c.GetElementError(i);
unc =GetElement(i);
dunc =GetElementError(i);
corr=unc-bkg;
dcorr=TMath::Sqrt(unc+bkg); //stat err only...
SetElement(i,corr);
SetElementError(i,dcorr);
}
}
//____________________________________________________________________
void AliCFDataGrid::Copy(TObject& eff) const
{
// copy function
Copy(eff);
AliCFDataGrid& target = (AliCFDataGrid &) eff;
target.fContainer=fContainer;
target.fSelData=fSelData;
}
<|endoftext|> |
<commit_before>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//! * Redistributions of source code must retain the above copyright
//! notice, this list ofconditions and the following disclaimer.
//!
//! * Redistributions in binary form must reproduce the above copyright
//! notice, this list of conditions and the following disclaimer in
//! the documentation and/or other materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
#include "buffer_file.h"
struct Data {
int a, b, c;
};
#define LOOP_TIMES (1000000)
int
main(int argc, char* argv[])
{
int counter;
DWORD beg, end;
BufferFile bf;
char buffer[1024 * 16];
Data d = {1, 2, 3};
if (bf.Open("demo.txt")) {
counter = 0;
beg = GetTickCount();
while (counter++ < LOOP_TIMES)
bf.Write(&d, sizeof(d));
end = GetTickCount();
fprintf(stdout, "use self buffer: %lu\n", end - beg);
}
bf.Close();
FILE* fp = fopen("demo1.txt", "w");
setvbuf(fp, buffer, _IOFBF, sizeof(buffer));
counter = 0;
beg = GetTickCount();
while (counter++ < LOOP_TIMES)
fwrite(&d, sizeof(d), 1, fp);
end = GetTickCount();
fprintf(stdout, "use stdio: %lu\n", end - beg);
fclose(fp);
return 0;
}
<commit_msg>changed test for BufferFile<commit_after>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//! * Redistributions of source code must retain the above copyright
//! notice, this list ofconditions and the following disclaimer.
//!
//! * Redistributions in binary form must reproduce the above copyright
//! notice, this list of conditions and the following disclaimer in
//! the documentation and/or other materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
#include "buffer_file.h"
#define LOOP_TIMES (10000)
int
main(int argc, char* argv[])
{
int counter;
DWORD beg, end;
BufferFile bf;
char buffer[1024 * 16];
char* s = "Hello, world! BufferFile testing ...\n";
int n = (int)strlen(s);
if (bf.Open("demo.txt")) {
counter = 0;
beg = GetTickCount();
while (counter++ < LOOP_TIMES)
bf.Write(s, n);
end = GetTickCount();
fprintf(stdout, "use self buffer: %lu\n", end - beg);
}
bf.Close();
FILE* fp = fopen("demo1.txt", "w");
setvbuf(fp, buffer, _IOFBF, sizeof(buffer));
counter = 0;
beg = GetTickCount();
while (counter++ < LOOP_TIMES)
fwrite(s, sizeof(char), n, fp);
end = GetTickCount();
fprintf(stdout, "use stdio: %lu\n", end - beg);
fclose(fp);
return 0;
}
<|endoftext|> |
<commit_before>// Standard demo of the numerical Bayesian calculator
/*
Author: Kyle Cranmer
date: Dec. 2010
This is a standard demo that can be used with any ROOT file
prepared in the standard way. You specify:
- name for input ROOT file
- name of workspace inside ROOT file that holds model and data
- name of ModelConfig that specifies details for calculator tools
- name of dataset
With default parameters the macro will attempt to run the
standard hist2workspace example and read the ROOT file
that it produces.
The actual heart of the demo is only about 10 lines long.
The BayesianCalculator is based on Bayes's theorem
and performs the integration using ROOT's numeric integration utilities
*/
#include "TFile.h"
#include "TROOT.h"
#include "RooWorkspace.h"
#include "RooAbsData.h"
#include "RooRealVar.h"
#include "RooUniform.h"
#include "RooStats/ModelConfig.h"
#include "RooStats/BayesianCalculator.h"
#include "RooStats/SimpleInterval.h"
#include "RooStats/RooStatsUtils.h"
#include "RooPlot.h"
#include "TSystem.h"
using namespace RooFit;
using namespace RooStats;
TString integrationType = ""; // integration Type (default is adaptive (numerical integration)
// possible values are "TOYMC" (toy MC integration, work when nuisances have a constraints pdf)
// "VEGAS" , "MISER", or "PLAIN" (these are all possible MC integration)
int nToys = 10000; // number of toys used for the MC integrations - for Vegas should be probably set to an higher value
bool scanPosterior = false; // flag to compute interval by scanning posterior (it is more robust but maybe less precise)
int nScanPoints = 50; // number of points for scanning the posterior (if scanPosterior = false it is used only for plotting)
int intervalType = 1; // type of interval (0 is shortest, 1 central, 2 upper limit)
double maxPOI = -999; // force a different value of POI for doing the scan (default is given value)
void StandardBayesianNumericalDemo(const char* infile = "",
const char* workspaceName = "combined",
const char* modelConfigName = "ModelConfig",
const char* dataName = "obsData") {
/////////////////////////////////////////////////////////////
// First part is just to access a user-defined file
// or create the standard example file if it doesn't exist
////////////////////////////////////////////////////////////
const char* filename = "";
if (!strcmp(infile,"")) {
filename = "results/example_combined_GaussExample_model.root";
bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
// if file does not exists generate with histfactory
if (!fileExist) {
#ifdef _WIN32
cout << "HistFactory file cannot be generated on Windows - exit" << endl;
return;
#endif
// Normally this would be run on the command line
cout <<"will run standard hist2workspace example"<<endl;
gROOT->ProcessLine(".! prepareHistFactory .");
gROOT->ProcessLine(".! hist2workspace config/example.xml");
cout <<"\n\n---------------------"<<endl;
cout <<"Done creating example input"<<endl;
cout <<"---------------------\n\n"<<endl;
}
}
else
filename = infile;
// Try to open the file
TFile *file = TFile::Open(filename);
// if input file was specified byt not found, quit
if(!file ){
cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
return;
}
/////////////////////////////////////////////////////////////
// Tutorial starts here
////////////////////////////////////////////////////////////
// get the workspace out of the file
RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
if(!w){
cout <<"workspace not found" << endl;
return;
}
// get the modelConfig out of the file
ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);
// get the modelConfig out of the file
RooAbsData* data = w->data(dataName);
// make sure ingredients are found
if(!data || !mc){
w->Print();
cout << "data or ModelConfig was not found" <<endl;
return;
}
/////////////////////////////////////////////
// create and use the BayesianCalculator
// to find and plot the 95% credible interval
// on the parameter of interest as specified
// in the model config
// before we do that, we must specify our prior
// it belongs in the model config, but it may not have
// been specified
RooUniform prior("prior","",*mc->GetParametersOfInterest());
w->import(prior);
mc->SetPriorPdf(*w->pdf("prior"));
// do without systematics
//mc->SetNuisanceParameters(RooArgSet() );
BayesianCalculator bayesianCalc(*data,*mc);
bayesianCalc.SetConfidenceLevel(0.95); // 95% interval
// default of the calculator is central interval. here use shortest , central or upper limit depending on input
// doing a shortest interval might require a longer time since it requires a scan of the posterior function
if (intervalType == 0) bayesianCalc.SetShortestInterval(); // for shortest interval
if (intervalType == 1) bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
if (intervalType == 2) bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit
if (!integrationType.IsNull() ) {
bayesianCalc.SetIntegrationType(integrationType); // set integrationType
bayesianCalc.SetNumIters(nToys); // set number of ietrations (i.e. number of toys for MC integrations)
}
// in case of toyMC make a nnuisance pdf
if (integrationType.Contains("TOYMC") ) {
RooAbsPdf * nuisPdf = RooStats::MakeNuisancePdf(*mc, "nuisance_pdf");
cout << "using TOYMC integration: make nuisance pdf from the model " << std::endl;
nuisPdf->Print();
bayesianCalc.ForceNuisancePdf(*nuisPdf);
scanPosterior = true; // for ToyMC the posterior is scanned anyway so used given points
}
// compute interval by scanning the posterior function
if (scanPosterior)
bayesianCalc.SetScanOfPosterior(nScanPoints);
RooRealVar* poi = (RooRealVar*) mc->GetParametersOfInterest()->first();
if (maxPOI != -999 && maxPOI > poi->getMin())
poi->setMax(maxPOI);
SimpleInterval* interval = bayesianCalc.GetInterval();
// print out the iterval on the first Parameter of Interest
cout << "\n95% interval on " << poi->GetName()<<" is : ["<<
interval->LowerLimit() << ", "<<
interval->UpperLimit() <<"] "<<endl;
// make a plot
// since plotting may take a long time (it requires evaluating
// the posterior in many points) this command will speed up
// by reducing the number of points to plot - do 50
cout << "\nDrawing plot of posterior function....." << endl;
bayesianCalc.SetScanOfPosterior(nScanPoints);
RooPlot * plot = bayesianCalc.GetPosteriorPlot();
plot->Draw();
}
<commit_msg>Speed up tutorial by plotting the posterior in less points (20 instead of 50)<commit_after>// Standard demo of the numerical Bayesian calculator
/*
Author: Kyle Cranmer
date: Dec. 2010
This is a standard demo that can be used with any ROOT file
prepared in the standard way. You specify:
- name for input ROOT file
- name of workspace inside ROOT file that holds model and data
- name of ModelConfig that specifies details for calculator tools
- name of dataset
With default parameters the macro will attempt to run the
standard hist2workspace example and read the ROOT file
that it produces.
The actual heart of the demo is only about 10 lines long.
The BayesianCalculator is based on Bayes's theorem
and performs the integration using ROOT's numeric integration utilities
*/
#include "TFile.h"
#include "TROOT.h"
#include "RooWorkspace.h"
#include "RooAbsData.h"
#include "RooRealVar.h"
#include "RooUniform.h"
#include "RooStats/ModelConfig.h"
#include "RooStats/BayesianCalculator.h"
#include "RooStats/SimpleInterval.h"
#include "RooStats/RooStatsUtils.h"
#include "RooPlot.h"
#include "TSystem.h"
using namespace RooFit;
using namespace RooStats;
TString integrationType = ""; // integration Type (default is adaptive (numerical integration)
// possible values are "TOYMC" (toy MC integration, work when nuisances have a constraints pdf)
// "VEGAS" , "MISER", or "PLAIN" (these are all possible MC integration)
int nToys = 10000; // number of toys used for the MC integrations - for Vegas should be probably set to an higher value
bool scanPosterior = false; // flag to compute interval by scanning posterior (it is more robust but maybe less precise)
int nScanPoints = 20; // number of points for scanning the posterior (if scanPosterior = false it is used only for plotting). Use by default a low value to speed-up tutorial
int intervalType = 1; // type of interval (0 is shortest, 1 central, 2 upper limit)
double maxPOI = -999; // force a different value of POI for doing the scan (default is given value)
void StandardBayesianNumericalDemo(const char* infile = "",
const char* workspaceName = "combined",
const char* modelConfigName = "ModelConfig",
const char* dataName = "obsData") {
/////////////////////////////////////////////////////////////
// First part is just to access a user-defined file
// or create the standard example file if it doesn't exist
////////////////////////////////////////////////////////////
const char* filename = "";
if (!strcmp(infile,"")) {
filename = "results/example_combined_GaussExample_model.root";
bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
// if file does not exists generate with histfactory
if (!fileExist) {
#ifdef _WIN32
cout << "HistFactory file cannot be generated on Windows - exit" << endl;
return;
#endif
// Normally this would be run on the command line
cout <<"will run standard hist2workspace example"<<endl;
gROOT->ProcessLine(".! prepareHistFactory .");
gROOT->ProcessLine(".! hist2workspace config/example.xml");
cout <<"\n\n---------------------"<<endl;
cout <<"Done creating example input"<<endl;
cout <<"---------------------\n\n"<<endl;
}
}
else
filename = infile;
// Try to open the file
TFile *file = TFile::Open(filename);
// if input file was specified byt not found, quit
if(!file ){
cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
return;
}
/////////////////////////////////////////////////////////////
// Tutorial starts here
////////////////////////////////////////////////////////////
// get the workspace out of the file
RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
if(!w){
cout <<"workspace not found" << endl;
return;
}
// get the modelConfig out of the file
ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);
// get the modelConfig out of the file
RooAbsData* data = w->data(dataName);
// make sure ingredients are found
if(!data || !mc){
w->Print();
cout << "data or ModelConfig was not found" <<endl;
return;
}
/////////////////////////////////////////////
// create and use the BayesianCalculator
// to find and plot the 95% credible interval
// on the parameter of interest as specified
// in the model config
// before we do that, we must specify our prior
// it belongs in the model config, but it may not have
// been specified
RooUniform prior("prior","",*mc->GetParametersOfInterest());
w->import(prior);
mc->SetPriorPdf(*w->pdf("prior"));
// do without systematics
//mc->SetNuisanceParameters(RooArgSet() );
BayesianCalculator bayesianCalc(*data,*mc);
bayesianCalc.SetConfidenceLevel(0.95); // 95% interval
// default of the calculator is central interval. here use shortest , central or upper limit depending on input
// doing a shortest interval might require a longer time since it requires a scan of the posterior function
if (intervalType == 0) bayesianCalc.SetShortestInterval(); // for shortest interval
if (intervalType == 1) bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
if (intervalType == 2) bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit
if (!integrationType.IsNull() ) {
bayesianCalc.SetIntegrationType(integrationType); // set integrationType
bayesianCalc.SetNumIters(nToys); // set number of ietrations (i.e. number of toys for MC integrations)
}
// in case of toyMC make a nnuisance pdf
if (integrationType.Contains("TOYMC") ) {
RooAbsPdf * nuisPdf = RooStats::MakeNuisancePdf(*mc, "nuisance_pdf");
cout << "using TOYMC integration: make nuisance pdf from the model " << std::endl;
nuisPdf->Print();
bayesianCalc.ForceNuisancePdf(*nuisPdf);
scanPosterior = true; // for ToyMC the posterior is scanned anyway so used given points
}
// compute interval by scanning the posterior function
if (scanPosterior)
bayesianCalc.SetScanOfPosterior(nScanPoints);
RooRealVar* poi = (RooRealVar*) mc->GetParametersOfInterest()->first();
if (maxPOI != -999 && maxPOI > poi->getMin())
poi->setMax(maxPOI);
SimpleInterval* interval = bayesianCalc.GetInterval();
// print out the iterval on the first Parameter of Interest
cout << "\n95% interval on " << poi->GetName()<<" is : ["<<
interval->LowerLimit() << ", "<<
interval->UpperLimit() <<"] "<<endl;
// make a plot
// since plotting may take a long time (it requires evaluating
// the posterior in many points) this command will speed up
// by reducing the number of points to plot - do 50
cout << "\nDrawing plot of posterior function....." << endl;
bayesianCalc.SetScanOfPosterior(nScanPoints);
RooPlot * plot = bayesianCalc.GetPosteriorPlot();
plot->Draw();
}
<|endoftext|> |
<commit_before>// http://www.apache.org/licenses/LICENSE-2.0
// Copyright 2014 Perttu Ahola <celeron55@gmail.com>
#include "core/types.h"
#include "core/log.h"
#include "server/config.h"
#include "server/state.h"
#include "interface/server.h"
#include <c55/getopt.h>
#include <c55/os.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#include <Context.h>
#include <Engine.h>
#include <Scene.h>
#pragma GCC diagnostic pop
#ifdef _WIN32
#include "ports/windows_sockets.h"
#include "ports/windows_compat.h"
#else
#include <unistd.h>
#endif
#include <iostream>
#include <signal.h>
#include <string.h> // strerror()
#include <time.h> // struct timeval
#define MODULE "main"
namespace magic = Urho3D;
server::Config g_server_config;
bool g_sigint_received = false;
void sigint_handler(int sig)
{
if(!g_sigint_received){
fprintf(stdout, "\n"); // Newline after "^C"
log_i("process", "SIGINT");
g_sigint_received = true;
} else {
(void)signal(SIGINT, SIG_DFL);
}
}
void signal_handler_init()
{
(void)signal(SIGINT, sigint_handler);
#ifndef _WIN32
(void)signal(SIGPIPE, SIG_IGN);
#endif
}
void basic_init()
{
signal_handler_init();
// Force '.' as decimal point
try {
std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
} catch(std::runtime_error &e){
// Can happen on Wine
fprintf(stderr, "Failed to set numeric C++ locale\n");
}
setlocale(LC_NUMERIC, "C");
log_init();
log_set_max_level(LOG_VERBOSE);
}
int main(int argc, char *argv[])
{
basic_init();
server::Config &config = g_server_config;
std::string module_path;
const char opts[100] = "hm:r:i:S:U:c:l:C:";
const char usagefmt[1000] =
"Usage: %s [OPTION]...\n"
" -h Show this help\n"
" -m [module_path] Specify module path\n"
" -r [rccpp_build_path]Specify runtime compiled C++ build path\n"
" -i [interface_path] Specify path to interface headers\n"
" -S [share_path] Specify path to share/\n"
" -U [urho3d_path] Specify Urho3D path\n"
" -c [command] Set compiler command\n"
" -l [integer] Set maximum log level (0...5)\n"
" -C [module_name] Skip compiling specified module\n"
;
int c;
while((c = c55_getopt(argc, argv, opts)) != -1)
{
switch(c)
{
case 'h':
printf(usagefmt, argv[0]);
return 1;
case 'm':
fprintf(stderr, "INFO: module_path: %s\n", c55_optarg);
module_path = c55_optarg;
break;
case 'r':
fprintf(stderr, "INFO: config.rccpp_build_path: %s\n", c55_optarg);
config.rccpp_build_path = c55_optarg;
break;
case 'i':
fprintf(stderr, "INFO: config.interface_path: %s\n", c55_optarg);
config.interface_path = c55_optarg;
break;
case 'S':
fprintf(stderr, "INFO: config.share_path: %s\n", c55_optarg);
config.share_path = c55_optarg;
break;
case 'U':
fprintf(stderr, "INFO: config.urho3d_path: %s\n", c55_optarg);
config.urho3d_path = c55_optarg;
break;
case 'c':
fprintf(stderr, "INFO: config.compiler_command: %s\n", c55_optarg);
config.compiler_command = c55_optarg;
break;
case 'l':
log_set_max_level(atoi(c55_optarg));
break;
case 'C':
fprintf(stderr, "INFO: config.skip_compiling_modules += %s\n",
c55_optarg);
config.skip_compiling_modules.insert(c55_optarg);
break;
default:
fprintf(stderr, "ERROR: Invalid command-line argument\n");
fprintf(stderr, usagefmt, argv[0]);
return 1;
}
}
std::cerr<<"Buildat server"<<std::endl;
if(!config.check_paths()){
return 1;
}
if(module_path.empty()){
std::cerr<<"Module path (-m) is empty"<<std::endl;
return 1;
}
int exit_status = 0;
ss_ shutdown_reason;
try {
up_<server::State> state(server::createState());
state->load_modules(module_path);
// Main loop
uint64_t next_tick_us = get_timeofday_us();
uint64_t t_per_tick = 1000 * 50;
set_<int> attempt_bad_fds;
int last_added_attempt_bad_fd = -42;
set_<int> bad_fds;
size_t num_consequent_valid_selects = 0;
while(!g_sigint_received){
uint64_t current_us = get_timeofday_us();
int64_t delay_us = next_tick_us - current_us;
if(delay_us < 0)
delay_us = 0;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = delay_us;
fd_set rfds;
FD_ZERO(&rfds);
sv_<int> sockets = state->get_sockets();
int fd_max = 0;
if(!attempt_bad_fds.empty() || !bad_fds.empty()){
log_w("main", "Ignoring fds %s and %s out of all %s",
cs(dump(attempt_bad_fds)), cs(dump(bad_fds)),
cs(dump(sockets)));
}
for(int fd : sockets){
if(attempt_bad_fds.count(fd) || bad_fds.count(fd))
continue;
FD_SET(fd, &rfds);
if(fd > fd_max)
fd_max = fd;
}
int r = select(fd_max + 1, &rfds, NULL, NULL, &tv);
if(r == -1){
if(errno == EINTR && g_sigint_received){
// Fine, we're quitting
break;
}
// Error
num_consequent_valid_selects = 0;
log_w("main", "select() returned -1: %s (fds: %s)",
strerror(errno), cs(dump(sockets)));
if(errno == EBADF || errno == EINTR){
// These are temporary errors
// Try to find out which socket is doing this
if(attempt_bad_fds.size() == sockets.size()){
throw Exception("All fds are bad");
} else {
for(;;){
int fd = sockets[rand() % sockets.size()];
if(attempt_bad_fds.count(fd) == 0){
log_w("main", "Trying to ignore fd=%i", fd);
attempt_bad_fds.insert(fd);
last_added_attempt_bad_fd = fd;
break;
}
}
}
} else {
// Don't consume 100% CPU and flood logs
usleep(1000 * 100);
return 1;
}
} else if(r == 0){
// Nothing happened
num_consequent_valid_selects++;
} else {
// Something happened
num_consequent_valid_selects++;
for(int fd : sockets){
if(FD_ISSET(fd, &rfds)){
log_d("main", "FD_ISSET: %i", fd);
state->emit_socket_event(fd);
}
}
}
if(!attempt_bad_fds.empty() && num_consequent_valid_selects > 5){
log_w("main", "Found bad fd: %d", last_added_attempt_bad_fd);
bad_fds.insert(last_added_attempt_bad_fd);
attempt_bad_fds.clear();
}
if(current_us >= next_tick_us){
next_tick_us += t_per_tick;
if(next_tick_us < current_us - 1000 * 1000){
log_w("main", "Skipping %zuus", current_us - next_tick_us);
next_tick_us = current_us;
}
interface::Event event("core:tick");
event.p.reset(new interface::TickEvent(t_per_tick / 1e6));
state->emit_event(std::move(event));
}
state->handle_events();
state->access_scene([&](magic::Scene *scene)
{
magic::Context *context = scene->GetContext();
magic::Engine *engine = context->GetSubsystem<magic::Engine>();
engine->SetNextTimeStep(t_per_tick / 1e6);
engine->RunFrame();
});
if(state->is_shutdown_requested(&exit_status, &shutdown_reason))
break;
}
} catch(server::ServerShutdownRequest &e){
log_v(MODULE, "ServerShutdownRequest: %s", e.what());
}
if(shutdown_reason != ""){
if(exit_status != 0)
log_w(MODULE, "Shutdown: %s", cs(shutdown_reason));
else
log_v(MODULE, "Shutdown: %s", cs(shutdown_reason));
}
return exit_status;
}
// vim: set noet ts=4 sw=4:
<commit_msg>server/main: Log Urho3D profiler output<commit_after>// http://www.apache.org/licenses/LICENSE-2.0
// Copyright 2014 Perttu Ahola <celeron55@gmail.com>
#include "core/types.h"
#include "core/log.h"
#include "server/config.h"
#include "server/state.h"
#include "interface/server.h"
#include <c55/getopt.h>
#include <c55/os.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#include <Context.h>
#include <Engine.h>
#include <Scene.h>
#include <Profiler.h>
#pragma GCC diagnostic pop
#ifdef _WIN32
#include "ports/windows_sockets.h"
#include "ports/windows_compat.h"
#else
#include <unistd.h>
#endif
#include <iostream>
#include <climits>
#include <signal.h>
#include <string.h> // strerror()
#include <time.h> // struct timeval
#define MODULE "main"
namespace magic = Urho3D;
server::Config g_server_config;
bool g_sigint_received = false;
void sigint_handler(int sig)
{
if(!g_sigint_received){
fprintf(stdout, "\n"); // Newline after "^C"
log_i("process", "SIGINT");
g_sigint_received = true;
} else {
(void)signal(SIGINT, SIG_DFL);
}
}
void signal_handler_init()
{
(void)signal(SIGINT, sigint_handler);
#ifndef _WIN32
(void)signal(SIGPIPE, SIG_IGN);
#endif
}
void basic_init()
{
signal_handler_init();
// Force '.' as decimal point
try {
std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
} catch(std::runtime_error &e){
// Can happen on Wine
fprintf(stderr, "Failed to set numeric C++ locale\n");
}
setlocale(LC_NUMERIC, "C");
log_init();
log_set_max_level(LOG_VERBOSE);
}
int main(int argc, char *argv[])
{
basic_init();
server::Config &config = g_server_config;
std::string module_path;
const char opts[100] = "hm:r:i:S:U:c:l:C:";
const char usagefmt[1000] =
"Usage: %s [OPTION]...\n"
" -h Show this help\n"
" -m [module_path] Specify module path\n"
" -r [rccpp_build_path]Specify runtime compiled C++ build path\n"
" -i [interface_path] Specify path to interface headers\n"
" -S [share_path] Specify path to share/\n"
" -U [urho3d_path] Specify Urho3D path\n"
" -c [command] Set compiler command\n"
" -l [integer] Set maximum log level (0...5)\n"
" -C [module_name] Skip compiling specified module\n"
;
int c;
while((c = c55_getopt(argc, argv, opts)) != -1)
{
switch(c)
{
case 'h':
printf(usagefmt, argv[0]);
return 1;
case 'm':
fprintf(stderr, "INFO: module_path: %s\n", c55_optarg);
module_path = c55_optarg;
break;
case 'r':
fprintf(stderr, "INFO: config.rccpp_build_path: %s\n", c55_optarg);
config.rccpp_build_path = c55_optarg;
break;
case 'i':
fprintf(stderr, "INFO: config.interface_path: %s\n", c55_optarg);
config.interface_path = c55_optarg;
break;
case 'S':
fprintf(stderr, "INFO: config.share_path: %s\n", c55_optarg);
config.share_path = c55_optarg;
break;
case 'U':
fprintf(stderr, "INFO: config.urho3d_path: %s\n", c55_optarg);
config.urho3d_path = c55_optarg;
break;
case 'c':
fprintf(stderr, "INFO: config.compiler_command: %s\n", c55_optarg);
config.compiler_command = c55_optarg;
break;
case 'l':
log_set_max_level(atoi(c55_optarg));
break;
case 'C':
fprintf(stderr, "INFO: config.skip_compiling_modules += %s\n",
c55_optarg);
config.skip_compiling_modules.insert(c55_optarg);
break;
default:
fprintf(stderr, "ERROR: Invalid command-line argument\n");
fprintf(stderr, usagefmt, argv[0]);
return 1;
}
}
std::cerr<<"Buildat server"<<std::endl;
if(!config.check_paths()){
return 1;
}
if(module_path.empty()){
std::cerr<<"Module path (-m) is empty"<<std::endl;
return 1;
}
int exit_status = 0;
ss_ shutdown_reason;
try {
up_<server::State> state(server::createState());
state->load_modules(module_path);
// Main loop
uint64_t next_tick_us = get_timeofday_us();
uint64_t t_per_tick = 1000 * 50;
set_<int> attempt_bad_fds;
int last_added_attempt_bad_fd = -42;
set_<int> bad_fds;
size_t num_consequent_valid_selects = 0;
float profiler_print_timer = 0;
while(!g_sigint_received){
uint64_t current_us = get_timeofday_us();
int64_t delay_us = next_tick_us - current_us;
if(delay_us < 0)
delay_us = 0;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = delay_us;
fd_set rfds;
FD_ZERO(&rfds);
sv_<int> sockets = state->get_sockets();
int fd_max = 0;
if(!attempt_bad_fds.empty() || !bad_fds.empty()){
log_w("main", "Ignoring fds %s and %s out of all %s",
cs(dump(attempt_bad_fds)), cs(dump(bad_fds)),
cs(dump(sockets)));
}
for(int fd : sockets){
if(attempt_bad_fds.count(fd) || bad_fds.count(fd))
continue;
FD_SET(fd, &rfds);
if(fd > fd_max)
fd_max = fd;
}
int r = select(fd_max + 1, &rfds, NULL, NULL, &tv);
if(r == -1){
if(errno == EINTR && g_sigint_received){
// Fine, we're quitting
break;
}
// Error
num_consequent_valid_selects = 0;
log_w("main", "select() returned -1: %s (fds: %s)",
strerror(errno), cs(dump(sockets)));
if(errno == EBADF || errno == EINTR){
// These are temporary errors
// Try to find out which socket is doing this
if(attempt_bad_fds.size() == sockets.size()){
throw Exception("All fds are bad");
} else {
for(;;){
int fd = sockets[rand() % sockets.size()];
if(attempt_bad_fds.count(fd) == 0){
log_w("main", "Trying to ignore fd=%i", fd);
attempt_bad_fds.insert(fd);
last_added_attempt_bad_fd = fd;
break;
}
}
}
} else {
// Don't consume 100% CPU and flood logs
usleep(1000 * 100);
return 1;
}
} else if(r == 0){
// Nothing happened
num_consequent_valid_selects++;
} else {
// Something happened
num_consequent_valid_selects++;
for(int fd : sockets){
if(FD_ISSET(fd, &rfds)){
log_d("main", "FD_ISSET: %i", fd);
state->emit_socket_event(fd);
}
}
}
if(!attempt_bad_fds.empty() && num_consequent_valid_selects > 5){
log_w("main", "Found bad fd: %d", last_added_attempt_bad_fd);
bad_fds.insert(last_added_attempt_bad_fd);
attempt_bad_fds.clear();
}
if(current_us >= next_tick_us){
next_tick_us += t_per_tick;
if(next_tick_us < current_us - 1000 * 1000){
log_w("main", "Skipping %zuus", current_us - next_tick_us);
next_tick_us = current_us;
}
interface::Event event("core:tick");
event.p.reset(new interface::TickEvent(t_per_tick / 1e6));
state->emit_event(std::move(event));
}
state->handle_events();
state->access_scene([&](magic::Scene *scene)
{
magic::Context *context = scene->GetContext();
magic::Engine *engine = context->GetSubsystem<magic::Engine>();
engine->SetNextTimeStep(t_per_tick / 1e6);
engine->RunFrame();
profiler_print_timer += t_per_tick / 1e6;
if(profiler_print_timer >= 10.0f){
// Aim for long-time stability in profiler intervals
profiler_print_timer -= 10.0f;
// Avoid useless flooding in case of stuck server
if(profiler_print_timer > 5.0f)
profiler_print_timer = 0.0f;
magic::Profiler *p = context->GetSubsystem<magic::Profiler>();
if(p){
magic::String s = p->GetData(false, false, UINT_MAX);
p->BeginInterval();
log_v("main", "Urho3D Profiler:\n%s", s.CString());
}
}
});
if(state->is_shutdown_requested(&exit_status, &shutdown_reason))
break;
}
} catch(server::ServerShutdownRequest &e){
log_v(MODULE, "ServerShutdownRequest: %s", e.what());
}
if(shutdown_reason != ""){
if(exit_status != 0)
log_w(MODULE, "Shutdown: %s", cs(shutdown_reason));
else
log_v(MODULE, "Shutdown: %s", cs(shutdown_reason));
}
return exit_status;
}
// vim: set noet ts=4 sw=4:
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: precompiled_canvas.hxx,v $
* $Revision: 1.4 $
*
* 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): Generated on 2006-09-01 17:49:32.389803
#ifdef PRECOMPILED_HEADERS
#include <sal/macros.h>
#endif
<commit_msg>INTEGRATION: CWS canvas05 (1.3.36); FILE MERGED 2008/04/21 07:26:51 thb 1.3.36.2: RESYNC: (1.3-1.4); FILE MERGED 2007/12/20 22:18:56 thb 1.3.36.1: #i81092# #i78888# #i78925# #i79258# #i79437# #i84784# Large canvas rework, completing various areas such as color spaces, bitmap data access, true sprite and non-sprite implementations, and upstreaming the canvas parts of rodos emf+ rendering<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: precompiled_canvas.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): Generated on 2006-09-01 17:49:32.389803
#ifdef PRECOMPILED_HEADERS
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: hierarchydatasupplier.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kso $ $Date: 2000-12-10 15:13:51 $
*
* 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): Kai Sommerfeld ( kso@sun.com )
*
*
************************************************************************/
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include <vector>
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _HIERARCHYDATASUPPLIER_HXX
#include "hierarchydatasupplier.hxx"
#endif
#ifndef _HIERARCHYPROVIDER_HXX
#include "hierarchyprovider.hxx"
#endif
#ifndef _HIERARCHYCONTENT_HXX
#include "hierarchycontent.hxx"
#endif
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace com::sun::star::sdbc;
using namespace rtl;
using namespace ucb;
using namespace hierarchy_ucp;
namespace hierarchy_ucp
{
//=========================================================================
//
// struct ResultListEntry.
//
//=========================================================================
struct ResultListEntry
{
OUString aId;
Reference< XContentIdentifier > xId;
Reference< XContent > xContent;
Reference< XRow > xRow;
HierarchyEntryData aData;
ResultListEntry( const HierarchyEntryData& rEntry ) : aData( rEntry ) {}
};
//=========================================================================
//
// ResultList.
//
//=========================================================================
typedef std::vector< ResultListEntry* > ResultList;
//=========================================================================
//
// struct DataSupplier_Impl.
//
//=========================================================================
struct DataSupplier_Impl
{
osl::Mutex m_aMutex;
ResultList m_aResults;
vos::ORef< HierarchyContent > m_xContent;
Reference< XMultiServiceFactory > m_xSMgr;
HierarchyEntry m_aFolder;
HierarchyEntry::iterator m_aIterator;
sal_Int32 m_nOpenMode;
sal_Bool m_bCountFinal;
DataSupplier_Impl( const Reference< XMultiServiceFactory >& rxSMgr,
const vos::ORef< HierarchyContent >& rContent,
sal_Int32 nOpenMode )
: m_xContent( rContent ), m_xSMgr( rxSMgr ),
m_aFolder( rxSMgr,
static_cast< HierarchyContentProvider * >(
rContent->getProvider().getBodyPtr() ),
rContent->getIdentifier()->getContentIdentifier() ),
m_nOpenMode( nOpenMode ), m_bCountFinal( sal_False ) {}
~DataSupplier_Impl();
};
//=========================================================================
DataSupplier_Impl::~DataSupplier_Impl()
{
ResultList::const_iterator it = m_aResults.begin();
ResultList::const_iterator end = m_aResults.end();
while ( it != end )
{
delete (*it);
it++;
}
}
}
//=========================================================================
//=========================================================================
//
// HierarchyResultSetDataSupplier Implementation.
//
//=========================================================================
//=========================================================================
HierarchyResultSetDataSupplier::HierarchyResultSetDataSupplier(
const Reference< XMultiServiceFactory >& rxSMgr,
const vos::ORef< HierarchyContent >& rContent,
sal_Int32 nOpenMode )
: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )
{
}
//=========================================================================
// virtual
HierarchyResultSetDataSupplier::~HierarchyResultSetDataSupplier()
{
delete m_pImpl;
}
//=========================================================================
// virtual
OUString HierarchyResultSetDataSupplier::queryContentIdentifierString(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
OUString aId = m_pImpl->m_aResults[ nIndex ]->aId;
if ( aId.getLength() )
{
// Already cached.
return aId;
}
}
if ( getResult( nIndex ) )
{
OUString aId
= m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();
if ( ( aId.lastIndexOf( '/' ) + 1 ) != aId.getLength() )
aId += OUString::createFromAscii( "/" );
aId += m_pImpl->m_aResults[ nIndex ]->aData.aName;
m_pImpl->m_aResults[ nIndex ]->aId = aId;
return aId;
}
return OUString();
}
//=========================================================================
// virtual
Reference< XContentIdentifier >
HierarchyResultSetDataSupplier::queryContentIdentifier( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
Reference< XContentIdentifier > xId
= m_pImpl->m_aResults[ nIndex ]->xId;
if ( xId.is() )
{
// Already cached.
return xId;
}
}
OUString aId = queryContentIdentifierString( nIndex );
if ( aId.getLength() )
{
Reference< XContentIdentifier > xId = new ContentIdentifier( aId );
m_pImpl->m_aResults[ nIndex ]->xId = xId;
return xId;
}
return Reference< XContentIdentifier >();
}
//=========================================================================
// virtual
Reference< XContent > HierarchyResultSetDataSupplier::queryContent(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
Reference< XContent > xContent
= m_pImpl->m_aResults[ nIndex ]->xContent;
if ( xContent.is() )
{
// Already cached.
return xContent;
}
}
Reference< XContentIdentifier > xId = queryContentIdentifier( nIndex );
if ( xId.is() )
{
try
{
Reference< XContent > xContent
= m_pImpl->m_xContent->getProvider()->queryContent( xId );
m_pImpl->m_aResults[ nIndex ]->xContent = xContent;
return xContent;
}
catch ( IllegalIdentifierException& )
{
}
}
return Reference< XContent >();
}
//=========================================================================
// virtual
sal_Bool HierarchyResultSetDataSupplier::getResult( sal_uInt32 nIndex )
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_aResults.size() > nIndex )
{
// Result already present.
return sal_True;
}
// Result not (yet) present.
if ( m_pImpl->m_bCountFinal )
return sal_False;
// Try to obtain result...
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
sal_Bool bFound = sal_False;
sal_uInt32 nPos = nOldCount;
while ( m_pImpl->m_aFolder.next( m_pImpl->m_aIterator ) )
{
const HierarchyEntryData& rResult = *m_pImpl->m_aIterator;
if ( checkResult( rResult ) )
{
m_pImpl->m_aResults.push_back( new ResultListEntry( rResult ) );
if ( nPos == nIndex )
{
// Result obtained.
bFound = sal_True;
break;
}
}
nPos++;
}
if ( !bFound )
m_pImpl->m_bCountFinal = sal_True;
vos::ORef< ResultSet > xResultSet = getResultSet();
if ( xResultSet.isValid() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
if ( m_pImpl->m_bCountFinal )
xResultSet->rowCountFinal();
}
return bFound;
}
//=========================================================================
// virtual
sal_uInt32 HierarchyResultSetDataSupplier::totalCount()
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_bCountFinal )
return m_pImpl->m_aResults.size();
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
while ( m_pImpl->m_aFolder.next( m_pImpl->m_aIterator ) )
{
const HierarchyEntryData& rResult = *m_pImpl->m_aIterator;
if ( checkResult( rResult ) )
m_pImpl->m_aResults.push_back( new ResultListEntry( rResult ) );
}
m_pImpl->m_bCountFinal = sal_True;
vos::ORef< ResultSet > xResultSet = getResultSet();
if ( xResultSet.isValid() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
xResultSet->rowCountFinal();
}
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_uInt32 HierarchyResultSetDataSupplier::currentCount()
{
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_Bool HierarchyResultSetDataSupplier::isCountFinal()
{
return m_pImpl->m_bCountFinal;
}
//=========================================================================
// virtual
Reference< XRow > HierarchyResultSetDataSupplier::queryPropertyValues(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
Reference< XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;
if ( xRow.is() )
{
// Already cached.
return xRow;
}
}
if ( getResult( nIndex ) )
{
HierarchyContentProperties aData;
aData.aTitle = m_pImpl->m_aResults[ nIndex ]->aData.aTitle;
aData.aTargetURL = m_pImpl->m_aResults[ nIndex ]->aData.aTargetURL;
aData.bIsDocument = ( aData.aTargetURL.getLength() > 0 );
aData.bIsFolder = !aData.bIsDocument;
aData.aContentType = aData.bIsFolder
? OUString::createFromAscii(
HIERARCHY_FOLDER_CONTENT_TYPE )
: OUString::createFromAscii(
HIERARCHY_LINK_CONTENT_TYPE );
Reference< XRow > xRow = HierarchyContent::getPropertyValues(
m_pImpl->m_xSMgr,
getResultSet()->getProperties(),
aData,
static_cast< HierarchyContentProvider * >(
m_pImpl->m_xContent->getProvider().getBodyPtr() ),
queryContentIdentifierString( nIndex ) );
m_pImpl->m_aResults[ nIndex ]->xRow = xRow;
return xRow;
}
return Reference< XRow >();
}
//=========================================================================
// virtual
void HierarchyResultSetDataSupplier::releasePropertyValues( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
m_pImpl->m_aResults[ nIndex ]->xRow = Reference< XRow >();
}
//=========================================================================
// virtual
void HierarchyResultSetDataSupplier::close()
{
}
//=========================================================================
// virtual
void HierarchyResultSetDataSupplier::validate()
throw( ResultSetException )
{
}
//=========================================================================
sal_Bool HierarchyResultSetDataSupplier::checkResult(
const HierarchyEntryData& rResult )
{
switch ( m_pImpl->m_nOpenMode )
{
case OpenMode::FOLDERS:
if ( rResult.aTargetURL.getLength() > 0 )
{
// Entry is a link.
return sal_False;
}
break;
case OpenMode::DOCUMENTS:
if ( rResult.aTargetURL.getLength() == 0 )
{
// Entry is a folder.
return sal_False;
}
break;
case OpenMode::ALL:
default:
break;
}
return sal_True;
}
<commit_msg>#80510# - Optimized HierarchyResultSetDataSupplier::queryPropertyValues(...)<commit_after>/*************************************************************************
*
* $RCSfile: hierarchydatasupplier.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kso $ $Date: 2001-03-13 14:14:01 $
*
* 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): Kai Sommerfeld ( kso@sun.com )
*
*
************************************************************************/
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include <vector>
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _HIERARCHYDATASUPPLIER_HXX
#include "hierarchydatasupplier.hxx"
#endif
#ifndef _HIERARCHYPROVIDER_HXX
#include "hierarchyprovider.hxx"
#endif
#ifndef _HIERARCHYCONTENT_HXX
#include "hierarchycontent.hxx"
#endif
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace com::sun::star::sdbc;
using namespace rtl;
using namespace ucb;
using namespace hierarchy_ucp;
namespace hierarchy_ucp
{
//=========================================================================
//
// struct ResultListEntry.
//
//=========================================================================
struct ResultListEntry
{
OUString aId;
Reference< XContentIdentifier > xId;
Reference< XContent > xContent;
Reference< XRow > xRow;
HierarchyEntryData aData;
ResultListEntry( const HierarchyEntryData& rEntry ) : aData( rEntry ) {}
};
//=========================================================================
//
// ResultList.
//
//=========================================================================
typedef std::vector< ResultListEntry* > ResultList;
//=========================================================================
//
// struct DataSupplier_Impl.
//
//=========================================================================
struct DataSupplier_Impl
{
osl::Mutex m_aMutex;
ResultList m_aResults;
vos::ORef< HierarchyContent > m_xContent;
Reference< XMultiServiceFactory > m_xSMgr;
HierarchyEntry m_aFolder;
HierarchyEntry::iterator m_aIterator;
sal_Int32 m_nOpenMode;
sal_Bool m_bCountFinal;
DataSupplier_Impl( const Reference< XMultiServiceFactory >& rxSMgr,
const vos::ORef< HierarchyContent >& rContent,
sal_Int32 nOpenMode )
: m_xContent( rContent ), m_xSMgr( rxSMgr ),
m_aFolder( rxSMgr,
static_cast< HierarchyContentProvider * >(
rContent->getProvider().getBodyPtr() ),
rContent->getIdentifier()->getContentIdentifier() ),
m_nOpenMode( nOpenMode ), m_bCountFinal( sal_False ) {}
~DataSupplier_Impl();
};
//=========================================================================
DataSupplier_Impl::~DataSupplier_Impl()
{
ResultList::const_iterator it = m_aResults.begin();
ResultList::const_iterator end = m_aResults.end();
while ( it != end )
{
delete (*it);
it++;
}
}
}
//=========================================================================
//=========================================================================
//
// HierarchyResultSetDataSupplier Implementation.
//
//=========================================================================
//=========================================================================
HierarchyResultSetDataSupplier::HierarchyResultSetDataSupplier(
const Reference< XMultiServiceFactory >& rxSMgr,
const vos::ORef< HierarchyContent >& rContent,
sal_Int32 nOpenMode )
: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )
{
}
//=========================================================================
// virtual
HierarchyResultSetDataSupplier::~HierarchyResultSetDataSupplier()
{
delete m_pImpl;
}
//=========================================================================
// virtual
OUString HierarchyResultSetDataSupplier::queryContentIdentifierString(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
OUString aId = m_pImpl->m_aResults[ nIndex ]->aId;
if ( aId.getLength() )
{
// Already cached.
return aId;
}
}
if ( getResult( nIndex ) )
{
OUString aId
= m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();
if ( ( aId.lastIndexOf( '/' ) + 1 ) != aId.getLength() )
aId += OUString::createFromAscii( "/" );
aId += m_pImpl->m_aResults[ nIndex ]->aData.aName;
m_pImpl->m_aResults[ nIndex ]->aId = aId;
return aId;
}
return OUString();
}
//=========================================================================
// virtual
Reference< XContentIdentifier >
HierarchyResultSetDataSupplier::queryContentIdentifier( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
Reference< XContentIdentifier > xId
= m_pImpl->m_aResults[ nIndex ]->xId;
if ( xId.is() )
{
// Already cached.
return xId;
}
}
OUString aId = queryContentIdentifierString( nIndex );
if ( aId.getLength() )
{
Reference< XContentIdentifier > xId = new ContentIdentifier( aId );
m_pImpl->m_aResults[ nIndex ]->xId = xId;
return xId;
}
return Reference< XContentIdentifier >();
}
//=========================================================================
// virtual
Reference< XContent > HierarchyResultSetDataSupplier::queryContent(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
Reference< XContent > xContent
= m_pImpl->m_aResults[ nIndex ]->xContent;
if ( xContent.is() )
{
// Already cached.
return xContent;
}
}
Reference< XContentIdentifier > xId = queryContentIdentifier( nIndex );
if ( xId.is() )
{
try
{
Reference< XContent > xContent
= m_pImpl->m_xContent->getProvider()->queryContent( xId );
m_pImpl->m_aResults[ nIndex ]->xContent = xContent;
return xContent;
}
catch ( IllegalIdentifierException& )
{
}
}
return Reference< XContent >();
}
//=========================================================================
// virtual
sal_Bool HierarchyResultSetDataSupplier::getResult( sal_uInt32 nIndex )
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_aResults.size() > nIndex )
{
// Result already present.
return sal_True;
}
// Result not (yet) present.
if ( m_pImpl->m_bCountFinal )
return sal_False;
// Try to obtain result...
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
sal_Bool bFound = sal_False;
sal_uInt32 nPos = nOldCount;
while ( m_pImpl->m_aFolder.next( m_pImpl->m_aIterator ) )
{
const HierarchyEntryData& rResult = *m_pImpl->m_aIterator;
if ( checkResult( rResult ) )
{
m_pImpl->m_aResults.push_back( new ResultListEntry( rResult ) );
if ( nPos == nIndex )
{
// Result obtained.
bFound = sal_True;
break;
}
}
nPos++;
}
if ( !bFound )
m_pImpl->m_bCountFinal = sal_True;
vos::ORef< ResultSet > xResultSet = getResultSet();
if ( xResultSet.isValid() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
if ( m_pImpl->m_bCountFinal )
xResultSet->rowCountFinal();
}
return bFound;
}
//=========================================================================
// virtual
sal_uInt32 HierarchyResultSetDataSupplier::totalCount()
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_bCountFinal )
return m_pImpl->m_aResults.size();
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
while ( m_pImpl->m_aFolder.next( m_pImpl->m_aIterator ) )
{
const HierarchyEntryData& rResult = *m_pImpl->m_aIterator;
if ( checkResult( rResult ) )
m_pImpl->m_aResults.push_back( new ResultListEntry( rResult ) );
}
m_pImpl->m_bCountFinal = sal_True;
vos::ORef< ResultSet > xResultSet = getResultSet();
if ( xResultSet.isValid() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
xResultSet->rowCountFinal();
}
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_uInt32 HierarchyResultSetDataSupplier::currentCount()
{
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_Bool HierarchyResultSetDataSupplier::isCountFinal()
{
return m_pImpl->m_bCountFinal;
}
//=========================================================================
// virtual
Reference< XRow > HierarchyResultSetDataSupplier::queryPropertyValues(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
Reference< XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;
if ( xRow.is() )
{
// Already cached.
return xRow;
}
}
if ( getResult( nIndex ) )
{
static OUString aFolderType( OUString::createFromAscii(
HIERARCHY_FOLDER_CONTENT_TYPE ) );
static OUString aLinkType( OUString::createFromAscii(
HIERARCHY_LINK_CONTENT_TYPE ) );
HierarchyContentProperties aData;
aData.aTitle = m_pImpl->m_aResults[ nIndex ]->aData.aTitle;
aData.aTargetURL = m_pImpl->m_aResults[ nIndex ]->aData.aTargetURL;
aData.bIsDocument = ( aData.aTargetURL.getLength() > 0 );
aData.bIsFolder = !aData.bIsDocument;
aData.aContentType = aData.bIsFolder ? aFolderType : aLinkType;
Reference< XRow > xRow = HierarchyContent::getPropertyValues(
m_pImpl->m_xSMgr,
getResultSet()->getProperties(),
aData,
static_cast< HierarchyContentProvider * >(
m_pImpl->m_xContent->getProvider().getBodyPtr() ),
queryContentIdentifierString( nIndex ) );
m_pImpl->m_aResults[ nIndex ]->xRow = xRow;
return xRow;
}
return Reference< XRow >();
}
//=========================================================================
// virtual
void HierarchyResultSetDataSupplier::releasePropertyValues( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
m_pImpl->m_aResults[ nIndex ]->xRow = Reference< XRow >();
}
//=========================================================================
// virtual
void HierarchyResultSetDataSupplier::close()
{
}
//=========================================================================
// virtual
void HierarchyResultSetDataSupplier::validate()
throw( ResultSetException )
{
}
//=========================================================================
sal_Bool HierarchyResultSetDataSupplier::checkResult(
const HierarchyEntryData& rResult )
{
switch ( m_pImpl->m_nOpenMode )
{
case OpenMode::FOLDERS:
if ( rResult.aTargetURL.getLength() > 0 )
{
// Entry is a link.
return sal_False;
}
break;
case OpenMode::DOCUMENTS:
if ( rResult.aTargetURL.getLength() == 0 )
{
// Entry is a folder.
return sal_False;
}
break;
case OpenMode::ALL:
default:
break;
}
return sal_True;
}
<|endoftext|> |
<commit_before>//===-- ObjectContainerBSDArchive.cpp ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ObjectContainerBSDArchive.h"
#include <ar.h>
#include "lldb/Core/Stream.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Mutex.h"
#include "lldb/Symbol/ObjectFile.h"
using namespace lldb;
using namespace lldb_private;
ObjectContainerBSDArchive::Object::Object() :
ar_name(),
ar_date(0),
ar_uid(0),
ar_gid(0),
ar_mode(0),
ar_size(0),
ar_file_offset(0),
ar_file_size(0)
{
}
void
ObjectContainerBSDArchive::Object::Clear()
{
ar_name.Clear();
ar_date = 0;
ar_uid = 0;
ar_gid = 0;
ar_mode = 0;
ar_size = 0;
ar_file_offset = 0;
ar_file_size = 0;
}
uint32_t
ObjectContainerBSDArchive::Object::Extract (const DataExtractor& data, uint32_t offset)
{
size_t ar_name_len = 0;
std::string str;
char *err;
str.assign ((const char *)data.GetData(&offset, 16), 16);
if (str.find("#1/") == 0)
{
// If the name is longer than 16 bytes, or contains an embedded space
// then it will use this format where the length of the name is
// here and the name characters are after this header.
ar_name_len = strtoul(str.c_str() + 3, &err, 10);
}
else
{
// Strip off any spaces (if the object file name contains spaces it
// will use the extended format above).
str.erase (str.find(' '));
ar_name.SetCString(str.c_str());
}
str.assign ((const char *)data.GetData(&offset, 12), 12);
ar_date = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 6), 6);
ar_uid = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 6), 6);
ar_gid = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 8), 8);
ar_mode = strtoul(str.c_str(), &err, 8);
str.assign ((const char *)data.GetData(&offset, 10), 10);
ar_size = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 2), 2);
if (str == ARFMAG)
{
if (ar_name_len > 0)
{
str.assign ((const char *)data.GetData(&offset, ar_name_len), ar_name_len);
ar_name.SetCString (str.c_str());
}
ar_file_offset = offset;
ar_file_size = ar_size - ar_name_len;
return offset;
}
return LLDB_INVALID_INDEX32;
}
ObjectContainerBSDArchive::Archive::Archive
(
const lldb_private::ArchSpec &arch,
const lldb_private::TimeValue &time
) :
m_arch (arch),
m_time (time),
m_objects()
{
}
ObjectContainerBSDArchive::Archive::~Archive ()
{
}
size_t
ObjectContainerBSDArchive::Archive::ParseObjects (DataExtractor &data)
{
std::string str;
uint32_t offset = 0;
str.assign((const char *)data.GetData(&offset, SARMAG), SARMAG);
if (str == ARMAG)
{
Object obj;
do
{
offset = obj.Extract (data, offset);
if (offset == LLDB_INVALID_INDEX32)
break;
uint32_t obj_idx = m_objects.size();
m_objects.push_back(obj);
// Insert all of the C strings out of order for now...
m_object_name_to_index_map.Append (obj.ar_name.GetCString(), obj_idx);
offset += obj.ar_file_size;
obj.Clear();
} while (data.ValidOffset(offset));
// Now sort all of the object name pointers
m_object_name_to_index_map.Sort ();
}
return m_objects.size();
}
ObjectContainerBSDArchive::Object *
ObjectContainerBSDArchive::Archive::FindObject (const ConstString &object_name)
{
const UniqueCStringMap<uint32_t>::Entry *match = m_object_name_to_index_map.FindFirstValueForName (object_name.GetCString());
if (match)
return &m_objects[match->value];
return NULL;
}
ObjectContainerBSDArchive::Archive::shared_ptr
ObjectContainerBSDArchive::Archive::FindCachedArchive (const FileSpec &file, const ArchSpec &arch, const TimeValue &time)
{
Mutex::Locker locker(Archive::GetArchiveCacheMutex ());
shared_ptr archive_sp;
Archive::Map &archive_map = Archive::GetArchiveCache ();
Archive::Map::iterator pos = archive_map.find (file);
// Don't cache a value for "archive_map.end()" below since we might
// delete an archive entry...
while (pos != archive_map.end() && pos->first == file)
{
if (pos->second->GetArchitecture() == arch)
{
if (pos->second->GetModificationTime() == time)
{
return pos->second;
}
else
{
// We have a file at the same path with the same architecture
// whose modification time doesn't match. It doesn't make sense
// for us to continue to use this BSD archive since we cache only
// the object info which consists of file time info and also the
// file offset and file size of any contianed objects. Since
// this information is now out of date, we won't get the correct
// information if we go and extract the file data, so we should
// remove the old and outdated entry.
archive_map.erase (pos);
pos = archive_map.find (file);
continue;
}
}
++pos;
}
return archive_sp;
}
ObjectContainerBSDArchive::Archive::shared_ptr
ObjectContainerBSDArchive::Archive::ParseAndCacheArchiveForFile
(
const FileSpec &file,
const ArchSpec &arch,
const TimeValue &time,
DataExtractor &data
)
{
shared_ptr archive_sp(new Archive (arch, time));
if (archive_sp)
{
if (archive_sp->ParseObjects (data) > 0)
{
Mutex::Locker locker(Archive::GetArchiveCacheMutex ());
Archive::GetArchiveCache().insert(std::make_pair(file, archive_sp));
}
else
{
archive_sp.reset();
}
}
return archive_sp;
}
ObjectContainerBSDArchive::Archive::Map &
ObjectContainerBSDArchive::Archive::GetArchiveCache ()
{
static Archive::Map g_archive_map;
return g_archive_map;
}
Mutex &
ObjectContainerBSDArchive::Archive::GetArchiveCacheMutex ()
{
static Mutex g_archive_map_mutex (Mutex::eMutexTypeRecursive);
return g_archive_map_mutex;
}
void
ObjectContainerBSDArchive::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
}
void
ObjectContainerBSDArchive::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
const char *
ObjectContainerBSDArchive::GetPluginNameStatic()
{
return "object-container.bsd-archive";
}
const char *
ObjectContainerBSDArchive::GetPluginDescriptionStatic()
{
return "BSD Archive object container reader.";
}
ObjectContainer *
ObjectContainerBSDArchive::CreateInstance
(
Module* module,
DataBufferSP& data_sp,
const FileSpec *file,
addr_t file_offset,
addr_t file_size)
{
if (file && data_sp && ObjectContainerBSDArchive::MagicBytesMatch(data_sp))
{
Timer scoped_timer (__PRETTY_FUNCTION__,
"ObjectContainerBSDArchive::CreateInstance (module = %s/%s, file = %p, file_offset = 0x%z8.8x, file_size = 0x%z8.8x)",
module->GetFileSpec().GetDirectory().AsCString(),
module->GetFileSpec().GetFilename().AsCString(),
file, file_offset, file_size);
std::auto_ptr<ObjectContainerBSDArchive> container_ap(new ObjectContainerBSDArchive (module, data_sp, file, file_offset, file_size));
if (container_ap.get())
{
Archive::shared_ptr archive_sp (Archive::FindCachedArchive (*file, module->GetArchitecture(), module->GetModificationTime()));
if (archive_sp)
{
// We already have this archive in our cache, use it
container_ap->SetArchive (archive_sp);
return container_ap.release();
}
else
{
// Read everything since we need that in order to index all the
// objects in the archive
data_sp = file->MemoryMapFileContents (file_offset, file_size);
if (container_ap->ParseHeader())
return container_ap.release();
}
}
}
return NULL;
}
bool
ObjectContainerBSDArchive::MagicBytesMatch (DataBufferSP& dataSP)
{
DataExtractor data(dataSP, lldb::endian::InlHostByteOrder(), 4);
uint32_t offset = 0;
const char* armag = (const char* )data.PeekData (offset, sizeof(ar_hdr));
if (armag && ::strncmp(armag, ARMAG, SARMAG) == 0)
{
armag += offsetof(struct ar_hdr, ar_fmag) + SARMAG;
if (strncmp(armag, ARFMAG, 2) == 0)
return true;
}
return false;
}
ObjectContainerBSDArchive::ObjectContainerBSDArchive
(
Module* module,
DataBufferSP& dataSP,
const lldb_private::FileSpec *file,
lldb::addr_t offset,
lldb::addr_t size
) :
ObjectContainer (module, file, offset, size, dataSP),
m_archive_sp ()
{
}
void
ObjectContainerBSDArchive::SetArchive (Archive::shared_ptr &archive_sp)
{
m_archive_sp = archive_sp;
}
ObjectContainerBSDArchive::~ObjectContainerBSDArchive()
{
}
bool
ObjectContainerBSDArchive::ParseHeader ()
{
if (m_archive_sp.get() == NULL)
{
if (m_data.GetByteSize() > 0)
{
m_archive_sp = Archive::ParseAndCacheArchiveForFile (m_file,
m_module->GetArchitecture(),
m_module->GetModificationTime(),
m_data);
// The archive might be huge, so clear "m_data" to free up the
// memory since it will contain the entire file (possibly more than
// one architecture slice). We already have an index of all objects
// in the file, so we will be ready to serve up those objects.
m_data.Clear();
}
}
return m_archive_sp.get() != NULL;
}
void
ObjectContainerBSDArchive::Dump (Stream *s) const
{
s->Printf("%p: ", this);
s->Indent();
const size_t num_archs = GetNumArchitectures();
const size_t num_objects = GetNumObjects();
s->Printf("ObjectContainerBSDArchive, num_archs = %lu, num_objects = %lu", num_archs, num_objects);
uint32_t i;
ArchSpec arch;
s->IndentMore();
for (i=0; i<num_archs; i++)
{
s->Indent();
GetArchitectureAtIndex(i, arch);
s->Printf("arch[%u] = %s\n", i, arch.GetArchitectureName());
}
for (i=0; i<num_objects; i++)
{
s->Indent();
s->Printf("object[%u] = %s\n", i, GetObjectNameAtIndex (i));
}
s->IndentLess();
s->EOL();
}
ObjectFileSP
ObjectContainerBSDArchive::GetObjectFile (const FileSpec *file)
{
if (m_module->GetObjectName() && m_archive_sp)
{
Object *object = m_archive_sp->FindObject (m_module->GetObjectName());
if (object)
return ObjectFile::FindPlugin (m_module, file, m_offset + object->ar_file_offset, object->ar_file_size);
}
return ObjectFileSP();
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
ObjectContainerBSDArchive::GetPluginName()
{
return "object-container.bsd-archive";
}
const char *
ObjectContainerBSDArchive::GetShortPluginName()
{
return GetPluginNameStatic();
}
uint32_t
ObjectContainerBSDArchive::GetPluginVersion()
{
return 1;
}
<commit_msg>Revert some changes I did for logging that affected the ability to load .o files in BSD archive parsing.<commit_after>//===-- ObjectContainerBSDArchive.cpp ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ObjectContainerBSDArchive.h"
#include <ar.h>
#include "lldb/Core/Stream.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Mutex.h"
#include "lldb/Symbol/ObjectFile.h"
using namespace lldb;
using namespace lldb_private;
ObjectContainerBSDArchive::Object::Object() :
ar_name(),
ar_date(0),
ar_uid(0),
ar_gid(0),
ar_mode(0),
ar_size(0),
ar_file_offset(0),
ar_file_size(0)
{
}
void
ObjectContainerBSDArchive::Object::Clear()
{
ar_name.Clear();
ar_date = 0;
ar_uid = 0;
ar_gid = 0;
ar_mode = 0;
ar_size = 0;
ar_file_offset = 0;
ar_file_size = 0;
}
uint32_t
ObjectContainerBSDArchive::Object::Extract (const DataExtractor& data, uint32_t offset)
{
size_t ar_name_len = 0;
std::string str;
char *err;
str.assign ((const char *)data.GetData(&offset, 16), 16);
if (str.find("#1/") == 0)
{
// If the name is longer than 16 bytes, or contains an embedded space
// then it will use this format where the length of the name is
// here and the name characters are after this header.
ar_name_len = strtoul(str.c_str() + 3, &err, 10);
}
else
{
// Strip off any spaces (if the object file name contains spaces it
// will use the extended format above).
str.erase (str.find(' '));
ar_name.SetCString(str.c_str());
}
str.assign ((const char *)data.GetData(&offset, 12), 12);
ar_date = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 6), 6);
ar_uid = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 6), 6);
ar_gid = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 8), 8);
ar_mode = strtoul(str.c_str(), &err, 8);
str.assign ((const char *)data.GetData(&offset, 10), 10);
ar_size = strtoul(str.c_str(), &err, 10);
str.assign ((const char *)data.GetData(&offset, 2), 2);
if (str == ARFMAG)
{
if (ar_name_len > 0)
{
str.assign ((const char *)data.GetData(&offset, ar_name_len), ar_name_len);
ar_name.SetCString (str.c_str());
}
ar_file_offset = offset;
ar_file_size = ar_size - ar_name_len;
return offset;
}
return LLDB_INVALID_INDEX32;
}
ObjectContainerBSDArchive::Archive::Archive
(
const lldb_private::ArchSpec &arch,
const lldb_private::TimeValue &time
) :
m_arch (arch),
m_time (time),
m_objects()
{
}
ObjectContainerBSDArchive::Archive::~Archive ()
{
}
size_t
ObjectContainerBSDArchive::Archive::ParseObjects (DataExtractor &data)
{
std::string str;
uint32_t offset = 0;
str.assign((const char *)data.GetData(&offset, SARMAG), SARMAG);
if (str == ARMAG)
{
Object obj;
do
{
offset = obj.Extract (data, offset);
if (offset == LLDB_INVALID_INDEX32)
break;
uint32_t obj_idx = m_objects.size();
m_objects.push_back(obj);
// Insert all of the C strings out of order for now...
m_object_name_to_index_map.Append (obj.ar_name.GetCString(), obj_idx);
offset += obj.ar_file_size;
obj.Clear();
} while (data.ValidOffset(offset));
// Now sort all of the object name pointers
m_object_name_to_index_map.Sort ();
}
return m_objects.size();
}
ObjectContainerBSDArchive::Object *
ObjectContainerBSDArchive::Archive::FindObject (const ConstString &object_name)
{
const UniqueCStringMap<uint32_t>::Entry *match = m_object_name_to_index_map.FindFirstValueForName (object_name.GetCString());
if (match)
return &m_objects[match->value];
return NULL;
}
ObjectContainerBSDArchive::Archive::shared_ptr
ObjectContainerBSDArchive::Archive::FindCachedArchive (const FileSpec &file, const ArchSpec &arch, const TimeValue &time)
{
Mutex::Locker locker(Archive::GetArchiveCacheMutex ());
shared_ptr archive_sp;
Archive::Map &archive_map = Archive::GetArchiveCache ();
Archive::Map::iterator pos = archive_map.find (file);
// Don't cache a value for "archive_map.end()" below since we might
// delete an archive entry...
while (pos != archive_map.end() && pos->first == file)
{
if (pos->second->GetArchitecture() == arch)
{
if (pos->second->GetModificationTime() == time)
{
return pos->second;
}
else
{
// We have a file at the same path with the same architecture
// whose modification time doesn't match. It doesn't make sense
// for us to continue to use this BSD archive since we cache only
// the object info which consists of file time info and also the
// file offset and file size of any contianed objects. Since
// this information is now out of date, we won't get the correct
// information if we go and extract the file data, so we should
// remove the old and outdated entry.
archive_map.erase (pos);
pos = archive_map.find (file);
continue;
}
}
++pos;
}
return archive_sp;
}
ObjectContainerBSDArchive::Archive::shared_ptr
ObjectContainerBSDArchive::Archive::ParseAndCacheArchiveForFile
(
const FileSpec &file,
const ArchSpec &arch,
const TimeValue &time,
DataExtractor &data
)
{
shared_ptr archive_sp(new Archive (arch, time));
if (archive_sp)
{
if (archive_sp->ParseObjects (data) > 0)
{
Mutex::Locker locker(Archive::GetArchiveCacheMutex ());
Archive::GetArchiveCache().insert(std::make_pair(file, archive_sp));
}
else
{
archive_sp.reset();
}
}
return archive_sp;
}
ObjectContainerBSDArchive::Archive::Map &
ObjectContainerBSDArchive::Archive::GetArchiveCache ()
{
static Archive::Map g_archive_map;
return g_archive_map;
}
Mutex &
ObjectContainerBSDArchive::Archive::GetArchiveCacheMutex ()
{
static Mutex g_archive_map_mutex (Mutex::eMutexTypeRecursive);
return g_archive_map_mutex;
}
void
ObjectContainerBSDArchive::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
}
void
ObjectContainerBSDArchive::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
const char *
ObjectContainerBSDArchive::GetPluginNameStatic()
{
return "object-container.bsd-archive";
}
const char *
ObjectContainerBSDArchive::GetPluginDescriptionStatic()
{
return "BSD Archive object container reader.";
}
ObjectContainer *
ObjectContainerBSDArchive::CreateInstance
(
Module* module,
DataBufferSP& data_sp,
const FileSpec *file,
addr_t offset,
addr_t length)
{
if (file && data_sp && ObjectContainerBSDArchive::MagicBytesMatch(data_sp))
{
Timer scoped_timer (__PRETTY_FUNCTION__,
"ObjectContainerBSDArchive::CreateInstance (module = %s/%s, file = %p, file_offset = 0x%z8.8x, file_size = 0x%z8.8x)",
module->GetFileSpec().GetDirectory().AsCString(),
module->GetFileSpec().GetFilename().AsCString(),
file, offset, length);
Archive::shared_ptr archive_sp (Archive::FindCachedArchive (*file, module->GetArchitecture(), module->GetModificationTime()));
if (archive_sp)
{
// We already have this archive in our cache, use it
std::auto_ptr<ObjectContainerBSDArchive> container_ap(new ObjectContainerBSDArchive (module, data_sp, file, offset, length));
if (container_ap.get())
{
container_ap->SetArchive (archive_sp);
return container_ap.release();
}
}
// Read everything since we need that in order to index all the
// objects in the archive
data_sp = file->MemoryMapFileContents (offset, length);
std::auto_ptr<ObjectContainerBSDArchive> container_ap(new ObjectContainerBSDArchive (module, data_sp, file, offset, length));
if (container_ap->ParseHeader())
return container_ap.release();
}
return NULL;
}
bool
ObjectContainerBSDArchive::MagicBytesMatch (DataBufferSP& dataSP)
{
DataExtractor data(dataSP, lldb::endian::InlHostByteOrder(), 4);
uint32_t offset = 0;
const char* armag = (const char* )data.PeekData (offset, sizeof(ar_hdr));
if (armag && ::strncmp(armag, ARMAG, SARMAG) == 0)
{
armag += offsetof(struct ar_hdr, ar_fmag) + SARMAG;
if (strncmp(armag, ARFMAG, 2) == 0)
return true;
}
return false;
}
ObjectContainerBSDArchive::ObjectContainerBSDArchive
(
Module* module,
DataBufferSP& dataSP,
const lldb_private::FileSpec *file,
lldb::addr_t offset,
lldb::addr_t size
) :
ObjectContainer (module, file, offset, size, dataSP),
m_archive_sp ()
{
}
void
ObjectContainerBSDArchive::SetArchive (Archive::shared_ptr &archive_sp)
{
m_archive_sp = archive_sp;
}
ObjectContainerBSDArchive::~ObjectContainerBSDArchive()
{
}
bool
ObjectContainerBSDArchive::ParseHeader ()
{
if (m_archive_sp.get() == NULL)
{
if (m_data.GetByteSize() > 0)
{
m_archive_sp = Archive::ParseAndCacheArchiveForFile (m_file,
m_module->GetArchitecture(),
m_module->GetModificationTime(),
m_data);
// The archive might be huge, so clear "m_data" to free up the
// memory since it will contain the entire file (possibly more than
// one architecture slice). We already have an index of all objects
// in the file, so we will be ready to serve up those objects.
m_data.Clear();
}
}
return m_archive_sp.get() != NULL;
}
void
ObjectContainerBSDArchive::Dump (Stream *s) const
{
s->Printf("%p: ", this);
s->Indent();
const size_t num_archs = GetNumArchitectures();
const size_t num_objects = GetNumObjects();
s->Printf("ObjectContainerBSDArchive, num_archs = %lu, num_objects = %lu", num_archs, num_objects);
uint32_t i;
ArchSpec arch;
s->IndentMore();
for (i=0; i<num_archs; i++)
{
s->Indent();
GetArchitectureAtIndex(i, arch);
s->Printf("arch[%u] = %s\n", i, arch.GetArchitectureName());
}
for (i=0; i<num_objects; i++)
{
s->Indent();
s->Printf("object[%u] = %s\n", i, GetObjectNameAtIndex (i));
}
s->IndentLess();
s->EOL();
}
ObjectFileSP
ObjectContainerBSDArchive::GetObjectFile (const FileSpec *file)
{
if (m_module->GetObjectName() && m_archive_sp)
{
Object *object = m_archive_sp->FindObject (m_module->GetObjectName());
if (object)
return ObjectFile::FindPlugin (m_module, file, m_offset + object->ar_file_offset, object->ar_file_size);
}
return ObjectFileSP();
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
ObjectContainerBSDArchive::GetPluginName()
{
return "object-container.bsd-archive";
}
const char *
ObjectContainerBSDArchive::GetShortPluginName()
{
return GetPluginNameStatic();
}
uint32_t
ObjectContainerBSDArchive::GetPluginVersion()
{
return 1;
}
<|endoftext|> |
<commit_before><commit_msg>Fix impalad crash: impala::LlvmCodeGen::OptimizeModule()<commit_after><|endoftext|> |
<commit_before>//
// Copyright (c) 2015 - 2016 CNRS
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/multibody/joint.hpp"
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/algorithm/crba.hpp"
#include "pinocchio/algorithm/rnea.hpp"
#include "pinocchio/algorithm/non-linear-effects.hpp"
#include "pinocchio/algorithm/cholesky.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include "pinocchio/simulation/compute-all-terms.hpp"
#include "pinocchio/algorithm/kinematics.hpp"
#include "pinocchio/algorithm/collisions.hpp"
#include "pinocchio/multibody/parser/urdf.hpp"
#include "pinocchio/multibody/parser/sample-models.hpp"
#include "pinocchio/multibody/geometry.hpp"
#include "pinocchio/multibody/parser/urdf-with-geometry.hpp"
#ifdef WITH_HPP_MODEL_URDF
#include <hpp/util/debug.hh>
#include <hpp/model/device.hh>
#include <hpp/model/body.hh>
#include <hpp/model/collision-object.hh>
#include <hpp/model/joint.hh>
#include <hpp/model/urdf/util.hh>
#endif
#include <iostream>
#include "pinocchio/tools/timer.hpp"
#include <Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)
int main()
{
using namespace Eigen;
using namespace se3;
StackTicToc timer(StackTicToc::US);
#ifdef NDEBUG
const unsigned int NBT = 1000*100;
const unsigned int NBD = 1000; // for heavy tests, like computeDistances()
#else
const unsigned int NBT = 1;
const unsigned int NBD = 1;
std::cout << "(the time score in debug mode is not relevant) " << std::endl;
#endif
std::string romeo_filename = PINOCCHIO_SOURCE_DIR"/models/romeo.urdf";
std::string romeo_meshDir = PINOCCHIO_SOURCE_DIR"/models/";
std::pair < Model, GeometryModel > romeo = se3::urdf::buildModelAndGeom(romeo_filename, romeo_meshDir, se3::JointModelFreeFlyer());
se3::Model romeo_model = romeo.first;
se3::GeometryModel romeo_model_geom = romeo.second;
Data romeo_data(romeo_model);
GeometryData romeo_data_geom(romeo_data, romeo_model_geom);
std::vector<VectorXd> qs_romeo (NBT);
std::vector<VectorXd> qdots_romeo (NBT);
std::vector<VectorXd> qddots_romeo (NBT);
for(size_t i=0;i<NBT;++i)
{
qs_romeo[i] = Eigen::VectorXd::Random(romeo_model.nq);
qs_romeo[i].segment<4>(3) /= qs_romeo[i].segment<4>(3).norm();
qdots_romeo[i] = Eigen::VectorXd::Random(romeo_model.nv);
qddots_romeo[i] = Eigen::VectorXd::Random(romeo_model.nv);
}
timer.tic();
SMOOTH(NBT)
{
geometry(romeo_model,romeo_data,qs_romeo[_smooth]);
}
double geom_time = timer.toc(StackTicToc::US)/NBT;
timer.tic();
SMOOTH(NBT)
{
updateCollisionGeometry(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth], true);
}
double update_col_time = timer.toc(StackTicToc::US)/NBT - geom_time;
std::cout << "Update Collision Geometry < false > = \t" << update_col_time << " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
updateCollisionGeometry(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth], true);
for (std::vector<se3::GeometryData::CollisionPair_t>::iterator it = romeo_data_geom.collision_pairs.begin(); it != romeo_data_geom.collision_pairs.end(); ++it)
{
romeo_data_geom.collide(it->first, it->second);
}
}
double collideTime = timer.toc(StackTicToc::US)/NBT - (update_col_time + geom_time);
std::cout << "Collision test between two geometry objects (mean time) = \t" << collideTime / romeo_data_geom.nCollisionPairs
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeCollisions(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth], true);
}
double is_colliding_time = timer.toc(StackTicToc::US)/NBT - (update_col_time + geom_time);
std::cout << "Collision Test : robot in collision? = \t" << is_colliding_time
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeDistances(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth]);
}
double computeDistancesTime = timer.toc(StackTicToc::US)/NBT - (update_col_time + geom_time);
std::cout << "Compute distance between two geometry objects (mean time) = \t" << computeDistancesTime / romeo_data_geom.nCollisionPairs
<< " " << StackTicToc::unitName(StackTicToc::US) << " " << romeo_data_geom.nCollisionPairs << " col pairs" << std::endl;
#ifdef WITH_HPP_MODEL_URDF
std::vector<VectorXd> qs_romeo_pino (NBT);
std::vector<VectorXd> qdots_romeo_pino (NBT);
std::vector<VectorXd> qddots_romeo_pino (NBT);
for(size_t i=0;i<NBT;++i)
{
qs_romeo_pino[i] = Eigen::VectorXd::Random(romeo_model.nq);
qs_romeo_pino[i].segment<4>(3) /= qs_romeo_pino[i].segment<4>(3).norm();
qdots_romeo_pino[i] = Eigen::VectorXd::Random(romeo_model.nv);
qddots_romeo_pino[i] = Eigen::VectorXd::Random(romeo_model.nv);
}
std::vector<VectorXd> qs_romeo_hpp (qs_romeo_pino);
std::vector<VectorXd> qdots_romeo_hpp (qdots_romeo_pino);
std::vector<VectorXd> qddots_romeo_hpp (qddots_romeo_pino);
for (size_t i = 0; i < NBT; ++i)
{
Vector4d quaternion;
quaternion << qs_romeo_pino[i][6], qs_romeo_pino[i][3], qs_romeo_pino[i][4], qs_romeo_pino[i][5];
qs_romeo_hpp[i].segment<4>(3) = quaternion ;
}
// /// ************* HPP ************* ///
// /// ********************************* ///
hpp::model::HumanoidRobotPtr_t humanoidRobot =
hpp::model::HumanoidRobot::create ("romeo");
hpp::model::urdf::loadHumanoidModel(humanoidRobot, "freeflyer",
"romeo_pinocchio", "romeo",
"", "");
timer.tic();
SMOOTH(NBT)
{
updateCollisionGeometry(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo_pino[_smooth], true);
}
double compute_forward_kinematics_time = timer.toc(StackTicToc::US)/NBT;
std::cout << "Update Collision Geometry < true > (K) = \t" << compute_forward_kinematics_time << " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->currentConfiguration (qs_romeo_hpp[_smooth]);
humanoidRobot->computeForwardKinematics ();
}
double compute_forward_kinematics_time_hpp = timer.toc(StackTicToc::US)/NBT;
std::cout << "HPP - Compute Forward Kinematics (K) = \t" << compute_forward_kinematics_time_hpp
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeCollisions(romeo_data_geom, true);
}
double is_romeo_colliding_time_pino = timer.toc(StackTicToc::US)/NBT;
std::cout << "Pinocchio - Collision Test : robot in collision? (G) = \t" << is_romeo_colliding_time_pino
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->collisionTest();
}
double is_romeo_colliding_time_hpp = timer.toc(StackTicToc::US)/NBT;
std::cout << "HPP - Collision Test : robot in collision? (G)= \t" << is_romeo_colliding_time_hpp
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeCollisions(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo_pino[_smooth], true);
}
is_romeo_colliding_time_pino = timer.toc(StackTicToc::US)/NBT;
std::cout << "Pinocchio - Collision Test : update + robot in collision? (K+G)= \t" << is_romeo_colliding_time_pino
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->currentConfiguration (qs_romeo_hpp[_smooth]);
humanoidRobot->computeForwardKinematics ();
humanoidRobot->collisionTest();
}
is_romeo_colliding_time_hpp = timer.toc(StackTicToc::US)/NBT;
std::cout << "HPP - Collision Test : update + robot in collision? (K+G) = \t" << is_romeo_colliding_time_hpp
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeDistances(romeo_data_geom);
}
computeDistancesTime = timer.toc(StackTicToc::US)/NBT ;
std::cout << "Pinocchio - Compute distances (D) " << romeo_data_geom.nCollisionPairs << " col pairs\t" << computeDistancesTime
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->computeDistances ();
}
double hpp_compute_distances = timer.toc(StackTicToc::US)/NBT ;
std::cout << "HPP - Compute distances (D) " << humanoidRobot->distanceResults().size() << " col pairs\t" << hpp_compute_distances
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeDistances(romeo_model, romeo_data, romeo_model_geom, romeo_data_geom, qs_romeo_pino[_smooth]);
}
computeDistancesTime = timer.toc(StackTicToc::US)/NBT ;
std::cout << "Pinocchio - Update + Compute distances (K+D) " << romeo_data_geom.nCollisionPairs << " col pairs\t" << computeDistancesTime
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->currentConfiguration (qs_romeo_hpp[_smooth]);
humanoidRobot->computeForwardKinematics ();
humanoidRobot->computeDistances ();
}
hpp_compute_distances = timer.toc(StackTicToc::US)/NBT ;
std::cout << "HPP - Update + Compute distances (K+D) " << humanoidRobot->distanceResults().size() << " col pairs\t" << hpp_compute_distances
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
#endif
return 0;
}
<commit_msg>[C++][Fix Bug] Update function name according to the new API<commit_after>//
// Copyright (c) 2015 - 2016 CNRS
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/multibody/joint.hpp"
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/algorithm/crba.hpp"
#include "pinocchio/algorithm/rnea.hpp"
#include "pinocchio/algorithm/non-linear-effects.hpp"
#include "pinocchio/algorithm/cholesky.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include "pinocchio/simulation/compute-all-terms.hpp"
#include "pinocchio/algorithm/kinematics.hpp"
#include "pinocchio/algorithm/collisions.hpp"
#include "pinocchio/multibody/parser/urdf.hpp"
#include "pinocchio/multibody/parser/sample-models.hpp"
#include "pinocchio/multibody/geometry.hpp"
#include "pinocchio/multibody/parser/urdf-with-geometry.hpp"
#ifdef WITH_HPP_MODEL_URDF
#include <hpp/util/debug.hh>
#include <hpp/model/device.hh>
#include <hpp/model/body.hh>
#include <hpp/model/collision-object.hh>
#include <hpp/model/joint.hh>
#include <hpp/model/urdf/util.hh>
#endif
#include <iostream>
#include "pinocchio/tools/timer.hpp"
#include <Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)
int main()
{
using namespace Eigen;
using namespace se3;
StackTicToc timer(StackTicToc::US);
#ifdef NDEBUG
const unsigned int NBT = 1000*100;
const unsigned int NBD = 1000; // for heavy tests, like computeDistances()
#else
const unsigned int NBT = 1;
const unsigned int NBD = 1;
std::cout << "(the time score in debug mode is not relevant) " << std::endl;
#endif
std::string romeo_filename = PINOCCHIO_SOURCE_DIR"/models/romeo.urdf";
std::string romeo_meshDir = PINOCCHIO_SOURCE_DIR"/models/";
std::pair < Model, GeometryModel > romeo = se3::urdf::buildModelAndGeom(romeo_filename, romeo_meshDir, se3::JointModelFreeFlyer());
se3::Model romeo_model = romeo.first;
se3::GeometryModel romeo_model_geom = romeo.second;
Data romeo_data(romeo_model);
GeometryData romeo_data_geom(romeo_data, romeo_model_geom);
std::vector<VectorXd> qs_romeo (NBT);
std::vector<VectorXd> qdots_romeo (NBT);
std::vector<VectorXd> qddots_romeo (NBT);
for(size_t i=0;i<NBT;++i)
{
qs_romeo[i] = Eigen::VectorXd::Random(romeo_model.nq);
qs_romeo[i].segment<4>(3) /= qs_romeo[i].segment<4>(3).norm();
qdots_romeo[i] = Eigen::VectorXd::Random(romeo_model.nv);
qddots_romeo[i] = Eigen::VectorXd::Random(romeo_model.nv);
}
timer.tic();
SMOOTH(NBT)
{
forwardKinematics(romeo_model,romeo_data,qs_romeo[_smooth]);
}
double geom_time = timer.toc(StackTicToc::US)/NBT;
timer.tic();
SMOOTH(NBT)
{
updateCollisionGeometry(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth], true);
}
double update_col_time = timer.toc(StackTicToc::US)/NBT - geom_time;
std::cout << "Update Collision Geometry < false > = \t" << update_col_time << " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
updateCollisionGeometry(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth], true);
for (std::vector<se3::GeometryData::CollisionPair_t>::iterator it = romeo_data_geom.collision_pairs.begin(); it != romeo_data_geom.collision_pairs.end(); ++it)
{
romeo_data_geom.collide(it->first, it->second);
}
}
double collideTime = timer.toc(StackTicToc::US)/NBT - (update_col_time + geom_time);
std::cout << "Collision test between two geometry objects (mean time) = \t" << collideTime / romeo_data_geom.nCollisionPairs
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeCollisions(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth], true);
}
double is_colliding_time = timer.toc(StackTicToc::US)/NBT - (update_col_time + geom_time);
std::cout << "Collision Test : robot in collision? = \t" << is_colliding_time
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeDistances(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo[_smooth]);
}
double computeDistancesTime = timer.toc(StackTicToc::US)/NBT - (update_col_time + geom_time);
std::cout << "Compute distance between two geometry objects (mean time) = \t" << computeDistancesTime / romeo_data_geom.nCollisionPairs
<< " " << StackTicToc::unitName(StackTicToc::US) << " " << romeo_data_geom.nCollisionPairs << " col pairs" << std::endl;
#ifdef WITH_HPP_MODEL_URDF
std::vector<VectorXd> qs_romeo_pino (NBT);
std::vector<VectorXd> qdots_romeo_pino (NBT);
std::vector<VectorXd> qddots_romeo_pino (NBT);
for(size_t i=0;i<NBT;++i)
{
qs_romeo_pino[i] = Eigen::VectorXd::Random(romeo_model.nq);
qs_romeo_pino[i].segment<4>(3) /= qs_romeo_pino[i].segment<4>(3).norm();
qdots_romeo_pino[i] = Eigen::VectorXd::Random(romeo_model.nv);
qddots_romeo_pino[i] = Eigen::VectorXd::Random(romeo_model.nv);
}
std::vector<VectorXd> qs_romeo_hpp (qs_romeo_pino);
std::vector<VectorXd> qdots_romeo_hpp (qdots_romeo_pino);
std::vector<VectorXd> qddots_romeo_hpp (qddots_romeo_pino);
for (size_t i = 0; i < NBT; ++i)
{
Vector4d quaternion;
quaternion << qs_romeo_pino[i][6], qs_romeo_pino[i][3], qs_romeo_pino[i][4], qs_romeo_pino[i][5];
qs_romeo_hpp[i].segment<4>(3) = quaternion ;
}
// /// ************* HPP ************* ///
// /// ********************************* ///
hpp::model::HumanoidRobotPtr_t humanoidRobot =
hpp::model::HumanoidRobot::create ("romeo");
hpp::model::urdf::loadHumanoidModel(humanoidRobot, "freeflyer",
"romeo_pinocchio", "romeo",
"", "");
timer.tic();
SMOOTH(NBT)
{
updateCollisionGeometry(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo_pino[_smooth], true);
}
double compute_forward_kinematics_time = timer.toc(StackTicToc::US)/NBT;
std::cout << "Update Collision Geometry < true > (K) = \t" << compute_forward_kinematics_time << " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->currentConfiguration (qs_romeo_hpp[_smooth]);
humanoidRobot->computeForwardKinematics ();
}
double compute_forward_kinematics_time_hpp = timer.toc(StackTicToc::US)/NBT;
std::cout << "HPP - Compute Forward Kinematics (K) = \t" << compute_forward_kinematics_time_hpp
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeCollisions(romeo_data_geom, true);
}
double is_romeo_colliding_time_pino = timer.toc(StackTicToc::US)/NBT;
std::cout << "Pinocchio - Collision Test : robot in collision? (G) = \t" << is_romeo_colliding_time_pino
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->collisionTest();
}
double is_romeo_colliding_time_hpp = timer.toc(StackTicToc::US)/NBT;
std::cout << "HPP - Collision Test : robot in collision? (G)= \t" << is_romeo_colliding_time_hpp
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeCollisions(romeo_model,romeo_data,romeo_model_geom,romeo_data_geom,qs_romeo_pino[_smooth], true);
}
is_romeo_colliding_time_pino = timer.toc(StackTicToc::US)/NBT;
std::cout << "Pinocchio - Collision Test : update + robot in collision? (K+G)= \t" << is_romeo_colliding_time_pino
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->currentConfiguration (qs_romeo_hpp[_smooth]);
humanoidRobot->computeForwardKinematics ();
humanoidRobot->collisionTest();
}
is_romeo_colliding_time_hpp = timer.toc(StackTicToc::US)/NBT;
std::cout << "HPP - Collision Test : update + robot in collision? (K+G) = \t" << is_romeo_colliding_time_hpp
<< StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeDistances(romeo_data_geom);
}
computeDistancesTime = timer.toc(StackTicToc::US)/NBT ;
std::cout << "Pinocchio - Compute distances (D) " << romeo_data_geom.nCollisionPairs << " col pairs\t" << computeDistancesTime
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->computeDistances ();
}
double hpp_compute_distances = timer.toc(StackTicToc::US)/NBT ;
std::cout << "HPP - Compute distances (D) " << humanoidRobot->distanceResults().size() << " col pairs\t" << hpp_compute_distances
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
computeDistances(romeo_model, romeo_data, romeo_model_geom, romeo_data_geom, qs_romeo_pino[_smooth]);
}
computeDistancesTime = timer.toc(StackTicToc::US)/NBT ;
std::cout << "Pinocchio - Update + Compute distances (K+D) " << romeo_data_geom.nCollisionPairs << " col pairs\t" << computeDistancesTime
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
timer.tic();
SMOOTH(NBT)
{
humanoidRobot->currentConfiguration (qs_romeo_hpp[_smooth]);
humanoidRobot->computeForwardKinematics ();
humanoidRobot->computeDistances ();
}
hpp_compute_distances = timer.toc(StackTicToc::US)/NBT ;
std::cout << "HPP - Update + Compute distances (K+D) " << humanoidRobot->distanceResults().size() << " col pairs\t" << hpp_compute_distances
<< " " << StackTicToc::unitName(StackTicToc::US) << std::endl;
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include "stft_client.h"
#include "app_globals.h"
#include "audio_nodes.h"
#include "recorder_node.h"
#include "stft_request.h"
#include "stft_client_storage.h"
#include <cinder/audio/dsp/Fft.h>
#include <cinder/audio/Buffer.h>
#include <cinder/CinderMath.h>
#include <mutex>
#include <thread>
#include <tuple>
namespace cieq {
namespace stft {
namespace {
/*!
* \struct ClientResources
* \brief internal storage for a thread, therefore multiple
* threads running at the same time do not share an FFT session.
*/
thread_local static struct ClientResources
{
ClientStorage* mPrivateStorage;
} _resources;
static class ClientResourcesAllocator
{
public:
void allocate( const Client::Format& fmt,
ClientResources& local_rsc)
{
std::lock_guard<std::mutex> _lock(mResourceLock);
mPrivateMemory.push_back(std::make_unique<ClientStorage>(fmt));
local_rsc.mPrivateStorage = mPrivateMemory.back().get();
}
private:
std::mutex mResourceLock;
/* mind: blown. */
std::vector < std::unique_ptr < ClientStorage > >
mPrivateMemory;
} _resources_allocator;
} //!namespace
Client::Client(work::Manager& m, AppGlobals* g /*= nullptr*/, Format fmt /*= Format()*/)
: work::Client(m)
, mFormat(fmt)
, mGlobals(g)
{}
void Client::handle(work::RequestRef req)
{
// Allocate once per thread.
thread_local static bool _ready = false;
if (!_ready)
{
// pass thread's local storage to the allocator function
_resources_allocator.allocate( mFormat, _resources );
_ready = true;
}
auto request_ptr = static_cast<stft::Request*>(req.get());
auto recorder_ptr = mGlobals->getAudioNodes().getBufferRecorderNode();
auto renderer_ptr = mGlobals->getThreadRenderer();
recorder_ptr->popBufferWindow(_resources.mPrivateStorage->mCopiedBuffer, request_ptr->getQueryPos());
// window the copied buffer and compute forward FFT transform
if (_resources.mPrivateStorage->mChannelSize > 1) {
// naive average of all channels
_resources.mPrivateStorage->mFftBuffer.zero();
float scale = 1.0f / _resources.mPrivateStorage->mChannelSize;
for (size_t ch = 0; ch < _resources.mPrivateStorage->mChannelSize; ch++) {
for (size_t i = 0; i < _resources.mPrivateStorage->mWindowSize; i++)
_resources.mPrivateStorage->mFftBuffer[i] += _resources.mPrivateStorage->mCopiedBuffer.getChannel(ch)[i] * scale;
}
ci::audio::dsp::mul( _resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowingTable.get(),
_resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowSize);
}
else
ci::audio::dsp::mul( _resources.mPrivateStorage->mCopiedBuffer.getData(),
_resources.mPrivateStorage->mWindowingTable.get(),
_resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowSize);
_resources.mPrivateStorage->mFft->forward(&_resources.mPrivateStorage->mFftBuffer, &_resources.mPrivateStorage->mBufferSpectral);
float *real = _resources.mPrivateStorage->mBufferSpectral.getReal();
float *imag = _resources.mPrivateStorage->mBufferSpectral.getImag();
// remove Nyquist component
imag[0] = 0.0f;
// compute normalized magnitude spectrum
// TODO: break this into vector Cartesian -> polar and then vector lowpass. skip lowpass if smoothing factor is very small
const float magScale = 1.0f / _resources.mPrivateStorage->mFft->getSize();
for (size_t i = 0; i < _resources.mPrivateStorage->mMagSpectrum.size(); i++) {
float re = real[i];
float im = imag[i];
_resources.mPrivateStorage->mMagSpectrum[i] =
_resources.mPrivateStorage->mMagSpectrum[i] *
_resources.mPrivateStorage->mSmoothingFactor +
ci::math<float>::sqrt(re * re + im * im) *
magScale * (1 - _resources.mPrivateStorage->mSmoothingFactor);
}
const auto pos = request_ptr->getQueryPos();
const auto surface_index = renderer_ptr->getSurfaceIndexByQueryPos(pos);
const auto index_in_surface = renderer_ptr->getIndexInSurfaceByQueryPos(pos);
renderer_ptr->getSurface(surface_index).fillRow(index_in_surface, _resources.mPrivateStorage->mMagSpectrum);
}
Client::Format& Client::Format::windowSize(std::size_t size)
{
mWindowSize = size; return *this;
}
Client::Format& Client::Format::fftSize(std::size_t size)
{
mFftSize = size; return *this;
}
std::size_t Client::Format::getWindowSize() const
{
return mWindowSize;
}
std::size_t Client::Format::getFftSize() const
{
return mFftSize;
}
Client::Format& Client::Format::channels(std::size_t size)
{
mChannels = size;
return *this;
}
std::size_t Client::Format::getChannelSize() const
{
return mChannels;
}
Client::Format& Client::Format::windowType(ci::audio::dsp::WindowType type)
{
mWindowType = type; return *this;
}
ci::audio::dsp::WindowType Client::Format::getWindowType() const
{
return mWindowType;
}
}
} //!cieq::stft<commit_msg>I wonder if this really needs to be copied every window<commit_after>#include "stft_client.h"
#include "app_globals.h"
#include "audio_nodes.h"
#include "recorder_node.h"
#include "stft_request.h"
#include "stft_client_storage.h"
#include <cinder/audio/dsp/Fft.h>
#include <cinder/audio/Buffer.h>
#include <cinder/CinderMath.h>
#include <mutex>
#include <thread>
#include <tuple>
namespace cieq {
namespace stft {
namespace {
/*!
* \struct ClientResources
* \brief internal storage for a thread, therefore multiple
* threads running at the same time do not share an FFT session.
*/
thread_local static struct ClientResources
{
ClientStorage* mPrivateStorage;
} _resources;
static class ClientResourcesAllocator
{
public:
void allocate( const Client::Format& fmt,
ClientResources& local_rsc)
{
std::lock_guard<std::mutex> _lock(mResourceLock);
mPrivateMemory.push_back(std::make_unique<ClientStorage>(fmt));
local_rsc.mPrivateStorage = mPrivateMemory.back().get();
}
private:
std::mutex mResourceLock;
/* mind: blown. */
std::vector < std::unique_ptr < ClientStorage > >
mPrivateMemory;
} _resources_allocator;
} //!namespace
Client::Client(work::Manager& m, AppGlobals* g /*= nullptr*/, Format fmt /*= Format()*/)
: work::Client(m)
, mFormat(fmt)
, mGlobals(g)
{}
void Client::handle(work::RequestRef req)
{
// Allocate once per thread.
thread_local static bool _ready = false;
if (!_ready)
{
// pass thread's local storage to the allocator function
_resources_allocator.allocate( mFormat, _resources );
_ready = true;
}
auto request_ptr = static_cast<stft::Request*>(req.get());
auto recorder_ptr = mGlobals->getAudioNodes().getBufferRecorderNode();
auto renderer_ptr = mGlobals->getThreadRenderer();
recorder_ptr->popBufferWindow(_resources.mPrivateStorage->mCopiedBuffer, request_ptr->getQueryPos());
// window the copied buffer and compute forward FFT transform
if (_resources.mPrivateStorage->mChannelSize > 1) {
// naive average of all channels
_resources.mPrivateStorage->mFftBuffer.zero();
float scale = 1.0f / _resources.mPrivateStorage->mChannelSize;
for (size_t ch = 0; ch < _resources.mPrivateStorage->mChannelSize; ch++) {
for (size_t i = 0; i < _resources.mPrivateStorage->mWindowSize; i++)
_resources.mPrivateStorage->mFftBuffer[i] += _resources.mPrivateStorage->mCopiedBuffer.getChannel(ch)[i] * scale;
}
ci::audio::dsp::mul( _resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowingTable.get(),
_resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowSize);
}
else
ci::audio::dsp::mul( _resources.mPrivateStorage->mCopiedBuffer.getData(),
_resources.mPrivateStorage->mWindowingTable.get(),
_resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowSize);
_resources.mPrivateStorage->mFft->forward(&_resources.mPrivateStorage->mFftBuffer, &_resources.mPrivateStorage->mBufferSpectral);
float *real = _resources.mPrivateStorage->mBufferSpectral.getReal();
float *imag = _resources.mPrivateStorage->mBufferSpectral.getImag();
// remove Nyquist component
imag[0] = 0.0f;
// compute normalized magnitude spectrum
// TODO: break this into vector Cartesian -> polar and then vector lowpass. skip lowpass if smoothing factor is very small
const float magScale = 1.0f / _resources.mPrivateStorage->mFft->getSize();
for (size_t i = 0; i < _resources.mPrivateStorage->mMagSpectrum.size(); i++) {
const float& re = real[i];
const float& im = imag[i];
_resources.mPrivateStorage->mMagSpectrum[i] =
_resources.mPrivateStorage->mMagSpectrum[i] *
_resources.mPrivateStorage->mSmoothingFactor +
ci::math<float>::sqrt(re * re + im * im) *
magScale * (1 - _resources.mPrivateStorage->mSmoothingFactor);
}
const auto pos = request_ptr->getQueryPos();
const auto surface_index = renderer_ptr->getSurfaceIndexByQueryPos(pos);
const auto index_in_surface = renderer_ptr->getIndexInSurfaceByQueryPos(pos);
renderer_ptr->getSurface(surface_index).fillRow(index_in_surface, _resources.mPrivateStorage->mMagSpectrum);
}
Client::Format& Client::Format::windowSize(std::size_t size)
{
mWindowSize = size; return *this;
}
Client::Format& Client::Format::fftSize(std::size_t size)
{
mFftSize = size; return *this;
}
std::size_t Client::Format::getWindowSize() const
{
return mWindowSize;
}
std::size_t Client::Format::getFftSize() const
{
return mFftSize;
}
Client::Format& Client::Format::channels(std::size_t size)
{
mChannels = size;
return *this;
}
std::size_t Client::Format::getChannelSize() const
{
return mChannels;
}
Client::Format& Client::Format::windowType(ci::audio::dsp::WindowType type)
{
mWindowType = type; return *this;
}
ci::audio::dsp::WindowType Client::Format::getWindowType() const
{
return mWindowType;
}
}
} //!cieq::stft<|endoftext|> |
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "Stock.hxx"
#include "Class.hxx"
#include "GetHandler.hxx"
#include "pool.hxx"
#include "event/Callback.hxx"
#include "util/Cast.hxx"
#include <daemon/log.h>
#include <glib.h>
#include <assert.h>
inline
Stock::Waiting::Waiting(Stock &_stock, struct pool &_pool, void *_info,
StockGetHandler &_handler,
struct async_operation_ref &_async_ref)
:stock(_stock), pool(_pool), info(_info),
handler(_handler),
async_ref(_async_ref)
{
operation.Init2<Waiting>();
pool_ref(&pool);
async_ref.Set(operation);
}
inline void
Stock::Waiting::Destroy()
{
DeleteUnrefPool(pool, this);
}
void
Stock::FadeAll()
{
for (auto &i : busy)
i.fade = true;
ClearIdle();
ScheduleCheckEmpty();
// TODO: restart the "num_create" list?
}
/*
* The "empty()" handler method.
*
*/
void
Stock::CheckEmpty()
{
if (IsEmpty() && handler != nullptr)
handler->OnStockEmpty(*this);
}
void
Stock::ScheduleCheckEmpty()
{
if (IsEmpty() && handler != nullptr)
empty_event.Schedule();
}
/*
* cleanup
*
*/
void
Stock::CleanupEventCallback()
{
assert(idle.size() > max_idle);
/* destroy one third of the idle items */
for (unsigned i = (idle.size() - max_idle + 2) / 3; i > 0; --i)
idle.pop_front_and_dispose([this](StockItem *item){
DestroyItem(*item);
});
/* schedule next cleanup */
if (idle.size() > max_idle)
ScheduleCleanup();
else
CheckEmpty();
}
/*
* wait operation
*
*/
inline void
Stock::Waiting::Abort()
{
auto &list = stock.waiting;
const auto i = list.iterator_to(*this);
list.erase_and_dispose(i, [](Stock::Waiting *w){ w->Destroy(); });
}
void
Stock::RetryWaiting()
{
if (limit == 0)
/* no limit configured, no waiters possible */
return;
/* first try to serve existing idle items */
while (!idle.empty()) {
const auto i = waiting.begin();
if (i == waiting.end())
return;
auto &w = *i;
w.operation.Finished();
waiting.erase(i);
if (GetIdle(w.handler))
w.Destroy();
else
/* didn't work (probably because borrowing the item has
failed) - re-add to "waiting" list */
waiting.push_front(w);
}
/* if we're below the limit, create a bunch of new items */
for (unsigned i = limit - busy.size() - num_create;
busy.size() + num_create < limit && i > 0 && !waiting.empty();
--i) {
auto &w = waiting.front();
waiting.pop_front();
w.operation.Finished();
GetCreate(w.pool, w.info,
w.handler,
w.async_ref);
w.Destroy();
}
}
void
Stock::ScheduleRetryWaiting()
{
if (limit > 0 && !waiting.empty() &&
busy.size() - num_create < limit)
retry_event.Schedule();
}
/*
* clear after 60 seconds idle
*
*/
void
Stock::ClearIdle()
{
daemon_log(5, "Stock::ClearIdle(%p, '%s') num_idle=%zu num_busy=%zu\n",
(const void *)this, name.c_str(),
idle.size(), busy.size());
if (idle.size() > max_idle)
UnscheduleCleanup();
idle.clear_and_dispose([this](StockItem *item){
DestroyItem(*item);
});
}
void
Stock::ClearEventCallback()
{
daemon_log(6, "Stock::ClearEvent(%p, '%s') may_clear=%d\n",
(const void *)this, name.c_str(), may_clear);
if (may_clear)
ClearIdle();
may_clear = true;
ScheduleClear();
CheckEmpty();
}
/*
* constructor
*
*/
Stock::Stock(EventLoop &event_loop, const StockClass &_cls, void *_class_ctx,
const char *_name, unsigned _limit, unsigned _max_idle,
StockHandler *_handler)
:cls(_cls), class_ctx(_class_ctx),
name(_name),
limit(_limit), max_idle(_max_idle),
handler(_handler),
retry_event(event_loop, BIND_THIS_METHOD(RetryWaiting)),
empty_event(event_loop, BIND_THIS_METHOD(CheckEmpty)),
cleanup_event(MakeSimpleEventCallback(Stock, CleanupEventCallback), this),
clear_event(MakeSimpleEventCallback(Stock, ClearEventCallback), this)
{
assert(cls.create != nullptr);
assert(max_idle > 0);
ScheduleClear();
}
Stock::~Stock()
{
assert(num_create == 0);
/* must not delete the Stock when there are busy items left */
assert(busy.empty());
retry_event.Cancel();
empty_event.Cancel();
cleanup_event.Cancel();
clear_event.Cancel();
ClearIdle();
}
void
Stock::DestroyItem(StockItem &item)
{
item.Destroy(class_ctx);
}
bool
Stock::GetIdle(StockGetHandler &get_handler)
{
auto i = idle.begin();
const auto end = idle.end();
while (i != end) {
StockItem &item = *i;
assert(item.is_idle);
i = idle.erase(i);
if (idle.size() == max_idle)
UnscheduleCleanup();
if (item.Borrow(class_ctx)) {
#ifndef NDEBUG
item.is_idle = false;
#endif
busy.push_front(item);
get_handler.OnStockItemReady(item);
return true;
}
DestroyItem(item);
}
ScheduleCheckEmpty();
return false;
}
void
Stock::GetCreate(struct pool &caller_pool, void *info,
StockGetHandler &get_handler,
struct async_operation_ref &async_ref)
{
++num_create;
cls.create(class_ctx, {*this, get_handler},
info, caller_pool, async_ref);
}
void
Stock::Get(struct pool &caller_pool, void *info,
StockGetHandler &get_handler,
struct async_operation_ref &async_ref)
{
may_clear = false;
if (GetIdle(get_handler))
return;
if (limit > 0 && busy.size() + num_create >= limit) {
/* item limit reached: wait for an item to return */
auto w = NewFromPool<Stock::Waiting>(caller_pool, *this,
caller_pool, info,
get_handler, async_ref);
waiting.push_front(*w);
return;
}
GetCreate(caller_pool, info, get_handler, async_ref);
}
StockItem *
Stock::GetNow(struct pool &caller_pool, void *info, GError **error_r)
{
struct NowRequest final : public StockGetHandler {
#ifndef NDEBUG
bool created = false;
#endif
StockItem *item;
GError *error;
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &_item) override {
#ifndef NDEBUG
created = true;
#endif
item = &_item;
}
void OnStockItemError(GError *_error) override {
#ifndef NDEBUG
created = true;
#endif
item = nullptr;
error = _error;
}
};
NowRequest data;
struct async_operation_ref async_ref;
/* cannot call this on a limited stock */
assert(limit == 0);
Get(caller_pool, info, data, async_ref);
assert(data.created);
if (data.item == nullptr)
g_propagate_error(error_r, data.error);
return data.item;
}
void
Stock::ItemCreateSuccess(StockItem &item)
{
assert(num_create > 0);
--num_create;
busy.push_front(item);
item.handler.OnStockItemReady(item);
}
void
Stock::ItemCreateError(StockItem &item, GError *error)
{
ItemCreateError(item.handler, error);
item.Destroy(class_ctx);
}
void
Stock::ItemCreateAborted(StockItem &item)
{
ItemCreateAborted();
item.Destroy(class_ctx);
}
void
Stock::ItemCreateError(StockGetHandler &get_handler, GError *error)
{
assert(error != nullptr);
assert(num_create > 0);
--num_create;
get_handler.OnStockItemError(error);
ScheduleCheckEmpty();
ScheduleRetryWaiting();
}
void
Stock::ItemCreateAborted()
{
assert(num_create > 0);
--num_create;
ScheduleCheckEmpty();
ScheduleRetryWaiting();
}
void
Stock::Put(StockItem &item, bool destroy)
{
assert(!item.is_idle);
assert(&item.stock == this);
may_clear = false;
assert(!busy.empty());
busy.erase(busy.iterator_to(item));
if (destroy || item.fade || !item.Release(class_ctx)) {
DestroyItem(item);
ScheduleCheckEmpty();
} else {
#ifndef NDEBUG
item.is_idle = true;
#endif
if (idle.size() == max_idle)
ScheduleCleanup();
idle.push_front(item);
}
ScheduleRetryWaiting();
}
void
Stock::ItemIdleDisconnect(StockItem &item)
{
assert(item.is_idle);
assert(!idle.empty());
idle.erase(idle.iterator_to(item));
if (idle.size() == max_idle)
UnscheduleCleanup();
DestroyItem(item);
ScheduleCheckEmpty();
}
<commit_msg>stock/Stock: use BIND_THIS_METHOD()<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "Stock.hxx"
#include "Class.hxx"
#include "GetHandler.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <daemon/log.h>
#include <glib.h>
#include <assert.h>
inline
Stock::Waiting::Waiting(Stock &_stock, struct pool &_pool, void *_info,
StockGetHandler &_handler,
struct async_operation_ref &_async_ref)
:stock(_stock), pool(_pool), info(_info),
handler(_handler),
async_ref(_async_ref)
{
operation.Init2<Waiting>();
pool_ref(&pool);
async_ref.Set(operation);
}
inline void
Stock::Waiting::Destroy()
{
DeleteUnrefPool(pool, this);
}
void
Stock::FadeAll()
{
for (auto &i : busy)
i.fade = true;
ClearIdle();
ScheduleCheckEmpty();
// TODO: restart the "num_create" list?
}
/*
* The "empty()" handler method.
*
*/
void
Stock::CheckEmpty()
{
if (IsEmpty() && handler != nullptr)
handler->OnStockEmpty(*this);
}
void
Stock::ScheduleCheckEmpty()
{
if (IsEmpty() && handler != nullptr)
empty_event.Schedule();
}
/*
* cleanup
*
*/
void
Stock::CleanupEventCallback()
{
assert(idle.size() > max_idle);
/* destroy one third of the idle items */
for (unsigned i = (idle.size() - max_idle + 2) / 3; i > 0; --i)
idle.pop_front_and_dispose([this](StockItem *item){
DestroyItem(*item);
});
/* schedule next cleanup */
if (idle.size() > max_idle)
ScheduleCleanup();
else
CheckEmpty();
}
/*
* wait operation
*
*/
inline void
Stock::Waiting::Abort()
{
auto &list = stock.waiting;
const auto i = list.iterator_to(*this);
list.erase_and_dispose(i, [](Stock::Waiting *w){ w->Destroy(); });
}
void
Stock::RetryWaiting()
{
if (limit == 0)
/* no limit configured, no waiters possible */
return;
/* first try to serve existing idle items */
while (!idle.empty()) {
const auto i = waiting.begin();
if (i == waiting.end())
return;
auto &w = *i;
w.operation.Finished();
waiting.erase(i);
if (GetIdle(w.handler))
w.Destroy();
else
/* didn't work (probably because borrowing the item has
failed) - re-add to "waiting" list */
waiting.push_front(w);
}
/* if we're below the limit, create a bunch of new items */
for (unsigned i = limit - busy.size() - num_create;
busy.size() + num_create < limit && i > 0 && !waiting.empty();
--i) {
auto &w = waiting.front();
waiting.pop_front();
w.operation.Finished();
GetCreate(w.pool, w.info,
w.handler,
w.async_ref);
w.Destroy();
}
}
void
Stock::ScheduleRetryWaiting()
{
if (limit > 0 && !waiting.empty() &&
busy.size() - num_create < limit)
retry_event.Schedule();
}
/*
* clear after 60 seconds idle
*
*/
void
Stock::ClearIdle()
{
daemon_log(5, "Stock::ClearIdle(%p, '%s') num_idle=%zu num_busy=%zu\n",
(const void *)this, name.c_str(),
idle.size(), busy.size());
if (idle.size() > max_idle)
UnscheduleCleanup();
idle.clear_and_dispose([this](StockItem *item){
DestroyItem(*item);
});
}
void
Stock::ClearEventCallback()
{
daemon_log(6, "Stock::ClearEvent(%p, '%s') may_clear=%d\n",
(const void *)this, name.c_str(), may_clear);
if (may_clear)
ClearIdle();
may_clear = true;
ScheduleClear();
CheckEmpty();
}
/*
* constructor
*
*/
Stock::Stock(EventLoop &event_loop, const StockClass &_cls, void *_class_ctx,
const char *_name, unsigned _limit, unsigned _max_idle,
StockHandler *_handler)
:cls(_cls), class_ctx(_class_ctx),
name(_name),
limit(_limit), max_idle(_max_idle),
handler(_handler),
retry_event(event_loop, BIND_THIS_METHOD(RetryWaiting)),
empty_event(event_loop, BIND_THIS_METHOD(CheckEmpty)),
cleanup_event(event_loop, BIND_THIS_METHOD(CleanupEventCallback)),
clear_event(event_loop, BIND_THIS_METHOD(ClearEventCallback))
{
assert(cls.create != nullptr);
assert(max_idle > 0);
ScheduleClear();
}
Stock::~Stock()
{
assert(num_create == 0);
/* must not delete the Stock when there are busy items left */
assert(busy.empty());
retry_event.Cancel();
empty_event.Cancel();
cleanup_event.Cancel();
clear_event.Cancel();
ClearIdle();
}
void
Stock::DestroyItem(StockItem &item)
{
item.Destroy(class_ctx);
}
bool
Stock::GetIdle(StockGetHandler &get_handler)
{
auto i = idle.begin();
const auto end = idle.end();
while (i != end) {
StockItem &item = *i;
assert(item.is_idle);
i = idle.erase(i);
if (idle.size() == max_idle)
UnscheduleCleanup();
if (item.Borrow(class_ctx)) {
#ifndef NDEBUG
item.is_idle = false;
#endif
busy.push_front(item);
get_handler.OnStockItemReady(item);
return true;
}
DestroyItem(item);
}
ScheduleCheckEmpty();
return false;
}
void
Stock::GetCreate(struct pool &caller_pool, void *info,
StockGetHandler &get_handler,
struct async_operation_ref &async_ref)
{
++num_create;
cls.create(class_ctx, {*this, get_handler},
info, caller_pool, async_ref);
}
void
Stock::Get(struct pool &caller_pool, void *info,
StockGetHandler &get_handler,
struct async_operation_ref &async_ref)
{
may_clear = false;
if (GetIdle(get_handler))
return;
if (limit > 0 && busy.size() + num_create >= limit) {
/* item limit reached: wait for an item to return */
auto w = NewFromPool<Stock::Waiting>(caller_pool, *this,
caller_pool, info,
get_handler, async_ref);
waiting.push_front(*w);
return;
}
GetCreate(caller_pool, info, get_handler, async_ref);
}
StockItem *
Stock::GetNow(struct pool &caller_pool, void *info, GError **error_r)
{
struct NowRequest final : public StockGetHandler {
#ifndef NDEBUG
bool created = false;
#endif
StockItem *item;
GError *error;
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &_item) override {
#ifndef NDEBUG
created = true;
#endif
item = &_item;
}
void OnStockItemError(GError *_error) override {
#ifndef NDEBUG
created = true;
#endif
item = nullptr;
error = _error;
}
};
NowRequest data;
struct async_operation_ref async_ref;
/* cannot call this on a limited stock */
assert(limit == 0);
Get(caller_pool, info, data, async_ref);
assert(data.created);
if (data.item == nullptr)
g_propagate_error(error_r, data.error);
return data.item;
}
void
Stock::ItemCreateSuccess(StockItem &item)
{
assert(num_create > 0);
--num_create;
busy.push_front(item);
item.handler.OnStockItemReady(item);
}
void
Stock::ItemCreateError(StockItem &item, GError *error)
{
ItemCreateError(item.handler, error);
item.Destroy(class_ctx);
}
void
Stock::ItemCreateAborted(StockItem &item)
{
ItemCreateAborted();
item.Destroy(class_ctx);
}
void
Stock::ItemCreateError(StockGetHandler &get_handler, GError *error)
{
assert(error != nullptr);
assert(num_create > 0);
--num_create;
get_handler.OnStockItemError(error);
ScheduleCheckEmpty();
ScheduleRetryWaiting();
}
void
Stock::ItemCreateAborted()
{
assert(num_create > 0);
--num_create;
ScheduleCheckEmpty();
ScheduleRetryWaiting();
}
void
Stock::Put(StockItem &item, bool destroy)
{
assert(!item.is_idle);
assert(&item.stock == this);
may_clear = false;
assert(!busy.empty());
busy.erase(busy.iterator_to(item));
if (destroy || item.fade || !item.Release(class_ctx)) {
DestroyItem(item);
ScheduleCheckEmpty();
} else {
#ifndef NDEBUG
item.is_idle = true;
#endif
if (idle.size() == max_idle)
ScheduleCleanup();
idle.push_front(item);
}
ScheduleRetryWaiting();
}
void
Stock::ItemIdleDisconnect(StockItem &item)
{
assert(item.is_idle);
assert(!idle.empty());
idle.erase(idle.iterator_to(item));
if (idle.size() == max_idle)
UnscheduleCleanup();
DestroyItem(item);
ScheduleCheckEmpty();
}
<|endoftext|> |
<commit_before>#pragma once
#include "global.hpp"
namespace testing {
namespace mock {
class timer_t {
public:
MOCK_CONST_METHOD0(current, std::time_t());
};
class time_picker_t {
public:
time_picker_t() {
std::tm timeinfo;
std::memset(&timeinfo, 0, sizeof(timeinfo));
ON_CALL(*this, now())
.WillByDefault(Return(timeinfo));
}
MOCK_CONST_METHOD0(now, std::tm());
};
} // namespace mock
} // namespace testing
<commit_msg>Missing header for GCC 4.4.<commit_after>#pragma once
#include <cstring>
#include "global.hpp"
namespace testing {
namespace mock {
class timer_t {
public:
MOCK_CONST_METHOD0(current, std::time_t());
};
class time_picker_t {
public:
time_picker_t() {
std::tm timeinfo;
std::memset(&timeinfo, 0, sizeof(timeinfo));
ON_CALL(*this, now())
.WillByDefault(Return(timeinfo));
}
MOCK_CONST_METHOD0(now, std::tm());
};
} // namespace mock
} // namespace testing
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <mesos/http.hpp>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/http.hpp>
#include <process/pid.hpp>
#include <process/process.hpp>
#include <stout/gtest.hpp>
#include "tests/flags.hpp"
#include "tests/utils.hpp"
using std::string;
namespace mesos {
namespace internal {
namespace tests {
#if MESOS_INSTALL_TESTS
const bool searchInstallationDirectory = true;
#else
const bool searchInstallationDirectory = false;
#endif
JSON::Object Metrics()
{
process::UPID upid("metrics", process::address());
process::Future<process::http::Response> response =
process::http::get(upid, "snapshot");
AWAIT_EXPECT_RESPONSE_STATUS_EQ(process::http::OK().status, response);
AWAIT_EXPECT_RESPONSE_HEADER_EQ(APPLICATION_JSON, "Content-Type", response);
Try<JSON::Object> parse = JSON::parse<JSON::Object>(response.get().body);
CHECK_SOME(parse);
return parse.get();
}
string getModulePath(const string& name)
{
string path = path::join(
tests::flags.build_dir,
"src",
".libs");
if (!os::exists(path) && searchInstallationDirectory) {
path = PKGMODULEDIR;
}
return path::join(path, os::libraries::expandName(name));
}
string getLibMesosPath()
{
string path = path::join(
tests::flags.build_dir,
"src",
".libs",
os::libraries::expandName("mesos-" VERSION));
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(
LIBDIR,
os::libraries::expandName("mesos-" VERSION));
}
return path;
}
string getLauncherDir()
{
string path = path::join(
tests::flags.build_dir,
"src");
if (!os::exists(path) && searchInstallationDirectory) {
path = PKGLIBEXECDIR;
}
return path;
}
string getTestHelperPath(const string& name)
{
string path = path::join(
tests::flags.build_dir,
"src",
name);
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(
TESTLIBEXECDIR,
name);
}
return path;
}
string getTestHelperDir()
{
string path = path::join(
tests::flags.build_dir,
"src");
if (!os::exists(path) && searchInstallationDirectory) {
return TESTLIBEXECDIR;
}
return path;
}
string getTestScriptPath(const string& script)
{
string path = path::join(
flags.source_dir,
"src",
"tests",
script);
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(
TESTLIBEXECDIR,
script);
}
return path;
}
string getSbinDir()
{
string path = path::join(
tests::flags.build_dir,
"src");
if (!os::exists(path) && searchInstallationDirectory) {
return SBINDIR;
}
return path;
}
string getWebUIDir()
{
string path = path::join(
flags.source_dir,
"src",
"webui");
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(
PKGDATADIR,
"webui");
}
return path;
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Fixed some whitespace in test utilities.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <mesos/http.hpp>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/http.hpp>
#include <process/pid.hpp>
#include <process/process.hpp>
#include <stout/gtest.hpp>
#include "tests/flags.hpp"
#include "tests/utils.hpp"
using std::string;
namespace mesos {
namespace internal {
namespace tests {
#if MESOS_INSTALL_TESTS
const bool searchInstallationDirectory = true;
#else
const bool searchInstallationDirectory = false;
#endif
JSON::Object Metrics()
{
process::UPID upid("metrics", process::address());
process::Future<process::http::Response> response =
process::http::get(upid, "snapshot");
AWAIT_EXPECT_RESPONSE_STATUS_EQ(process::http::OK().status, response);
AWAIT_EXPECT_RESPONSE_HEADER_EQ(APPLICATION_JSON, "Content-Type", response);
Try<JSON::Object> parse = JSON::parse<JSON::Object>(response.get().body);
CHECK_SOME(parse);
return parse.get();
}
string getModulePath(const string& name)
{
string path = path::join(tests::flags.build_dir, "src", ".libs");
if (!os::exists(path) && searchInstallationDirectory) {
path = PKGMODULEDIR;
}
return path::join(path, os::libraries::expandName(name));
}
string getLibMesosPath()
{
string path = path::join(
tests::flags.build_dir,
"src",
".libs",
os::libraries::expandName("mesos-" VERSION));
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(LIBDIR, os::libraries::expandName("mesos-" VERSION));
}
return path;
}
string getLauncherDir()
{
string path = path::join(tests::flags.build_dir, "src");
if (!os::exists(path) && searchInstallationDirectory) {
path = PKGLIBEXECDIR;
}
return path;
}
string getTestHelperPath(const string& name)
{
string path = path::join(tests::flags.build_dir, "src", name);
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(TESTLIBEXECDIR, name);
}
return path;
}
string getTestHelperDir()
{
string path = path::join(tests::flags.build_dir, "src");
if (!os::exists(path) && searchInstallationDirectory) {
return TESTLIBEXECDIR;
}
return path;
}
string getTestScriptPath(const string& script)
{
string path = path::join(flags.source_dir, "src", "tests", script);
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(TESTLIBEXECDIR, script);
}
return path;
}
string getSbinDir()
{
string path = path::join(tests::flags.build_dir, "src");
if (!os::exists(path) && searchInstallationDirectory) {
return SBINDIR;
}
return path;
}
string getWebUIDir()
{
string path = path::join(flags.source_dir, "src", "webui");
if (!os::exists(path) && searchInstallationDirectory) {
path = path::join(PKGDATADIR, "webui");
}
return path;
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>#include <AltSoftSerial.h>
void clearVars(void);
/**
* \brief Software serial port object
* \author volodink
*/
AltSoftSerial mySerial;
volatile uint8_t message[512]; /**< Maximum message size */
/**
* The first argument to calculate the checksum
*/
uint8_t CK_A = 0, CK_B = 0;
/**< The second argument to calculate the checksum */
/**
* The first argument to comparison the checksum
*/
uint8_t CK_AU = 0, CK_BU = 0; /**< The second argument to comparison the checksum */
int gpsStep = 0; /**< If the data suits us, this parameter makes the step */
uint8_t UBX_id = 0; /**< Message ID */
uint8_t UBX_class = 0; /**< Message class */
uint8_t meslenL = 0; /**< variable, with which compare a message */
uint8_t meslenH = 0; /**< variable, which shifts to the left */
int16_t meslen = 0; /**< variable, which assigned a message to its further comparisons */
int count = 0; /**< Message size */
boolean gotUBX = false; /**< The parameter which checks getting data */
boolean POSLLH = 0; /**< Geodetic Position Solution; This message outputs
* the Geodetic position in the currently selected Ellipsoid.
*/
boolean SVINFO = 0;/**< Space Vehicle Information */
boolean SOL = 0;/**< Navigation Solution Information; This message combines Position,
* velocity and time solution in ECEF, including accuracy figures
*/
boolean VELNED = 0;/**< Velocity Solution in NED */
long int longitude; /**< Longitude */
float longitudef; /**< Output longitude */
long int latitude; /**< Latitude */
float latitudef; /**< Output latitude */
long int height; /**< Height */
float heightf; /**< Output height */
long int speed3; /**< Speed */
float speed3f; /**< Output speed */
long int hAcc; /**< Horizontal accuracy */
float hAccf; /**< Output horizontal accuracy */
long int vAcc; /**< Vertical accuracy */
float vAccf; /**< Output vertical accuracy */
long int pAcc; /**< 3D accuracy */
float pAccf; /**< Output 3D accuracy */
char bufer[20];
/**
* GPSfix Type, range 0..5;
* Is a measure of the communication
* required for a GPS receiver to acquire
* satellite signals and navigation data
*/
unsigned char FixType;
unsigned char NumSVs; /**< Number of SVs used in Nav Solution */
int ledPin = 13; /**< working pin */
int fixStep = 0; /**< If parameter FixType is 0x02 or 0x03, this parameter makes the step */
int nofixStep = 0; /**< If parameter FixType is not 0x02 or 0x03, this parameter makes the step */
/**
* \brief uBlox checksum algorithm
* \param ubx_data Contains the data over
* which the checksum is to be calculated.
*/
void ubx_checksum(byte ubx_data) { //рассчет контрольной суммы
CK_A += ubx_data;
CK_B += CK_A;
}
/**
* \brief Getting and comparing data
*/
void getUBX(void) { //Получаем пакет и делаем с ним штуки
if (Serial.available() > 0) {
uint8_t c = Serial.read();
switch (gpsStep) {
case 0:
if (c == 0xB5) {
gpsStep++;
// mySerial.print("Start 0xB5 ");
}
break;
case 1:
if (c == 0x62) {
gpsStep++;
// mySerial.print("Start 0x62 ");
} else {
gpsStep = 0;
// mySerial.println(" Error not62 ");
}
break;
case 2:
UBX_class = c;
ubx_checksum(c);
gpsStep++;
// mySerial.println(""); mySerial.print(" UBX_CLASS = "); mySerial.println(UBX_class);
break;
case 3:
UBX_id = c;
ubx_checksum(c);
gpsStep++;
// mySerial.println(""); mySerial.print(" UBX_id = "); mySerial.println(UBX_id);
break;
case 4:
meslenL = c;
ubx_checksum(c);
gpsStep++;
// mySerial.print(" ml ");
break;
case 5:
meslenH = c;
ubx_checksum(c);
gpsStep++;
meslen = 0xFF & meslenL;
meslen |= meslenH << 8;
count = 0;
// mySerial.print(" mh ");
// mySerial.print("mlen=");
// mySerial.print(meslen);
break;
case 6:
message[count] = c;
ubx_checksum(c);
count++;
if (count == meslen) {
gpsStep++;
count = 0;
}
break;
case 7:
CK_AU = c;
gpsStep++;
break;
case 8:
CK_BU = c;
if (CK_A == CK_AU && CK_B == CK_BU) { //сравнение контрольной суммы
gotUBX = true;
gpsStep++;
}
break;
}
}
}
/**
* \brief UBX-decoder
*/
void decodeUBX(void) {
if (UBX_class == 0x01) {
switch (UBX_id) {
case 0x02: //NAV-POSLLH
longitude = 0xFF & message[7]; //долгота
longitude = longitude << 8;
longitude |= message[6];
longitude = longitude << 8;
longitude |= message[5];
longitude = longitude << 8;
longitude |= message[4];
longitudef = longitude / 10000000.0;
latitude = 0xFF & message[11]; //широта
latitude = latitude << 8;
latitude |= message[10];
latitude = latitude << 8;
latitude |= message[9];
latitude = latitude << 8;
latitude |= message[8];
latitudef = latitude / 10000000.0;
height = 0xFF & message[19]; //высота
height = height << 8;
height |= message[18];
height = height << 8;
height |= message[17];
height = height << 8;
height |= message[16];
heightf = height / 1000.0;
hAcc = 0xFF & message[23]; //гор. точность
hAcc = hAcc << 8;
hAcc |= message[22];
hAcc = hAcc << 8;
hAcc |= message[21];
hAcc = hAcc << 8;
hAcc |= message[20];
hAccf = hAcc / 1000.0;
vAcc = 0xFF & message[27]; //верт. точность
vAcc = vAcc << 8;
vAcc |= message[26];
vAcc = vAcc << 8;
vAcc |= message[25];
vAcc = vAcc << 8;
vAcc |= message[24];
vAccf = vAcc / 1000.0;
POSLLH = true;
// mySerial.println("POSLLH got.");
break;
case 0x12: //NAV-VELNED
speed3 = 0xFF & message[19]; //скорость
speed3 = speed3 << 8;
speed3 |= message[18];
speed3 = speed3 << 8;
speed3 |= message[17];
speed3 = speed3 << 8;
speed3 |= message[16];
speed3f = speed3 / 100.0;
VELNED = true;
// mySerial.println("VELNED got.");
break;
case 0x06: // NAV-SOL
NumSVs = message[47]; //кол-во спутников в решении
FixType = message[10]; //тип фикса
pAcc = 0xFF & message[27]; //3D точность
pAcc = pAcc << 8;
pAcc |= message[26];
pAcc = pAcc << 8;
pAcc |= message[25];
pAcc = pAcc << 8;
pAcc |= message[24];
pAccf = pAcc / 100.0;
if (FixType == 0x02 || FixType == 0x03) {
fixStep++;
nofixStep = 0;
} else {
nofixStep++;
fixStep = 0;
}
if (fixStep == 12) digitalWrite(ledPin, HIGH);
if (nofixStep == 12) digitalWrite(ledPin, LOW);
// mySerial.println(NumSVs);
// mySerial.println(FixType);
SOL = true;
// mySerial.println("SOL got.");
break;
// default:
// mySerial.print("Unknown ubx id = ");
// mySerial.println(UBX_id);
}
}
}
/**
* \brief Function output data
*/
void sendGPS(void) {
mySerial.print("A");
mySerial.print(longitudef, 6);
mySerial.print(" B");
mySerial.print(latitudef, 6);
mySerial.print(" C");
mySerial.print(heightf, 3);
mySerial.print(" D");
mySerial.print(speed3f, 3);
mySerial.print(" E");
mySerial.print(vAccf, 3);
mySerial.print(" F");
mySerial.print(hAccf, 3);
mySerial.print(" G");
mySerial.print(pAccf);
mySerial.print(" H");
mySerial.print(NumSVs);
mySerial.print(" I");
mySerial.println(FixType);
longitude = 0;
latitude = 0;
height = 0;
speed3 = 0;
NumSVs = 0;
FixType = 0;
}
/**
* \brief Data cleansing
*/
void clearVars(void) {
gpsStep = 0;
UBX_id = 0;
UBX_class = 0;
meslen = 0;
count = 0;
CK_AU = 0;
CK_BU = 0;
CK_A = 0;
CK_B = 0;
for(int i = 0; i < 60; i++) {
message[i] = 0;
}
}
/**
* \brief Starts only 1 time after reset
* \author volodink
*/
void setup() {
Serial.begin(57600); /**< setup hardware serial for GPS side */
mySerial.begin(9600);/**< setup hardware serial for GPS side */
pinMode(13, OUTPUT);
mySerial.println("UBX ready.");
clearVars();
}
/**
* \brief Running in the infinite loop
* \author volodink
*/
void loop() {
//mySerial.println("enter loop");
getUBX();
if (gotUBX == true) {
// mySerial.println("got ubx packet");
decodeUBX();
// mySerial.println("ubx packet decoded");
if (POSLLH == 1 && VELNED == 1 && SOL == 1) {
// mySerial.println("if posllh == 1");
sendGPS();
POSLLH = 0;
VELNED = 0;
SOL = 0;
}
clearVars();
gotUBX = false;
}
}
<commit_msg>Test commit<commit_after>#include <AltSoftSerial.h>
void clearVars(void);
/**
* \brief Software serial port object
* \author volodink
*/
AltSoftSerial mySerial;
volatile uint8_t message[512]; /**< Maximum message size */
/**
* The first argument to calculate the checksum
*/
uint8_t CK_A = 0, CK_B = 0;
/**< The second argument to calculate the checksum */
/**
* The first argument to comparison the checksum
*/
uint8_t CK_AU = 0, CK_BU = 0; /**< The second argument to comparison the checksum */
int gpsStep = 0; /**< If the data suits us, this parameter makes the step */
uint8_t UBX_id = 0; /**< Message ID */
uint8_t UBX_class = 0; /**< Message class */
uint8_t meslenL = 0; /**< variable, with which compare a message */
uint8_t meslenH = 0; /**< variable, which shifts to the left */
int16_t meslen = 0; /**< variable, which assigned a message to its further comparisons */
int count = 0; /**< Message size */
boolean gotUBX = false; /**< The parameter which checks getting data */
boolean POSLLH = 0; /**< Geodetic Position Solution; This message outputs
* the Geodetic position in the currently selected Ellipsoid.
*/
boolean SVINFO = 0;/**< Space Vehicle Information */
boolean SOL = 0;/**< Navigation Solution Information; This message combines Position,
* velocity and time solution in ECEF, including accuracy figures
*/
boolean VELNED = 0;/**< Velocity Solution in NED */
long int longitude; /**< Longitude */
float longitudef; /**< Output longitude */
long int latitude; /**< Latitude */
float latitudef; /**< Output latitude */
long int height; /**< Height */
float heightf; /**< Output height */
long int speed3; /**< Speed */
float speed3f; /**< Output speed */
long int hAcc; /**< Horizontal accuracy */
float hAccf; /**< Output horizontal accuracy */
long int vAcc; /**< Vertical accuracy */
float vAccf; /**< Output vertical accuracy */
long int pAcc; /**< 3D accuracy */
float pAccf; /**< Output 3D accuracy */
char bufer[20];
/**
* GPSfix Type, range 0..5;
* Is a measure of the communication
* required for a GPS receiver to acquire
* satellite signals and navigation data
*/
unsigned char FixType;
unsigned char NumSVs; /**< Number of SVs used in Nav Solution */
int ledPin = 13; /**< working pin */
int fixStep = 0; /**< If parameter FixType is 0x02 or 0x03, this parameter makes the step */
int nofixStep = 0; /**< If parameter FixType is not 0x02 or 0x03, this parameter makes the step */
/**
* \brief uBlox checksum algorithm
* \param ubx_data Contains the data over
* which the checksum is to be calculated.
*/
void ubx_checksum(byte ubx_data) { //рассчет контрольной суммы
CK_A += ubx_data;
CK_B += CK_A;
}
/**
* \brief Getting and comparing data
*/
void getUBX(void) { //Получаем пакет и делаем с ним штуки
if (Serial.available() > 0) {
uint8_t c = Serial.read();
switch (gpsStep) {
case 0:
if (c == 0xB5) {
gpsStep++;
// mySerial.print("Start 0xB5 ");
}
break;
case 1:
if (c == 0x62) {
gpsStep++;
// mySerial.print("Start 0x62 ");
} else {
gpsStep = 0;
// mySerial.println(" Error not62 ");
}
break;
case 2:
UBX_class = c;
ubx_checksum(c);
gpsStep++;
// mySerial.println(""); mySerial.print(" UBX_CLASS = "); mySerial.println(UBX_class);
break;
case 3:
UBX_id = c;
ubx_checksum(c);
gpsStep++;
// mySerial.println(""); mySerial.print(" UBX_id = "); mySerial.println(UBX_id);
break;
case 4:
meslenL = c;
ubx_checksum(c);
gpsStep++;
// mySerial.print(" ml ");
break;
case 5:
meslenH = c;
ubx_checksum(c);
gpsStep++;
meslen = 0xFF & meslenL;
meslen |= meslenH << 8;
count = 0;
// mySerial.print(" mh ");
// mySerial.print("mlen=");
// mySerial.print(meslen);
break;
case 6:
message[count] = c;
ubx_checksum(c);
count++;
if (count == meslen) {
gpsStep++;
count = 0;
}
break;
case 7:
CK_AU = c;
gpsStep++;
break;
case 8:
CK_BU = c;
if (CK_A == CK_AU && CK_B == CK_BU) { //сравнение контрольной суммы
gotUBX = true;
gpsStep++;
}
break;
}
}
}
/**
* \brief UBX-decoder
*/
void decodeUBX(void) {
if (UBX_class == 0x01) {
switch (UBX_id) {
case 0x02: //NAV-POSLLH
longitude = 0xFF & message[7]; //долгота
longitude = longitude << 8;
longitude |= message[6];
longitude = longitude << 8;
longitude |= message[5];
longitude = longitude << 8;
longitude |= message[4];
longitudef = longitude / 10000000.0;
latitude = 0xFF & message[11]; //широта
latitude = latitude << 8;
latitude |= message[10];
latitude = latitude << 8;
latitude |= message[9];
latitude = latitude << 8;
latitude |= message[8];
latitudef = latitude / 10000000.0;
height = 0xFF & message[19]; //высота
height = height << 8;
height |= message[18];
height = height << 8;
height |= message[17];
height = height << 8;
height |= message[16];
heightf = height / 1000.0;
hAcc = 0xFF & message[23]; //гор. точность
hAcc = hAcc << 8;
hAcc |= message[22];
hAcc = hAcc << 8;
hAcc |= message[21];
hAcc = hAcc << 8;
hAcc |= message[20];
hAccf = hAcc / 1000.0;
vAcc = 0xFF & message[27]; //верт. точность
vAcc = vAcc << 8;
vAcc |= message[26];
vAcc = vAcc << 8;
vAcc |= message[25];
vAcc = vAcc << 8;
vAcc |= message[24];
vAccf = vAcc / 1000.0;
POSLLH = true;
// mySerial.println("POSLLH got.");
break;
case 0x12: //NAV-VELNED
speed3 = 0xFF & message[19]; //скорость
speed3 = speed3 << 8;
speed3 |= message[18];
speed3 = speed3 << 8;
speed3 |= message[17];
speed3 = speed3 << 8;
speed3 |= message[16];
speed3f = speed3 / 100.0;
VELNED = true;
// mySerial.println("VELNED got.");
break;
case 0x06: // NAV-SOL
NumSVs = message[47]; //кол-во спутников в решении
FixType = message[10]; //тип фикса
pAcc = 0xFF & message[27]; //3D точность
pAcc = pAcc << 8;
pAcc |= message[26];
pAcc = pAcc << 8;
pAcc |= message[25];
pAcc = pAcc << 8;
pAcc |= message[24];
pAccf = pAcc / 100.0;
if (FixType == 0x02 || FixType == 0x03) {
fixStep++;
nofixStep = 0;
} else {
nofixStep++;
fixStep = 0;
}
if (fixStep == 12) digitalWrite(ledPin, HIGH);
if (nofixStep == 12) digitalWrite(ledPin, LOW);
// mySerial.println(NumSVs);
// mySerial.println(FixType);
SOL = true;
// mySerial.println("SOL got.");
break;
// default:
// mySerial.print("Unknown ubx id = ");
// mySerial.println(UBX_id);
}
}
}
/**
* \brief Function output data
*/
void sendGPS(void) {
mySerial.print("A");
mySerial.print(longitudef, 6);
mySerial.print(" B");
mySerial.print(latitudef, 6);
mySerial.print(" C");
mySerial.print(heightf, 3);
mySerial.print(" D");
mySerial.print(speed3f, 3);
mySerial.print(" E");
mySerial.print(vAccf, 3);
mySerial.print(" F");
mySerial.print(hAccf, 3);
mySerial.print(" G");
mySerial.print(pAccf);
mySerial.print(" H");
mySerial.print(NumSVs);
mySerial.print(" I");
mySerial.println(FixType);
longitude = 0;
latitude = 0;
height = 0;
speed3 = 0;
NumSVs = 0;
FixType = 0;
}
/**
* \brief Data cleansing
*/
void clearVars(void) {
gpsStep = 0;
UBX_id = 0;
UBX_class = 0;
meslen = 0;
count = 0;
CK_AU = 0;
CK_BU = 0;
CK_A = 0;
CK_B = 0;
for(int i = 0; i < 60; i++) {
message[i] = 0;
}
}
/**
* \brief Starts only 1 time after reset
* \author volodink
*/
void setup() {
Serial.begin(57600); /**< setup hardware serial for GPS side */
mySerial.begin(9600);/**< setup hardware serial for GPS side */
pinMode(13, OUTPUT);
mySerial.println("UBX ready.");
clearVars();
}
/**
* \brief Running in the infinite loop
* \author volodink
*/
void loop() {
//mySerial.println("enter loop");
getUBX();
if (gotUBX == true) {
// mySerial.println("got ubx packet");
decodeUBX();
// mySerial.println("ubx packet decoded");
if (POSLLH == 1 && VELNED == 1 && SOL == 1) {
// mySerial.println("if posllh == 1");
sendGPS();
POSLLH = 0;
VELNED = 0;
SOL = 0;
}
clearVars();
gotUBX = false;
}
}
<|endoftext|> |
<commit_before>#include "physics/kepler_orbit.hpp"
#include "astronomy/frames.hpp"
#include "geometry/epoch.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mathematica/mathematica.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/almost_equals.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::JulianDate;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using testing_utilities::AlmostEquals;
using ::testing::AllOf;
using ::testing::Gt;
using ::testing::Lt;
namespace physics {
class KeplerOrbitTest : public ::testing::Test {};
// Target body name : Moon(301) { source: DE431mx }
// Center body name : Earth(399) { source: DE431mx }
// Output units : KM-S, deg, Julian day number (Tp)
// Reference frame : ICRF / J2000.0
// Coordinate systm : Earth Mean Equator and Equinox of Reference Epoch
// System GM : 4.0350323550225975E+05 km^3/s^2
// 2457397.500000000 = A.D. 2016-Jan-10 00:00:00.0000 (TDB)
// EC= 4.772161502830355E-02 QR= 3.685366825859605E+05 IN= 1.842335956339145E+01
// OM= 1.752118723367974E+00 W = 3.551364385683149E+02 Tp= 2457402.376861531753
// N = 1.511718576836574E-04 MA= 2.963020996150547E+02 TA= 2.912732951134421E+02
// A = 3.870051955415476E+05 AD= 4.054737084971346E+05 PR= 2.381395621619845E+06
// X = 1.177367562036580E+05 Y =-3.419908628150604E+05 Z =-1.150659799281941E+05
// VX= 9.745048087261129E-01 VY= 3.500672337210811E-01 VZ= 1.066306010215636E-01
TEST_F(KeplerOrbitTest, EarthMoon) {
SolarSystem<ICRFJ2000Equator> solar_system;
solar_system.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"initial_state_jd_2433282_500000000.proto.txt");
auto const earth = SolarSystem<ICRFJ2000Equator>::MakeMassiveBody(
solar_system.gravity_model_message("Earth"));
auto const moon = SolarSystem<ICRFJ2000Equator>::MakeMassiveBody(
solar_system.gravity_model_message("Moon"));
// The numbers in the gravity models and those from the query above both come
// from DE431, so the sums are the same up to round-off.
EXPECT_THAT(
earth->gravitational_parameter() + moon->gravitational_parameter(),
AlmostEquals(
4.0350323550225975E+05 * (Pow<3>(Kilo(Metre)) / Pow<2>(Second)), 1));
Instant const date = JulianDate(2457397.500000000);
KeplerianElements<ICRFJ2000Equator> elements;
elements.eccentricity = 4.772161502830355E-02;
elements.semimajor_axis = 3.870051955415476E+05 * Kilo(Metre);
elements.inclination = 1.842335956339145E+01 * Degree;
elements.longitude_of_ascending_node = 1.752118723367974E+00 * Degree;
elements.argument_of_periapsis = 3.551364385683149E+02 * Degree;
elements.mean_anomaly = 2.963020996150547E+02 * Degree;
KeplerOrbit<ICRFJ2000Equator> const moon_orbit(*earth, *moon, date, elements);
Displacement<ICRFJ2000Equator> const expected_displacement(
{ 1.177367562036580E+05 * Kilo(Metre),
-3.419908628150604E+05 * Kilo(Metre),
-1.150659799281941E+05 * Kilo(Metre)});
Velocity<ICRFJ2000Equator> const expected_velocity(
{9.745048087261129E-01 * (Kilo(Metre) / Second),
3.500672337210811E-01 * (Kilo(Metre) / Second),
1.066306010215636E-01 * (Kilo(Metre) / Second)});
EXPECT_THAT(moon_orbit.PrimocentricStateVectors(date).displacement(),
AlmostEquals(expected_displacement, 13));
EXPECT_THAT(moon_orbit.PrimocentricStateVectors(date).velocity(),
AlmostEquals(expected_velocity, 12));
}
TEST_F(KeplerOrbitTest, JoolSystem) {
using KSP =
Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>;
MasslessBody test_particle;
// Gravitational parameters from the KSP wiki.
std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies;
auto const add_body = [&bodies](
GravitationalParameter const& μ) -> not_null<MassiveBody const*> {
bodies.emplace_back(make_not_null_unique<MassiveBody>(μ));
return bodies.back().get();
};
auto const sun = add_body(1.1723328E+18 * Pow<3>(Metre) / Pow<2>(Second));
auto const jool = add_body(2.8252800E+14 * Pow<3>(Metre) / Pow<2>(Second));
auto const laythe = add_body(1.9620000E+12 * Pow<3>(Metre) / Pow<2>(Second));
auto const vall = add_body(2.0748150E+11 * Pow<3>(Metre) / Pow<2>(Second));
auto const tylo = add_body(2.8252800E+12 * Pow<3>(Metre) / Pow<2>(Second));
auto const bop = add_body(2.4868349E+09 * Pow<3>(Metre) / Pow<2>(Second));
auto const pol = add_body(7.2170208E+08 * Pow<3>(Metre) / Pow<2>(Second));
// Elements from the KSP wiki.
KeplerianElements<KSP> jool_elements;
jool_elements.eccentricity = 0.05;
jool_elements.semimajor_axis = 68'773'560'320 * Metre;
jool_elements.inclination = 1.304 * Degree;
jool_elements.longitude_of_ascending_node = 52 * Degree;
jool_elements.argument_of_periapsis = 0 * Degree;
jool_elements.mean_anomaly = 0.1 * Radian;
KeplerianElements<KSP> laythe_elements;
laythe_elements.eccentricity = 0;
laythe_elements.semimajor_axis = 27'184'000 * Metre;
laythe_elements.inclination = 0 * Degree;
laythe_elements.longitude_of_ascending_node = 0 * Degree;
laythe_elements.argument_of_periapsis = 0 * Degree;
laythe_elements.mean_anomaly = 3.14 * Radian;
KeplerianElements<KSP> vall_elements;
vall_elements.eccentricity = 0;
vall_elements.semimajor_axis = 43'152'000 * Metre;
vall_elements.inclination = 0 * Degree;
vall_elements.longitude_of_ascending_node = 0 * Degree;
vall_elements.argument_of_periapsis = 0 * Degree;
vall_elements.mean_anomaly = 0.9 * Radian;
KeplerianElements<KSP> tylo_elements;
tylo_elements.eccentricity = 0;
tylo_elements.semimajor_axis = 68'500'000 * Metre;
tylo_elements.inclination = 0.025 * Degree;
tylo_elements.longitude_of_ascending_node = 0 * Degree;
tylo_elements.argument_of_periapsis = 0 * Degree;
tylo_elements.mean_anomaly = 3.14 * Radian;
KeplerianElements<KSP> bop_elements;
bop_elements.eccentricity = 0.24;
bop_elements.semimajor_axis = 128'500'000 * Metre;
bop_elements.inclination = 15 * Degree;
bop_elements.longitude_of_ascending_node = 10 * Degree;
bop_elements.argument_of_periapsis = 25 * Degree;
bop_elements.mean_anomaly = 0.9 * Radian;
KeplerianElements<KSP> pol_elements;
pol_elements.eccentricity = 0.17;
pol_elements.semimajor_axis = 179'890'000 * Metre;
pol_elements.inclination = 4.25 * Degree;
pol_elements.longitude_of_ascending_node = 2 * Degree;
pol_elements.argument_of_periapsis = 15 * Degree;
pol_elements.mean_anomaly = 0.9 * Radian;
Instant const game_epoch;
auto const stock_jool_orbit =
KeplerOrbit<KSP>(*sun, test_particle, game_epoch, jool_elements);
auto const stock_laythe_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, laythe_elements);
auto const stock_vall_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, vall_elements);
auto const stock_tylo_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, tylo_elements);
auto const stock_bop_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, bop_elements);
auto const stock_pol_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, pol_elements);
DegreesOfFreedom<KSP> const origin = {KSP::origin, Velocity<KSP>()};
auto const stock_jool_initial_state =
origin + stock_jool_orbit.PrimocentricStateVectors(game_epoch);
Ephemeris<KSP> stock_ephemeris(
std::move(bodies),
{origin,
stock_jool_initial_state,
stock_jool_initial_state +
stock_laythe_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_vall_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_tylo_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_bop_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_pol_orbit.PrimocentricStateVectors(game_epoch)},
game_epoch,
McLachlanAtela1992Order5Optimal<Position<KSP>>(),
45 * Minute,
5 * Milli(Metre));
stock_ephemeris.Prolong(game_epoch + 90 * Day);
std::vector<Instant> times;
std::vector<std::vector<Displacement<KSP>>> displacements;
for (Instant t = game_epoch; t < game_epoch + 90 * Day; t += 45 * Minute) {
auto const jool_position =
stock_ephemeris.trajectory(jool)->EvaluatePosition(t, nullptr);
auto const displacement_from_jool = [&jool_position, &stock_ephemeris, t](
not_null<MassiveBody const*> body) {
return stock_ephemeris.trajectory(body)->EvaluatePosition(t, nullptr) -
jool_position;
};
times.emplace_back(t);
displacements.push_back(
{displacement_from_jool(laythe),
displacement_from_jool(vall),
displacement_from_jool(tylo),
displacement_from_jool(bop),
displacement_from_jool(pol)});
}
std::ofstream file;
file.open("stock_jool.wl");
file << mathematica::Assign("q", displacements);
file << mathematica::Assign("t", times);
file.close();
// fails.
stock_ephemeris.Prolong(game_epoch + 100 * Day);
}
} // namespace physics
} // namespace principia
<commit_msg>barycentric frame<commit_after>#include "physics/kepler_orbit.hpp"
#include "astronomy/frames.hpp"
#include "geometry/epoch.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mathematica/mathematica.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/almost_equals.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::JulianDate;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using testing_utilities::AlmostEquals;
using ::testing::AllOf;
using ::testing::Gt;
using ::testing::Lt;
namespace physics {
class KeplerOrbitTest : public ::testing::Test {};
// Target body name : Moon(301) { source: DE431mx }
// Center body name : Earth(399) { source: DE431mx }
// Output units : KM-S, deg, Julian day number (Tp)
// Reference frame : ICRF / J2000.0
// Coordinate systm : Earth Mean Equator and Equinox of Reference Epoch
// System GM : 4.0350323550225975E+05 km^3/s^2
// 2457397.500000000 = A.D. 2016-Jan-10 00:00:00.0000 (TDB)
// EC= 4.772161502830355E-02 QR= 3.685366825859605E+05 IN= 1.842335956339145E+01
// OM= 1.752118723367974E+00 W = 3.551364385683149E+02 Tp= 2457402.376861531753
// N = 1.511718576836574E-04 MA= 2.963020996150547E+02 TA= 2.912732951134421E+02
// A = 3.870051955415476E+05 AD= 4.054737084971346E+05 PR= 2.381395621619845E+06
// X = 1.177367562036580E+05 Y =-3.419908628150604E+05 Z =-1.150659799281941E+05
// VX= 9.745048087261129E-01 VY= 3.500672337210811E-01 VZ= 1.066306010215636E-01
TEST_F(KeplerOrbitTest, EarthMoon) {
SolarSystem<ICRFJ2000Equator> solar_system;
solar_system.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"initial_state_jd_2433282_500000000.proto.txt");
auto const earth = SolarSystem<ICRFJ2000Equator>::MakeMassiveBody(
solar_system.gravity_model_message("Earth"));
auto const moon = SolarSystem<ICRFJ2000Equator>::MakeMassiveBody(
solar_system.gravity_model_message("Moon"));
// The numbers in the gravity models and those from the query above both come
// from DE431, so the sums are the same up to round-off.
EXPECT_THAT(
earth->gravitational_parameter() + moon->gravitational_parameter(),
AlmostEquals(
4.0350323550225975E+05 * (Pow<3>(Kilo(Metre)) / Pow<2>(Second)), 1));
Instant const date = JulianDate(2457397.500000000);
KeplerianElements<ICRFJ2000Equator> elements;
elements.eccentricity = 4.772161502830355E-02;
elements.semimajor_axis = 3.870051955415476E+05 * Kilo(Metre);
elements.inclination = 1.842335956339145E+01 * Degree;
elements.longitude_of_ascending_node = 1.752118723367974E+00 * Degree;
elements.argument_of_periapsis = 3.551364385683149E+02 * Degree;
elements.mean_anomaly = 2.963020996150547E+02 * Degree;
KeplerOrbit<ICRFJ2000Equator> const moon_orbit(*earth, *moon, date, elements);
Displacement<ICRFJ2000Equator> const expected_displacement(
{ 1.177367562036580E+05 * Kilo(Metre),
-3.419908628150604E+05 * Kilo(Metre),
-1.150659799281941E+05 * Kilo(Metre)});
Velocity<ICRFJ2000Equator> const expected_velocity(
{9.745048087261129E-01 * (Kilo(Metre) / Second),
3.500672337210811E-01 * (Kilo(Metre) / Second),
1.066306010215636E-01 * (Kilo(Metre) / Second)});
EXPECT_THAT(moon_orbit.PrimocentricStateVectors(date).displacement(),
AlmostEquals(expected_displacement, 13));
EXPECT_THAT(moon_orbit.PrimocentricStateVectors(date).velocity(),
AlmostEquals(expected_velocity, 12));
}
TEST_F(KeplerOrbitTest, JoolSystem) {
using KSP =
Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>;
MasslessBody test_particle;
// Gravitational parameters from the KSP wiki.
std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies;
auto const add_body = [&bodies](
GravitationalParameter const& μ) -> not_null<MassiveBody const*> {
bodies.emplace_back(make_not_null_unique<MassiveBody>(μ));
return bodies.back().get();
};
auto const sun = add_body(1.1723328E+18 * Pow<3>(Metre) / Pow<2>(Second));
auto const jool = add_body(2.8252800E+14 * Pow<3>(Metre) / Pow<2>(Second));
auto const laythe = add_body(1.9620000E+12 * Pow<3>(Metre) / Pow<2>(Second));
auto const vall = add_body(2.0748150E+11 * Pow<3>(Metre) / Pow<2>(Second));
auto const tylo = add_body(2.8252800E+12 * Pow<3>(Metre) / Pow<2>(Second));
auto const bop = add_body(2.4868349E+09 * Pow<3>(Metre) / Pow<2>(Second));
auto const pol = add_body(7.2170208E+08 * Pow<3>(Metre) / Pow<2>(Second));
// Elements from the KSP wiki.
KeplerianElements<KSP> jool_elements;
jool_elements.eccentricity = 0.05;
jool_elements.semimajor_axis = 68'773'560'320 * Metre;
jool_elements.inclination = 1.304 * Degree;
jool_elements.longitude_of_ascending_node = 52 * Degree;
jool_elements.argument_of_periapsis = 0 * Degree;
jool_elements.mean_anomaly = 0.1 * Radian;
KeplerianElements<KSP> laythe_elements;
laythe_elements.eccentricity = 0;
laythe_elements.semimajor_axis = 27'184'000 * Metre;
laythe_elements.inclination = 0 * Degree;
laythe_elements.longitude_of_ascending_node = 0 * Degree;
laythe_elements.argument_of_periapsis = 0 * Degree;
laythe_elements.mean_anomaly = 3.14 * Radian;
KeplerianElements<KSP> vall_elements;
vall_elements.eccentricity = 0;
vall_elements.semimajor_axis = 43'152'000 * Metre;
vall_elements.inclination = 0 * Degree;
vall_elements.longitude_of_ascending_node = 0 * Degree;
vall_elements.argument_of_periapsis = 0 * Degree;
vall_elements.mean_anomaly = 0.9 * Radian;
KeplerianElements<KSP> tylo_elements;
tylo_elements.eccentricity = 0;
tylo_elements.semimajor_axis = 68'500'000 * Metre;
tylo_elements.inclination = 0.025 * Degree;
tylo_elements.longitude_of_ascending_node = 0 * Degree;
tylo_elements.argument_of_periapsis = 0 * Degree;
tylo_elements.mean_anomaly = 3.14 * Radian;
KeplerianElements<KSP> bop_elements;
bop_elements.eccentricity = 0.24;
bop_elements.semimajor_axis = 128'500'000 * Metre;
bop_elements.inclination = 15 * Degree;
bop_elements.longitude_of_ascending_node = 10 * Degree;
bop_elements.argument_of_periapsis = 25 * Degree;
bop_elements.mean_anomaly = 0.9 * Radian;
KeplerianElements<KSP> pol_elements;
pol_elements.eccentricity = 0.17;
pol_elements.semimajor_axis = 179'890'000 * Metre;
pol_elements.inclination = 4.25 * Degree;
pol_elements.longitude_of_ascending_node = 2 * Degree;
pol_elements.argument_of_periapsis = 15 * Degree;
pol_elements.mean_anomaly = 0.9 * Radian;
Instant const game_epoch;
auto const stock_jool_orbit =
KeplerOrbit<KSP>(*sun, test_particle, game_epoch, jool_elements);
auto const stock_laythe_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, laythe_elements);
auto const stock_vall_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, vall_elements);
auto const stock_tylo_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, tylo_elements);
auto const stock_bop_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, bop_elements);
auto const stock_pol_orbit =
KeplerOrbit<KSP>(*jool, test_particle, game_epoch, pol_elements);
DegreesOfFreedom<KSP> const origin = {KSP::origin, Velocity<KSP>()};
auto const stock_jool_initial_state =
origin + stock_jool_orbit.PrimocentricStateVectors(game_epoch);
Ephemeris<KSP> stock_ephemeris(
std::move(bodies),
{origin,
stock_jool_initial_state,
stock_jool_initial_state +
stock_laythe_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_vall_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_tylo_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_bop_orbit.PrimocentricStateVectors(game_epoch),
stock_jool_initial_state +
stock_pol_orbit.PrimocentricStateVectors(game_epoch)},
game_epoch,
McLachlanAtela1992Order5Optimal<Position<KSP>>(),
45 * Minute,
5 * Milli(Metre));
stock_ephemeris.Prolong(game_epoch + 90 * Day);
std::vector<Instant> times;
std::vector<std::vector<Displacement<KSP>>> displacements;
for (Instant t = game_epoch; t < game_epoch + 90 * Day; t += 45 * Minute) {
auto const position = [&stock_ephemeris, t](
not_null<MassiveBody const*> body) {
return stock_ephemeris.trajectory(body)->EvaluatePosition(t, nullptr);
};
auto const barycentre =
Barycentre<Position<KSP>, Mass>(
{position(jool), position(laythe), position(vall), position(tylo),
position(bop), position(pol)},
{jool->mass(), laythe->mass(), vall->mass(), tylo->mass(),
bop->mass(), pol->mass()});
times.emplace_back(t);
displacements.push_back(
{position(jool) - barycentre, position(laythe) - barycentre,
position(vall) - barycentre, position(tylo) - barycentre,
position(bop) - barycentre, position(pol) - barycentre});
}
std::ofstream file;
file.open("stock_jool.wl");
file << mathematica::Assign("q", displacements);
file << mathematica::Assign("t", times);
file.close();
// fails.
stock_ephemeris.Prolong(game_epoch + 100 * Day);
}
} // namespace physics
} // namespace principia
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.5 2001/10/10 19:14:08 peiyongz
* Patch from Petr Gotthard : encode() provided and some other changes
*
* Revision 1.4 2001/06/07 20:55:20 tng
* Fix no newline at the end warning. By Pei Yong Zhang.
*
* Revision 1.3 2001/05/28 21:11:16 tng
* Schema: Various DatatypeValidator fix. By Pei Yong Zhang
*
* Revision 1.2 2001/05/16 19:01:04 tng
* Schema: Typo fix in Base64
*
* Revision 1.1 2001/05/16 15:25:36 tng
* Schema: Add Base64 and HexBin. By Pei Yong Zhang.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/Base64.hpp>
#include <util/XMLString.hpp>
#include <util/Janitor.hpp>
#include <util/PlatformUtils.hpp>
#include <util/TransService.hpp>
// ---------------------------------------------------------------------------
// constants
// ---------------------------------------------------------------------------
static const int BASELENGTH = 255;
static const int FOURBYTE = 4;
// ---------------------------------------------------------------------------
// class data member
// ---------------------------------------------------------------------------
// the base64 alphabet according to definition in RFC 2045
const XMLCh Base64::base64Alphabet[64] = {
chLatin_A, chLatin_B, chLatin_C, chLatin_D, chLatin_E,
chLatin_F, chLatin_G, chLatin_H, chLatin_I, chLatin_J,
chLatin_K, chLatin_L, chLatin_M, chLatin_N, chLatin_O,
chLatin_P, chLatin_Q, chLatin_R, chLatin_S, chLatin_T,
chLatin_U, chLatin_V, chLatin_W, chLatin_X, chLatin_Y,
chLatin_Z, chLatin_a, chLatin_b, chLatin_c, chLatin_d,
chLatin_e, chLatin_f, chLatin_g, chLatin_h, chLatin_i,
chLatin_j, chLatin_k, chLatin_l, chLatin_m, chLatin_n,
chLatin_o, chLatin_p, chLatin_q, chLatin_r, chLatin_s,
chLatin_t, chLatin_u, chLatin_v, chLatin_w, chLatin_x,
chLatin_y, chLatin_z, chDigit_0, chDigit_1, chDigit_2,
chDigit_3, chDigit_4, chDigit_5, chDigit_6, chDigit_7,
chDigit_8, chDigit_9, chPlus, chForwardSlash
};
const XMLCh Base64::base64Padding = chEqual;
XMLCh Base64::base64Inverse[ BASELENGTH ];
bool Base64::isInitialized = false;
// number of quadruplets per one line ( must be >1 and <19 )
const unsigned int Base64::quadsPerLine = 15;
XMLCh* Base64::encode(
const XMLCh* const inputData,
const int inputLength,
int *outputLength )
{
if (!isInitialized)
init();
if ( inputData == 0 )
return 0;
int quadrupletCount = ( inputLength + 2 ) / 3;
if (quadrupletCount == 0)
return 0;
// number of rows in encoded stream ( including the last one )
int lineCount = ( quadrupletCount + quadsPerLine-1 ) / quadsPerLine;
//
// convert the triplet(s) to quadruplet(s)
//
XMLCh b1, b2, b3, b4; // base64 binary codes ( 0..63 )
int inputIndex = 0;
int outputIndex = 0;
XMLCh *encodedData =
new XMLCh[ quadrupletCount*FOURBYTE + lineCount + 1 ];
//
// Process all quadruplet(s) except the last
//
int quad = 1;
for (; quad <= quadrupletCount-1; quad++ )
{
// read triplet from the input stream
split1stOctet( inputData[ inputIndex++ ], b1, b2 );
split2ndOctet( inputData[ inputIndex++ ], b2, b3 );
split3rdOctet( inputData[ inputIndex++ ], b3, b4 );
// write quadruplet to the output stream
encodedData[ outputIndex++ ] = base64Alphabet[ b1 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b2 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b3 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b4 ];
if (( quad % quadsPerLine ) == 0 )
encodedData[ outputIndex++ ] = chLF;
}
//
// process the last Quadruplet
//
// first octet is present always, process it
split1stOctet( inputData[ inputIndex++ ], b1, b2 );
encodedData[ outputIndex++ ] = base64Alphabet[ b1 ];
if( inputIndex < inputLength )
{
// second octet is present, process it
split2ndOctet( inputData[ inputIndex++ ], b2, b3 );
encodedData[ outputIndex++ ] = base64Alphabet[ b2 ];
if( inputIndex < inputLength )
{
// third octet present, process it
// no PAD e.g. 3cQl
split3rdOctet( inputData[ inputIndex++ ], b3, b4 );
encodedData[ outputIndex++ ] = base64Alphabet[ b3 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b4 ];
}
else
{
// third octet not present
// one PAD e.g. 3cQ=
encodedData[ outputIndex++ ] = base64Alphabet[ b3 ];
encodedData[ outputIndex++ ] = base64Padding;
}
}
else
{
// second octet not present
// two PADs e.g. 3c==
encodedData[ outputIndex++ ] = base64Padding;
encodedData[ outputIndex++ ] = base64Padding;
}
// write out end of the last line
encodedData[ outputIndex++ ] = chLF;
// write out end of string
encodedData[ outputIndex ] = 0;
if( outputLength != 0 )
(*outputLength) = outputIndex;
return encodedData;
}
//
// delete the buffer allocated by decode() if
// decoding is successfully done.
//
// In previous version, we use XMLString::strLen(decodedData)
// to get the length, this will fail for test case containing
// consequtive "A", such "AAFF", or "ab56AA56". Instead of
// returning 3/6, we have 0 and 3, indicating that "AA", after
// decoded, is interpreted as <null> by the strLen().
//
// Since decode() has track of length of the decoded data, we
// will get this length from decode(), instead of strLen().
//
int Base64::getDataLength( const XMLCh* const inputData )
{
int retLen = 0;
XMLCh* decodedData = decode( inputData, retLen );
if ( !decodedData )
return -1;
else
{
delete[] decodedData;
return retLen;
}
}
//
// return 0(null) if invalid data found.
// return the buffer containning decoded data otherwise
// the caller is responsible for the de-allocation of the
// buffer returned.
//
// temporary data, rawInputData, is ALWAYS released by this function.
//
XMLCh* Base64::decode( const XMLCh* const inputData, int& outputLength )
{
if (!isInitialized)
init();
if (( inputData == 0 ) || ( *inputData == 0 ))
return 0;
//
// remove all whitespaces from the base64Data
//
int inputLength = XMLString::stringLen( inputData );
XMLCh* rawInputData = new XMLCh[ inputLength + 1 ];
ArrayJanitor<XMLCh> jan(rawInputData);
int inputIndex = 0;
int rawInputLength = 0;
while ( inputIndex < inputLength )
{
// if( !isspace( inputData[ inputIndex ] ))
if (!XMLPlatformUtils::fgTransService->isSpace(inputData[inputIndex]))
rawInputData[ rawInputLength++ ] = inputData[ inputIndex ];
inputIndex++;
}
rawInputData[ rawInputLength ] = 0;
// the length of raw data should be divisible by four
if (( rawInputLength % FOURBYTE ) != 0 )
return 0;
int quadrupletCount = rawInputLength / FOURBYTE;
if ( quadrupletCount == 0 )
return 0;
//
// convert the quadruplet(s) to triplet(s)
//
XMLCh d1, d2, d3, d4; // base64 characters
XMLCh b1, b2, b3, b4; // base64 binary codes ( 0..64 )
int rawInputIndex = 0;
int outputIndex = 0;
XMLCh *decodedData = new XMLCh[ quadrupletCount*3 + 1 ];
//
// Process all quadruplet(s) except the last
//
int quad = 1;
for (; quad <= quadrupletCount-1; quad++ )
{
// read quadruplet from the input stream
if (!isData( (d1 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d2 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d3 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d4 = rawInputData[ rawInputIndex++ ]) ))
{
// if found "no data" just return NULL
delete[] decodedData;
return 0;
}
b1 = base64Inverse[ d1 ];
b2 = base64Inverse[ d2 ];
b3 = base64Inverse[ d3 ];
b4 = base64Inverse[ d4 ];
// write triplet to the output stream
decodedData[ outputIndex++ ] = set1stOctet(b1, b2);
decodedData[ outputIndex++ ] = set2ndOctet(b2, b3);
decodedData[ outputIndex++ ] = set3rdOctet(b3, b4);
}
//
// process the last Quadruplet
//
// first two octets are present always, process them
if (!isData( (d1 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d2 = rawInputData[ rawInputIndex++ ]) ))
{
// if found "no data" just return NULL
delete[] decodedData;
return 0;
}
b1 = base64Inverse[ d1 ];
b2 = base64Inverse[ d2 ];
// try to process last two octets
d3 = rawInputData[ rawInputIndex++ ];
d4 = rawInputData[ rawInputIndex++ ];
if (!isData( d3 ) || !isData( d4 ))
{
// check if last two are PAD characters
if (isPad( d3 ) && isPad( d4 ))
{
// two PAD e.g. 3c==
if ((b2 & 0xf) != 0) // last 4 bits should be zero
{
delete[] decodedData;
return 0;
}
decodedData[ outputIndex++ ] = set1stOctet(b1, b2);
}
else if (!isPad( d3 ) && isPad( d4 ))
{
// one PAD e.g. 3cQ=
b3 = base64Inverse[ d3 ];
if (( b3 & 0x3 ) != 0 ) // last 2 bits should be zero
{
delete[] decodedData;
return 0;
}
decodedData[ outputIndex++ ] = set1stOctet( b1, b2 );
decodedData[ outputIndex++ ] = set2ndOctet( b2, b3 );
}
else
{
// an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
delete[] decodedData;
return 0;
}
}
else
{
// no PAD e.g 3cQl
b3 = base64Inverse[ d3 ];
b4 = base64Inverse[ d4 ];
decodedData[ outputIndex++ ] = set1stOctet( b1, b2 );
decodedData[ outputIndex++ ] = set2ndOctet( b2, b3 );
decodedData[ outputIndex++ ] = set3rdOctet( b3, b4 );
}
// write out the end of string
decodedData[ outputIndex ] = 0;
outputLength = outputIndex;
return decodedData;
}
// -----------------------------------------------------------------------
// Helper methods
// -----------------------------------------------------------------------
void Base64::init()
{
if (isInitialized)
return;
isInitialized = true;
// create inverse table for base64 decoding
// if base64Alphabet[ 17 ] = 'R', then base64Inverse[ 'R' ] = 17
// for characters not in base64Alphabet the base64Inverse[] = -1
int i;
// set all fields to -1
for ( i = 0; i < BASELENGTH; i++ )
base64Inverse[i] = (XMLCh)-1;
// compute inverse table
for ( i = 0; i < 64; i++ )
base64Inverse[ base64Alphabet[i] ] = (XMLCh)i;
}
bool Base64::isData(const XMLCh& octet)
{
// sanity check to avoid out-of-bound index
if (( octet >= BASELENGTH ) || ( octet < 0 ))
return false;
return( base64Inverse[octet] != (XMLCh) -1);
}
<commit_msg>Null-terminate base64Alphabet.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.6 2001/10/15 19:42:16 knoaman
* Null-terminate base64Alphabet.
*
* Revision 1.5 2001/10/10 19:14:08 peiyongz
* Patch from Petr Gotthard : encode() provided and some other changes
*
* Revision 1.4 2001/06/07 20:55:20 tng
* Fix no newline at the end warning. By Pei Yong Zhang.
*
* Revision 1.3 2001/05/28 21:11:16 tng
* Schema: Various DatatypeValidator fix. By Pei Yong Zhang
*
* Revision 1.2 2001/05/16 19:01:04 tng
* Schema: Typo fix in Base64
*
* Revision 1.1 2001/05/16 15:25:36 tng
* Schema: Add Base64 and HexBin. By Pei Yong Zhang.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/Base64.hpp>
#include <util/XMLString.hpp>
#include <util/Janitor.hpp>
#include <util/PlatformUtils.hpp>
#include <util/TransService.hpp>
// ---------------------------------------------------------------------------
// constants
// ---------------------------------------------------------------------------
static const int BASELENGTH = 255;
static const int FOURBYTE = 4;
// ---------------------------------------------------------------------------
// class data member
// ---------------------------------------------------------------------------
// the base64 alphabet according to definition in RFC 2045
const XMLCh Base64::base64Alphabet[] = {
chLatin_A, chLatin_B, chLatin_C, chLatin_D, chLatin_E,
chLatin_F, chLatin_G, chLatin_H, chLatin_I, chLatin_J,
chLatin_K, chLatin_L, chLatin_M, chLatin_N, chLatin_O,
chLatin_P, chLatin_Q, chLatin_R, chLatin_S, chLatin_T,
chLatin_U, chLatin_V, chLatin_W, chLatin_X, chLatin_Y,
chLatin_Z, chLatin_a, chLatin_b, chLatin_c, chLatin_d,
chLatin_e, chLatin_f, chLatin_g, chLatin_h, chLatin_i,
chLatin_j, chLatin_k, chLatin_l, chLatin_m, chLatin_n,
chLatin_o, chLatin_p, chLatin_q, chLatin_r, chLatin_s,
chLatin_t, chLatin_u, chLatin_v, chLatin_w, chLatin_x,
chLatin_y, chLatin_z, chDigit_0, chDigit_1, chDigit_2,
chDigit_3, chDigit_4, chDigit_5, chDigit_6, chDigit_7,
chDigit_8, chDigit_9, chPlus, chForwardSlash, chNull
};
const XMLCh Base64::base64Padding = chEqual;
XMLCh Base64::base64Inverse[ BASELENGTH ];
bool Base64::isInitialized = false;
// number of quadruplets per one line ( must be >1 and <19 )
const unsigned int Base64::quadsPerLine = 15;
XMLCh* Base64::encode(
const XMLCh* const inputData,
const int inputLength,
int *outputLength )
{
if (!isInitialized)
init();
if ( inputData == 0 )
return 0;
int quadrupletCount = ( inputLength + 2 ) / 3;
if (quadrupletCount == 0)
return 0;
// number of rows in encoded stream ( including the last one )
int lineCount = ( quadrupletCount + quadsPerLine-1 ) / quadsPerLine;
//
// convert the triplet(s) to quadruplet(s)
//
XMLCh b1, b2, b3, b4; // base64 binary codes ( 0..63 )
int inputIndex = 0;
int outputIndex = 0;
XMLCh *encodedData =
new XMLCh[ quadrupletCount*FOURBYTE + lineCount + 1 ];
//
// Process all quadruplet(s) except the last
//
int quad = 1;
for (; quad <= quadrupletCount-1; quad++ )
{
// read triplet from the input stream
split1stOctet( inputData[ inputIndex++ ], b1, b2 );
split2ndOctet( inputData[ inputIndex++ ], b2, b3 );
split3rdOctet( inputData[ inputIndex++ ], b3, b4 );
// write quadruplet to the output stream
encodedData[ outputIndex++ ] = base64Alphabet[ b1 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b2 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b3 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b4 ];
if (( quad % quadsPerLine ) == 0 )
encodedData[ outputIndex++ ] = chLF;
}
//
// process the last Quadruplet
//
// first octet is present always, process it
split1stOctet( inputData[ inputIndex++ ], b1, b2 );
encodedData[ outputIndex++ ] = base64Alphabet[ b1 ];
if( inputIndex < inputLength )
{
// second octet is present, process it
split2ndOctet( inputData[ inputIndex++ ], b2, b3 );
encodedData[ outputIndex++ ] = base64Alphabet[ b2 ];
if( inputIndex < inputLength )
{
// third octet present, process it
// no PAD e.g. 3cQl
split3rdOctet( inputData[ inputIndex++ ], b3, b4 );
encodedData[ outputIndex++ ] = base64Alphabet[ b3 ];
encodedData[ outputIndex++ ] = base64Alphabet[ b4 ];
}
else
{
// third octet not present
// one PAD e.g. 3cQ=
encodedData[ outputIndex++ ] = base64Alphabet[ b3 ];
encodedData[ outputIndex++ ] = base64Padding;
}
}
else
{
// second octet not present
// two PADs e.g. 3c==
encodedData[ outputIndex++ ] = base64Padding;
encodedData[ outputIndex++ ] = base64Padding;
}
// write out end of the last line
encodedData[ outputIndex++ ] = chLF;
// write out end of string
encodedData[ outputIndex ] = 0;
if( outputLength != 0 )
(*outputLength) = outputIndex;
return encodedData;
}
//
// delete the buffer allocated by decode() if
// decoding is successfully done.
//
// In previous version, we use XMLString::strLen(decodedData)
// to get the length, this will fail for test case containing
// consequtive "A", such "AAFF", or "ab56AA56". Instead of
// returning 3/6, we have 0 and 3, indicating that "AA", after
// decoded, is interpreted as <null> by the strLen().
//
// Since decode() has track of length of the decoded data, we
// will get this length from decode(), instead of strLen().
//
int Base64::getDataLength( const XMLCh* const inputData )
{
int retLen = 0;
XMLCh* decodedData = decode( inputData, retLen );
if ( !decodedData )
return -1;
else
{
delete[] decodedData;
return retLen;
}
}
//
// return 0(null) if invalid data found.
// return the buffer containning decoded data otherwise
// the caller is responsible for the de-allocation of the
// buffer returned.
//
// temporary data, rawInputData, is ALWAYS released by this function.
//
XMLCh* Base64::decode( const XMLCh* const inputData, int& outputLength )
{
if (!isInitialized)
init();
if (( inputData == 0 ) || ( *inputData == 0 ))
return 0;
//
// remove all whitespaces from the base64Data
//
int inputLength = XMLString::stringLen( inputData );
XMLCh* rawInputData = new XMLCh[ inputLength + 1 ];
ArrayJanitor<XMLCh> jan(rawInputData);
int inputIndex = 0;
int rawInputLength = 0;
while ( inputIndex < inputLength )
{
// if( !isspace( inputData[ inputIndex ] ))
if (!XMLPlatformUtils::fgTransService->isSpace(inputData[inputIndex]))
rawInputData[ rawInputLength++ ] = inputData[ inputIndex ];
inputIndex++;
}
rawInputData[ rawInputLength ] = 0;
// the length of raw data should be divisible by four
if (( rawInputLength % FOURBYTE ) != 0 )
return 0;
int quadrupletCount = rawInputLength / FOURBYTE;
if ( quadrupletCount == 0 )
return 0;
//
// convert the quadruplet(s) to triplet(s)
//
XMLCh d1, d2, d3, d4; // base64 characters
XMLCh b1, b2, b3, b4; // base64 binary codes ( 0..64 )
int rawInputIndex = 0;
int outputIndex = 0;
XMLCh *decodedData = new XMLCh[ quadrupletCount*3 + 1 ];
//
// Process all quadruplet(s) except the last
//
int quad = 1;
for (; quad <= quadrupletCount-1; quad++ )
{
// read quadruplet from the input stream
if (!isData( (d1 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d2 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d3 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d4 = rawInputData[ rawInputIndex++ ]) ))
{
// if found "no data" just return NULL
delete[] decodedData;
return 0;
}
b1 = base64Inverse[ d1 ];
b2 = base64Inverse[ d2 ];
b3 = base64Inverse[ d3 ];
b4 = base64Inverse[ d4 ];
// write triplet to the output stream
decodedData[ outputIndex++ ] = set1stOctet(b1, b2);
decodedData[ outputIndex++ ] = set2ndOctet(b2, b3);
decodedData[ outputIndex++ ] = set3rdOctet(b3, b4);
}
//
// process the last Quadruplet
//
// first two octets are present always, process them
if (!isData( (d1 = rawInputData[ rawInputIndex++ ]) ) ||
!isData( (d2 = rawInputData[ rawInputIndex++ ]) ))
{
// if found "no data" just return NULL
delete[] decodedData;
return 0;
}
b1 = base64Inverse[ d1 ];
b2 = base64Inverse[ d2 ];
// try to process last two octets
d3 = rawInputData[ rawInputIndex++ ];
d4 = rawInputData[ rawInputIndex++ ];
if (!isData( d3 ) || !isData( d4 ))
{
// check if last two are PAD characters
if (isPad( d3 ) && isPad( d4 ))
{
// two PAD e.g. 3c==
if ((b2 & 0xf) != 0) // last 4 bits should be zero
{
delete[] decodedData;
return 0;
}
decodedData[ outputIndex++ ] = set1stOctet(b1, b2);
}
else if (!isPad( d3 ) && isPad( d4 ))
{
// one PAD e.g. 3cQ=
b3 = base64Inverse[ d3 ];
if (( b3 & 0x3 ) != 0 ) // last 2 bits should be zero
{
delete[] decodedData;
return 0;
}
decodedData[ outputIndex++ ] = set1stOctet( b1, b2 );
decodedData[ outputIndex++ ] = set2ndOctet( b2, b3 );
}
else
{
// an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
delete[] decodedData;
return 0;
}
}
else
{
// no PAD e.g 3cQl
b3 = base64Inverse[ d3 ];
b4 = base64Inverse[ d4 ];
decodedData[ outputIndex++ ] = set1stOctet( b1, b2 );
decodedData[ outputIndex++ ] = set2ndOctet( b2, b3 );
decodedData[ outputIndex++ ] = set3rdOctet( b3, b4 );
}
// write out the end of string
decodedData[ outputIndex ] = 0;
outputLength = outputIndex;
return decodedData;
}
// -----------------------------------------------------------------------
// Helper methods
// -----------------------------------------------------------------------
void Base64::init()
{
if (isInitialized)
return;
isInitialized = true;
// create inverse table for base64 decoding
// if base64Alphabet[ 17 ] = 'R', then base64Inverse[ 'R' ] = 17
// for characters not in base64Alphabet the base64Inverse[] = -1
int i;
// set all fields to -1
for ( i = 0; i < BASELENGTH; i++ )
base64Inverse[i] = (XMLCh)-1;
// compute inverse table
for ( i = 0; i < 64; i++ )
base64Inverse[ base64Alphabet[i] ] = (XMLCh)i;
}
bool Base64::isData(const XMLCh& octet)
{
// sanity check to avoid out-of-bound index
if (( octet >= BASELENGTH ) || ( octet < 0 ))
return false;
return( base64Inverse[octet] != (XMLCh) -1);
}
<|endoftext|> |
<commit_before>#ifdef USE_SDL
#include <SDL.h>
#endif
#include "bitmap.h"
#include "events.h"
#include "exceptions/shutdown_exception.h"
#include "funcs.h"
#include "thread.h"
namespace Util{
EventManager::EventManager(){
}
#ifdef USE_SDL
void EventManager::runSDL(){
SDL_Event event;
while (SDL_PollEvent(&event) == 1){
switch (event.type){
case SDL_QUIT : {
dispatch(CloseWindow);
break;
}
case SDL_VIDEORESIZE : {
int width = event.resize.w;
int height = event.resize.h;
/* to keep the perspective correct
* 640/480 = 1.33333
*/
if (width > height){
height = (int)((double) width / 1.3333333333);
} else {
width = (int)((double) height * 1.3333333333);
}
dispatch(ResizeScreen, width, height);
break;
}
default : {
break;
}
}
}
}
#endif
void EventManager::run(){
#ifdef USE_SDL
runSDL();
#endif
}
/* kill the program if the user requests */
void EventManager::waitForThread(WaitThread & thread){
while (!thread.isRunning()){
try{
run();
} catch (const ShutdownException & death){
thread.kill();
throw death;
}
Util::rest(10);
}
}
EventManager::~EventManager(){
}
void EventManager::dispatch(Event type, int arg1, int arg2){
switch (type){
case ResizeScreen : {
Bitmap::setGraphicsMode(0, arg1, arg2);
break;
}
default : break;
}
}
void EventManager::dispatch(Event type){
switch (type){
case CloseWindow : {
throw ShutdownException();
}
default : break;
}
}
}
<commit_msg>update configuration when screen size changes<commit_after>#ifdef USE_SDL
#include <SDL.h>
#endif
#include "bitmap.h"
#include "events.h"
#include "exceptions/shutdown_exception.h"
#include "configuration.h"
#include "globals.h"
#include "funcs.h"
#include "thread.h"
namespace Util{
EventManager::EventManager(){
}
#ifdef USE_SDL
void EventManager::runSDL(){
SDL_Event event;
while (SDL_PollEvent(&event) == 1){
switch (event.type){
case SDL_QUIT : {
dispatch(CloseWindow);
break;
}
case SDL_VIDEORESIZE : {
int width = event.resize.w;
int height = event.resize.h;
/* to keep the perspective correct
* 640/480 = 1.33333
*/
if (width > height){
height = (int)((double) width / 1.3333333333);
} else {
width = (int)((double) height * 1.3333333333);
}
dispatch(ResizeScreen, width, height);
break;
}
default : {
break;
}
}
}
}
#endif
void EventManager::run(){
#ifdef USE_SDL
runSDL();
#endif
}
/* kill the program if the user requests */
void EventManager::waitForThread(WaitThread & thread){
while (!thread.isRunning()){
try{
run();
} catch (const ShutdownException & death){
thread.kill();
throw death;
}
Util::rest(10);
}
}
EventManager::~EventManager(){
}
void EventManager::dispatch(Event type, int arg1, int arg2){
switch (type){
case ResizeScreen : {
Global::debug(0) << "Resizing screen to " << arg1 << ", " << arg2 << std::endl;
Bitmap::setGraphicsMode(0, arg1, arg2);
Configuration::setScreenWidth(arg1);
Configuration::setScreenHeight(arg2);
break;
}
default : break;
}
}
void EventManager::dispatch(Event type){
switch (type){
case CloseWindow : {
throw ShutdownException();
}
default : break;
}
}
}
<|endoftext|> |
<commit_before>#include "util/logger.h"
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog/async.h>
void khorost::log::prepare_logger(const config& configure, const std::string& logger_name) {
spdlog::init_thread_pool(8192, 1);
spdlog::flush_every(std::chrono::seconds(10));
const auto prefix_key = "log:" + logger_name;
const auto pattern_file = configure.get_value(prefix_key + ":pattern", "[%Y-%m-%d %T.%F] [%n] [thread %t] [%l] %v");
const auto pattern_console = configure.get_value(prefix_key + ":pattern",
"[%Y-%m-%d %T.%F] [%n] [thread %t] [%^%l%$] %v");
const auto level = configure.get_value(prefix_key + ":level", "WARNING");
auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
configure.get_value(prefix_key + ":file_name", "./log")
, configure.get_value(prefix_key + ":max_file_size", 1048576 * 5)
, configure.get_value(prefix_key + ":max_files", 3));
rotating_sink->set_pattern(pattern_file);
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_pattern(pattern_console);
std::vector<spdlog::sink_ptr> sinks = {console_sink, rotating_sink};
if (configure.is_value(prefix_key + ":async", true)) {
spdlog::register_logger(std::make_shared<spdlog::async_logger>(logger_name, sinks.begin(), sinks.end(),
spdlog::thread_pool(),
spdlog::async_overflow_policy::block));
} else {
spdlog::register_logger(std::make_shared<spdlog::logger>(logger_name, sinks.begin(), sinks.end()));
}
const auto logger = spdlog::get(logger_name);
if (logger != nullptr) {
if (level == "DEBUG") {
logger->set_level(spdlog::level::debug);
} else if (level == "TRACE") {
logger->set_level(spdlog::level::trace);
} else if (level == "INFO") {
logger->set_level(spdlog::level::info);
} else if (level == "ERROR") {
logger->set_level(spdlog::level::err);
} else if (level == "CRITICAL") {
logger->set_level(spdlog::level::critical);
} else if (level == "OFF") {
logger->set_level(spdlog::level::off);
} else {
logger->set_level(spdlog::level::warn);
}
logger->info("Logger prepare successful. level = {}", level);
}
}
<commit_msg>fix logger<commit_after>#include "util/logger.h"
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog/async.h>
void khorost::log::prepare_logger(const config& configure, const std::string& logger_name) {
spdlog::init_thread_pool(8192, 1);
spdlog::flush_every(std::chrono::seconds(10));
const auto prefix_key = "log:" + logger_name;
const auto pattern_file = configure.get_value(prefix_key + ":pattern", "[%Y-%m-%d %T.%F] [%n] [thread %t] [%l] %v");
const auto pattern_console = configure.get_value(prefix_key + ":pattern",
"[%Y-%m-%d %T.%F] [%n] [thread %t] [%^%l%$] %v");
const auto level = configure.get_value(prefix_key + ":level", "WARNING");
auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
configure.get_value(prefix_key + ":file_name", "./log")
, configure.get_value(prefix_key + ":max_file_size", 1048576 * 10)
, configure.get_value(prefix_key + ":max_files", 5));
rotating_sink->set_pattern(pattern_file);
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_pattern(pattern_console);
std::vector<spdlog::sink_ptr> sinks = {console_sink, rotating_sink};
if (configure.is_value(prefix_key + ":async", true)) {
static auto tp = std::make_shared<spdlog::details::thread_pool>(8192, 2); // TODO залепуха, исправить
register_logger(std::make_shared<spdlog::async_logger>(logger_name, sinks.begin(), sinks.end(),
tp,
spdlog::async_overflow_policy::block));
} else {
register_logger(std::make_shared<spdlog::logger>(logger_name, sinks.begin(), sinks.end()));
}
const auto logger = spdlog::get(logger_name);
if (logger != nullptr) {
if (level == "DEBUG") {
logger->set_level(spdlog::level::debug);
} else if (level == "TRACE") {
logger->set_level(spdlog::level::trace);
} else if (level == "INFO") {
logger->set_level(spdlog::level::info);
} else if (level == "ERROR") {
logger->set_level(spdlog::level::err);
} else if (level == "CRITICAL") {
logger->set_level(spdlog::level::critical);
} else if (level == "OFF") {
logger->set_level(spdlog::level::off);
} else {
logger->set_level(spdlog::level::warn);
}
logger->info("Logger prepare successful. level = {}", level);
}
}
<|endoftext|> |
<commit_before>/**
* Runtime CPU detection
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/loadstor.h>
#include <botan/mem_ops.h>
#if defined(BOTAN_TARGET_ARCH_IS_X86) || defined(BOTAN_TARGET_ARCH_IS_AMD64)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type) } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_ICC)
#include <ia32intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type) } while(0);
#elif defined(BOTAN_BUILD_COMPILER_IS_GCC)
#include <cpuid.h>
#define CALL_CPUID(type, out) \
do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0);
#endif
#else
// In all other cases, just zeroize the supposed cpuid output
#define CALL_CPUID(type, out) out[0] = out[1] = out[2] = out[3] = 0;
#endif
namespace Botan {
namespace {
u32bit get_x86_cache_line_size()
{
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
CALL_CPUID(0, cpuid);
if(same_mem(cpuid + 1, INTEL_CPUID, 3))
{
CALL_CPUID(1, cpuid);
return 8 * get_byte(2, cpuid[1]);
}
else if(same_mem(cpuid + 1, AMD_CPUID, 3))
{
CALL_CPUID(0x80000005, cpuid);
return get_byte(3, cpuid[2]);
}
else
return 32; // default cache line guess
}
}
/*
* Call the x86 CPUID instruction and return the contents of ecx and
* edx, which contain the feature masks.
*/
u64bit CPUID::x86_processor_flags()
{
static u64bit proc_flags = 0;
if(proc_flags)
return proc_flags;
u32bit cpuid[4] = { 0 };
CALL_CPUID(1, cpuid);
// Set the FPU bit on to force caching in proc_flags
proc_flags = ((u64bit)cpuid[2] << 32) | cpuid[3] | 1;
return proc_flags;
}
u32bit CPUID::cache_line_size()
{
static u32bit cl_size = 0;
if(cl_size)
return cl_size;
cl_size = get_x86_cache_line_size();
return cl_size;
}
}
<commit_msg>Enable CPUID on x86 (checking wrong macro name)<commit_after>/**
* Runtime CPU detection
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/loadstor.h>
#include <botan/mem_ops.h>
#if defined(BOTAN_TARGET_ARCH_IS_IA32) || defined(BOTAN_TARGET_ARCH_IS_AMD64)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type) } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_ICC)
#include <ia32intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type) } while(0);
#elif defined(BOTAN_BUILD_COMPILER_IS_GCC)
#include <cpuid.h>
#define CALL_CPUID(type, out) \
do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0);
#endif
#else
// In all other cases, just zeroize the supposed cpuid output
#define CALL_CPUID(type, out) out[0] = out[1] = out[2] = out[3] = 0;
#endif
namespace Botan {
namespace {
u32bit get_x86_cache_line_size()
{
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
CALL_CPUID(0, cpuid);
if(same_mem(cpuid + 1, INTEL_CPUID, 3))
{
CALL_CPUID(1, cpuid);
return 8 * get_byte(2, cpuid[1]);
}
else if(same_mem(cpuid + 1, AMD_CPUID, 3))
{
CALL_CPUID(0x80000005, cpuid);
return get_byte(3, cpuid[2]);
}
else
return 32; // default cache line guess
}
}
/*
* Call the x86 CPUID instruction and return the contents of ecx and
* edx, which contain the feature masks.
*/
u64bit CPUID::x86_processor_flags()
{
static u64bit proc_flags = 0;
if(proc_flags)
return proc_flags;
u32bit cpuid[4] = { 0 };
CALL_CPUID(1, cpuid);
// Set the FPU bit on to force caching in proc_flags
proc_flags = ((u64bit)cpuid[2] << 32) | cpuid[3] | 1;
return proc_flags;
}
u32bit CPUID::cache_line_size()
{
static u32bit cl_size = 0;
if(cl_size)
return cl_size;
cl_size = get_x86_cache_line_size();
return cl_size;
}
}
<|endoftext|> |
<commit_before>#include <vast/program.h>
#include <cstdlib>
#include <iostream>
#include <boost/exception/diagnostic_information.hpp>
#include <vast/exception.h>
#include <vast/comm/broccoli.h>
#include <vast/detail/cppa_type_info.h>
#include <vast/fs/path.h>
#include <vast/fs/operations.h>
#include <vast/ingest/ingestor.h>
#include <vast/meta/schema_manager.h>
#include <vast/query/client.h>
#include <vast/query/search.h>
#include <vast/store/archive.h>
#include <vast/util/logger.h>
#include <config.h>
#ifdef USE_PERFTOOLS
#include <google/profiler.h>
#include <google/heap-profiler.h>
#endif
namespace vast {
/// Declaration of global (extern) variables.
namespace util {
logger* LOGGER;
}
program::program()
: terminating_(false)
, return_(EXIT_SUCCESS)
{
}
program::~program()
{
}
bool program::init(std::string const& filename)
{
try
{
config_.load(filename);
do_init();
return true;
}
catch (boost::program_options::unknown_option const& e)
{
std::cerr << e.what();
}
return false;
}
bool program::init(int argc, char *argv[])
{
try
{
config_.load(argc, argv);
if (argc < 2 || config_.check("help") || config_.check("advanced"))
{
config_.print(std::cerr, config_.check("advanced"));
return false;
}
do_init();
return true;
}
catch (config_exception const& e)
{
std::cerr << e.what() << std::endl;
}
catch (boost::program_options::unknown_option const& e)
{
std::cerr << e.what() << ", try -h or --help" << std::endl;
}
catch (boost::exception const& e)
{
std::cerr << boost::diagnostic_information(e);
}
return false;
}
void program::start()
{
using namespace cppa;
announce(typeid(ze::uuid), new detail::uuid_type_info);
announce(typeid(ze::event), new detail::event_type_info);
try
{
auto log_dir = config_.get<fs::path>("log-dir");
#ifdef USE_PERFTOOLS
if (config_.check("perftools-heap"))
{
LOG(info, core) << "starting perftools CPU profiler";
::HeapProfilerStart((log_dir / "heap.profile").string().data());
}
if (config_.check("perftools-cpu"))
{
LOG(info, core) << "starting perftools heap profiler";
::ProfilerStart((log_dir / "cpu.profile").string().data());
}
#endif
if (config_.check("profile"))
{
auto const& filename = log_dir / "profiler.log";
auto interval = config_.get<unsigned>("profiler-interval");
profiler_.init(filename, std::chrono::milliseconds(interval));
profiler_.start();
}
schema_manager_ = spawn<meta::schema_manager>();
if (config_.check("schema"))
{
send(schema_manager_, atom("load"), config_.get<std::string>("schema"));
if (config_.check("print-schema"))
{
send(schema_manager_, atom("print"));
receive(
on(atom("schema"), arg_match) >> [](std::string const& schema)
{
std::cout << schema << std::endl;
});
return;
}
}
comm::broccoli::init(config_.check("broccoli-messages"),
config_.check("broccoli-calltrace"));
if (config_.check("comp-archive"))
{
archive_ = spawn<store::archive>(
(config_.get<fs::path>("vast-dir") / "archive").string(),
config_.get<size_t>("archive.max-events-per-chunk"),
config_.get<size_t>("archive.max-segment-size") * 1000,
config_.get<size_t>("archive.max-segments"));
}
else
{
archive_ = remote_actor(
config_.get<std::string>("archive.host").data(),
config_.get<unsigned>("archive.port"));
}
if (config_.check("comp-ingestor"))
{
ingestor_ = spawn<ingest::ingestor>(archive_);
send(ingestor_,
atom("initialize"),
config_.get<std::string>("ingestor.host"),
config_.get<unsigned>("ingestor.port"));
if (config_.check("ingestor.events"))
{
auto events = config_.get<std::vector<std::string>>("ingestor.events");
for (auto& event : events)
{
LOG(verbose, store) << "subscribing to event " << event;
send(ingestor_, atom("subscribe"), event);
}
}
if (config_.check("ingestor.file"))
{
auto files = config_.get<std::vector<std::string>>("ingestor.file");
for (auto& file : files)
{
LOG(info, core) << "ingesting " << file;
send(ingestor_, atom("read_file"), file);
}
}
}
else
{
ingestor_ = remote_actor(
config_.get<std::string>("ingestor.host").data(),
config_.get<unsigned>("ingestor.port"));
}
if (config_.check("comp-search"))
{
search_ = spawn<query::search>(archive_);
send(search_,
atom("publish"),
config_.get<std::string>("search.host"),
config_.get<unsigned>("search.port"));
}
else
{
search_ = remote_actor(
config_.get<std::string>("search.host").data(),
config_.get<unsigned>("search.port"));
}
if (config_.check("query"))
{
query_client_ = spawn<query::client>(
search_,
config_.get<unsigned>("client.batch-size"));
send(query_client_,
atom("query"),
atom("create"),
config_.get<std::string>("query"));
}
await_all_others_done();
}
catch (...)
{
LOG(fatal, core)
<< "exception details:\n"
<< boost::current_exception_diagnostic_information();
return_ = EXIT_FAILURE;
}
if (! terminating_)
stop();
}
void program::stop()
{
using namespace cppa;
if (terminating_)
{
return_ = EXIT_FAILURE;
return;
}
terminating_ = true;
LOG(verbose, core) << "writing out in-memory state";
auto shutdown = make_any_tuple(atom("shutdown"));
if (config_.check("query"))
{
LOG(debug, core) << "stopping queries";
query_client_ << shutdown;
}
if (config_.check("comp-search"))
{
LOG(debug, core) << "stopping search component";
search_ << shutdown;
}
if (config_.check("comp-ingestor"))
{
LOG(debug, core) << "stopping ingestor component";
ingestor_ << shutdown;
}
if (config_.check("comp-archive"))
{
LOG(debug, core) << "stopping archive component";
archive_ << shutdown;
}
if (config_.check("profile"))
{
LOG(debug, core) << "stopping profiler";
profiler_.stop();
}
#ifdef USE_PERFTOOLS
if (config_.check("perftools-cpu"))
{
LOG(info, core) << "stopping perftools CPU profiler";
::ProfilerStop();
}
if (config_.check("perftools-heap") && ::IsHeapProfilerRunning())
{
LOG(info, core) << "stopping perftools heap profiler";
::HeapProfilerDump("cleanup");
::HeapProfilerStop();
}
#endif
LOG(verbose, core) << "state saved";
return_ = EXIT_SUCCESS;
await_all_others_done();
}
int program::end()
{
switch (return_)
{
case EXIT_SUCCESS:
LOG(verbose, core) << "VAST terminated cleanly";
break;
case EXIT_FAILURE:
LOG(verbose, core) << "VAST terminated with errors";
break;
default:
assert(! "invalid return code");
}
return return_;
}
void program::do_init()
{
auto vast_dir = config_.get<fs::path>("vast-dir");
if (! fs::exists(vast_dir))
fs::mkdir(vast_dir);
util::LOGGER = new util::logger(
static_cast<util::logger::level>(config_.get<int>("console-verbosity")),
static_cast<util::logger::level>(config_.get<int>("logfile-verbosity")),
config_.get<fs::path>("log-dir") / "vast.log");
LOG(verbose, core) << " _ _____ __________";
LOG(verbose, core) << "| | / / _ | / __/_ __/";
LOG(verbose, core) << "| |/ / __ |_\\ \\ / / ";
LOG(verbose, core) << "|___/_/ |_/___/ /_/ " << VAST_VERSION;
LOG(verbose, core) << "";
}
} // namespace vast
<commit_msg>Use new cppa::remote_actor string overload.<commit_after>#include <vast/program.h>
#include <cstdlib>
#include <iostream>
#include <boost/exception/diagnostic_information.hpp>
#include <vast/exception.h>
#include <vast/comm/broccoli.h>
#include <vast/detail/cppa_type_info.h>
#include <vast/fs/path.h>
#include <vast/fs/operations.h>
#include <vast/ingest/ingestor.h>
#include <vast/meta/schema_manager.h>
#include <vast/query/client.h>
#include <vast/query/search.h>
#include <vast/store/archive.h>
#include <vast/util/logger.h>
#include <config.h>
#ifdef USE_PERFTOOLS
#include <google/profiler.h>
#include <google/heap-profiler.h>
#endif
namespace vast {
/// Declaration of global (extern) variables.
namespace util {
logger* LOGGER;
}
program::program()
: terminating_(false)
, return_(EXIT_SUCCESS)
{
}
program::~program()
{
}
bool program::init(std::string const& filename)
{
try
{
config_.load(filename);
do_init();
return true;
}
catch (boost::program_options::unknown_option const& e)
{
std::cerr << e.what();
}
return false;
}
bool program::init(int argc, char *argv[])
{
try
{
config_.load(argc, argv);
if (argc < 2 || config_.check("help") || config_.check("advanced"))
{
config_.print(std::cerr, config_.check("advanced"));
return false;
}
do_init();
return true;
}
catch (config_exception const& e)
{
std::cerr << e.what() << std::endl;
}
catch (boost::program_options::unknown_option const& e)
{
std::cerr << e.what() << ", try -h or --help" << std::endl;
}
catch (boost::exception const& e)
{
std::cerr << boost::diagnostic_information(e);
}
return false;
}
void program::start()
{
using namespace cppa;
announce(typeid(ze::uuid), new detail::uuid_type_info);
announce(typeid(ze::event), new detail::event_type_info);
try
{
auto log_dir = config_.get<fs::path>("log-dir");
#ifdef USE_PERFTOOLS
if (config_.check("perftools-heap"))
{
LOG(info, core) << "starting perftools CPU profiler";
::HeapProfilerStart((log_dir / "heap.profile").string().data());
}
if (config_.check("perftools-cpu"))
{
LOG(info, core) << "starting perftools heap profiler";
::ProfilerStart((log_dir / "cpu.profile").string().data());
}
#endif
if (config_.check("profile"))
{
auto const& filename = log_dir / "profiler.log";
auto interval = config_.get<unsigned>("profiler-interval");
profiler_.init(filename, std::chrono::milliseconds(interval));
profiler_.start();
}
schema_manager_ = spawn<meta::schema_manager>();
if (config_.check("schema"))
{
send(schema_manager_, atom("load"), config_.get<std::string>("schema"));
if (config_.check("print-schema"))
{
send(schema_manager_, atom("print"));
receive(
on(atom("schema"), arg_match) >> [](std::string const& schema)
{
std::cout << schema << std::endl;
});
return;
}
}
comm::broccoli::init(config_.check("broccoli-messages"),
config_.check("broccoli-calltrace"));
if (config_.check("comp-archive"))
{
archive_ = spawn<store::archive>(
(config_.get<fs::path>("vast-dir") / "archive").string(),
config_.get<size_t>("archive.max-events-per-chunk"),
config_.get<size_t>("archive.max-segment-size") * 1000,
config_.get<size_t>("archive.max-segments"));
}
else
{
archive_ = remote_actor(
config_.get<std::string>("archive.host"),
config_.get<unsigned>("archive.port"));
}
if (config_.check("comp-ingestor"))
{
ingestor_ = spawn<ingest::ingestor>(archive_);
send(ingestor_,
atom("initialize"),
config_.get<std::string>("ingestor.host"),
config_.get<unsigned>("ingestor.port"));
if (config_.check("ingestor.events"))
{
auto events = config_.get<std::vector<std::string>>("ingestor.events");
for (auto& event : events)
{
LOG(verbose, store) << "subscribing to event " << event;
send(ingestor_, atom("subscribe"), event);
}
}
if (config_.check("ingestor.file"))
{
auto files = config_.get<std::vector<std::string>>("ingestor.file");
for (auto& file : files)
{
LOG(info, core) << "ingesting " << file;
send(ingestor_, atom("read_file"), file);
}
}
}
else
{
ingestor_ = remote_actor(
config_.get<std::string>("ingestor.host"),
config_.get<unsigned>("ingestor.port"));
}
if (config_.check("comp-search"))
{
search_ = spawn<query::search>(archive_);
send(search_,
atom("publish"),
config_.get<std::string>("search.host"),
config_.get<unsigned>("search.port"));
}
else
{
search_ = remote_actor(
config_.get<std::string>("search.host"),
config_.get<unsigned>("search.port"));
}
if (config_.check("query"))
{
query_client_ = spawn<query::client>(
search_,
config_.get<unsigned>("client.batch-size"));
send(query_client_,
atom("query"),
atom("create"),
config_.get<std::string>("query"));
}
await_all_others_done();
}
catch (...)
{
LOG(fatal, core)
<< "exception details:\n"
<< boost::current_exception_diagnostic_information();
return_ = EXIT_FAILURE;
}
if (! terminating_)
stop();
}
void program::stop()
{
using namespace cppa;
if (terminating_)
{
return_ = EXIT_FAILURE;
return;
}
terminating_ = true;
LOG(verbose, core) << "writing out in-memory state";
auto shutdown = make_any_tuple(atom("shutdown"));
if (config_.check("query"))
{
LOG(debug, core) << "stopping queries";
query_client_ << shutdown;
}
if (config_.check("comp-search"))
{
LOG(debug, core) << "stopping search component";
search_ << shutdown;
}
if (config_.check("comp-ingestor"))
{
LOG(debug, core) << "stopping ingestor component";
ingestor_ << shutdown;
}
if (config_.check("comp-archive"))
{
LOG(debug, core) << "stopping archive component";
archive_ << shutdown;
}
if (config_.check("profile"))
{
LOG(debug, core) << "stopping profiler";
profiler_.stop();
}
#ifdef USE_PERFTOOLS
if (config_.check("perftools-cpu"))
{
LOG(info, core) << "stopping perftools CPU profiler";
::ProfilerStop();
}
if (config_.check("perftools-heap") && ::IsHeapProfilerRunning())
{
LOG(info, core) << "stopping perftools heap profiler";
::HeapProfilerDump("cleanup");
::HeapProfilerStop();
}
#endif
LOG(verbose, core) << "state saved";
return_ = EXIT_SUCCESS;
await_all_others_done();
}
int program::end()
{
switch (return_)
{
case EXIT_SUCCESS:
LOG(verbose, core) << "VAST terminated cleanly";
break;
case EXIT_FAILURE:
LOG(verbose, core) << "VAST terminated with errors";
break;
default:
assert(! "invalid return code");
}
return return_;
}
void program::do_init()
{
auto vast_dir = config_.get<fs::path>("vast-dir");
if (! fs::exists(vast_dir))
fs::mkdir(vast_dir);
util::LOGGER = new util::logger(
static_cast<util::logger::level>(config_.get<int>("console-verbosity")),
static_cast<util::logger::level>(config_.get<int>("logfile-verbosity")),
config_.get<fs::path>("log-dir") / "vast.log");
LOG(verbose, core) << " _ _____ __________";
LOG(verbose, core) << "| | / / _ | / __/_ __/";
LOG(verbose, core) << "| |/ / __ |_\\ \\ / / ";
LOG(verbose, core) << "|___/_/ |_/___/ /_/ " << VAST_VERSION;
LOG(verbose, core) << "";
}
} // namespace vast
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007-2010, Python File Format Interface
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 Python File Format Interface
project 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 <iostream> // for dump
#include <stdexcept>
#include <boost/foreach.hpp>
#include "vcache/defines.hpp"
#include "vcache/mesh.hpp"
MVertex::MVertex(int vertex)
: vertex(vertex), cache_position(-1), score(-VCACHE_PRECISION), mfaces()
{
// nothing to do: faces are set in Mesh::add_face.
};
void MVertex::dump() const
{
std::cout << " vertex " << vertex << std::endl;
std::cout << " score " << score << std::endl;
std::cout << " cache pos " << cache_position << std::endl;
BOOST_FOREACH(boost::weak_ptr<MFace> mface, mfaces) {
if (MFacePtr f = mface.lock()) {
std::cout << " face " << f->mv0->vertex << "," << f->mv1->vertex << "," << f->mv2->vertex << std::endl;
};
};
}
Face::Face(int _v0, int _v1, int _v2)
{
// ensure it is not degenerate
if ((_v0 == _v1) || (_v1 == _v2) || (_v0 == _v2))
throw std::runtime_error("Degenerate face.");
// order vertex indices
if ((_v0 < _v1) && (_v0 < _v2)) {
v0 = _v0;
v1 = _v1;
v2 = _v2;
} else if ((_v1 < _v0) && (_v1 < _v2)) {
v0 = _v1;
v1 = _v2;
v2 = _v0;
} else if ((_v2 < _v0) && (_v2 < _v1)) {
v0 = _v2;
v1 = _v0;
v2 = _v1;
} else {
throw std::runtime_error("Oops. Face construction bug!");
}
};
bool Face::operator<(const Face & otherface) const
{
if (v0 < otherface.v0) return true;
if (v0 > otherface.v0) return false;
if (v1 < otherface.v1) return true;
if (v1 > otherface.v1) return false;
if (v2 < otherface.v2) return true;
return false;
};
bool Face::operator==(const Face & otherface) const
{
return ((v0 == otherface.v0) && (v1 == otherface.v1) && (v2 == otherface.v2));
};
MFace::MFace()
: mv0(), mv1(), mv2(), score(-3 * VCACHE_PRECISION)
{
// nothing to do
};
void MFace::dump() const
{
std::cout << " face " << mv0->vertex << "," << mv1->vertex << "," << mv2->vertex << std::endl;
std::cout << " score " << score << std::endl;
}
MVertexPtr Mesh::add_vertex(MFacePtr mface, int vertex)
{
MVertexPtr mvertex;
// search for vertex in mesh
VertexMap::const_iterator vertex_iter = _vertices.find(vertex);
if (vertex_iter != _vertices.end()) {
// vertex already exists!
mvertex = vertex_iter->second;
} else {
// create vertex
mvertex = MVertexPtr(new MVertex(vertex));
_vertices[vertex] = mvertex;
};
// update list of faces that have this vertex
mvertex->mfaces.insert(mface);
return mvertex;
};
Mesh::Mesh() : _faces(), _vertices() {};
MFacePtr Mesh::add_face(int v0, int v1, int v2)
{
// create face index and search if face already exists in mesh
Face face(v0, v1, v2);
FaceMap::const_iterator face_iter = _faces.find(face);
if (face_iter != _faces.end()) {
// face already exists!
return face_iter->second;
} else {
// create face
MFacePtr mface(new MFace);
_faces[face] = mface;
// create vertices and update links between faces and vertices
mface->mv0 = add_vertex(mface, v0);
mface->mv1 = add_vertex(mface, v1);
mface->mv2 = add_vertex(mface, v2);
return mface;
};
}
void Mesh::dump() const
{
std::cout << _faces.size() << " faces" << std::endl;
BOOST_FOREACH(FaceMap::value_type face, _faces) {
face.second->dump();
};
std::cout << _vertices.size() << " vertices" << std::endl;
BOOST_FOREACH(VertexMap::value_type vertex, _vertices) {
vertex.second->dump();
};
}
void Mesh::update_score(VertexScore const & vertex_score)
{
// calculate score of all vertices
BOOST_FOREACH(VertexMap::value_type vertex, _vertices) {
MVertexPtr mvertex = vertex.second;
mvertex->score =
vertex_score.get(
mvertex->cache_position,
mvertex->mfaces.size());
};
// calculate score of all triangles
BOOST_FOREACH(FaceMap::value_type face, _faces) {
MFacePtr mface = face.second;
mface->score =
mface->mv0->score +
mface->mv1->score +
mface->mv2->score;
};
}
std::list<MFacePtr> Mesh::get_cache_optimized_faces(VertexScore const & vertex_score)
{
}
<commit_msg>First draft of implementation (untested).<commit_after>/*
Copyright (c) 2007-2010, Python File Format Interface
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 Python File Format Interface
project 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 <deque>
#include <iostream> // for dump
#include <stdexcept>
#include <boost/foreach.hpp>
#include "vcache/defines.hpp"
#include "vcache/mesh.hpp"
MVertex::MVertex(int vertex)
: vertex(vertex), cache_position(-1), score(-VCACHE_PRECISION), mfaces()
{
// nothing to do: faces are set in Mesh::add_face.
};
void MVertex::dump() const
{
std::cout << " vertex " << vertex << std::endl;
std::cout << " score " << score << std::endl;
std::cout << " cache pos " << cache_position << std::endl;
BOOST_FOREACH(boost::weak_ptr<MFace> mface, mfaces) {
if (MFacePtr f = mface.lock()) {
std::cout << " face " << f->mv0->vertex << "," << f->mv1->vertex << "," << f->mv2->vertex << std::endl;
};
};
}
Face::Face(int _v0, int _v1, int _v2)
{
// ensure it is not degenerate
if ((_v0 == _v1) || (_v1 == _v2) || (_v0 == _v2))
throw std::runtime_error("Degenerate face.");
// order vertex indices
if ((_v0 < _v1) && (_v0 < _v2)) {
v0 = _v0;
v1 = _v1;
v2 = _v2;
} else if ((_v1 < _v0) && (_v1 < _v2)) {
v0 = _v1;
v1 = _v2;
v2 = _v0;
} else if ((_v2 < _v0) && (_v2 < _v1)) {
v0 = _v2;
v1 = _v0;
v2 = _v1;
} else {
throw std::runtime_error("Oops. Face construction bug!");
}
};
bool Face::operator<(const Face & otherface) const
{
if (v0 < otherface.v0) return true;
if (v0 > otherface.v0) return false;
if (v1 < otherface.v1) return true;
if (v1 > otherface.v1) return false;
if (v2 < otherface.v2) return true;
return false;
};
bool Face::operator==(const Face & otherface) const
{
return ((v0 == otherface.v0) && (v1 == otherface.v1) && (v2 == otherface.v2));
};
MFace::MFace()
: mv0(), mv1(), mv2(), score(-3 * VCACHE_PRECISION)
{
// nothing to do
};
void MFace::dump() const
{
std::cout << " face " << mv0->vertex << "," << mv1->vertex << "," << mv2->vertex << std::endl;
std::cout << " score " << score << std::endl;
}
MVertexPtr Mesh::add_vertex(MFacePtr mface, int vertex)
{
MVertexPtr mvertex;
// search for vertex in mesh
VertexMap::const_iterator vertex_iter = _vertices.find(vertex);
if (vertex_iter != _vertices.end()) {
// vertex already exists!
mvertex = vertex_iter->second;
} else {
// create vertex
mvertex = MVertexPtr(new MVertex(vertex));
_vertices[vertex] = mvertex;
};
// update list of faces that have this vertex
mvertex->mfaces.insert(mface);
return mvertex;
};
Mesh::Mesh() : _faces(), _vertices() {};
MFacePtr Mesh::add_face(int v0, int v1, int v2)
{
// create face index and search if face already exists in mesh
Face face(v0, v1, v2);
FaceMap::const_iterator face_iter = _faces.find(face);
if (face_iter != _faces.end()) {
// face already exists!
return face_iter->second;
} else {
// create face
MFacePtr mface(new MFace);
_faces[face] = mface;
// create vertices and update links between faces and vertices
mface->mv0 = add_vertex(mface, v0);
mface->mv1 = add_vertex(mface, v1);
mface->mv2 = add_vertex(mface, v2);
return mface;
};
}
void Mesh::dump() const
{
std::cout << _faces.size() << " faces" << std::endl;
BOOST_FOREACH(FaceMap::value_type face, _faces) {
face.second->dump();
};
std::cout << _vertices.size() << " vertices" << std::endl;
BOOST_FOREACH(VertexMap::value_type vertex, _vertices) {
vertex.second->dump();
};
}
void Mesh::update_score(VertexScore const & vertex_score)
{
// calculate score of all vertices
BOOST_FOREACH(VertexMap::value_type vertex, _vertices) {
MVertexPtr mvertex = vertex.second;
mvertex->score =
vertex_score.get(
mvertex->cache_position,
mvertex->mfaces.size());
};
// calculate score of all triangles
BOOST_FOREACH(FaceMap::value_type face, _faces) {
MFacePtr mface = face.second;
mface->score =
mface->mv0->score +
mface->mv1->score +
mface->mv2->score;
};
}
// helper function for get_cache_optimized_faces
MFacePtr get_best_face(std::set<MFacePtr> const & faces)
{
if (faces.empty()) {
// corner case: if faces is empty, then return a NULL pointer
return MFacePtr();
};
MFacePtr best_face = *(faces.begin());
BOOST_FOREACH(MFacePtr face, faces) {
if (best_face->score < face->score) {
best_face = face;
};
};
return best_face;
};
// helper function to insert faces from a vertex
void insert_faces(std::set<MFacePtr> & faces, MVertexPtr mvertex)
{
BOOST_FOREACH(boost::weak_ptr<MFace> const & face, mvertex->mfaces) {
if (MFacePtr mface = face.lock()) {
faces.insert(mface);
};
};
};
std::list<MFacePtr> Mesh::get_cache_optimized_faces(VertexScore const & vertex_score)
{
// result
std::list<MFacePtr> cache_optimized_faces;
// calculate score of all vertices
update_score(vertex_score);
// emulated cache
std::deque<MVertexPtr> cache;
// add face by face by maximal score, updating the score as we go along
// set of remaining faces
std::set<MFacePtr> remaining_faces;
BOOST_FOREACH(FaceMap::value_type & face, _faces) {
remaining_faces.insert(face.second);
};
// set of faces whose scores were updated in the previous run
std::set<MFacePtr> updated_faces;
// set of vertices whose scores were updated in the previous run
std::set<MVertexPtr> updated_vertices;
while (!remaining_faces.empty()) {
// find the best face, or a good approximation
MFacePtr best_face;
if (!updated_faces.empty()) {
// search only recently updated faces (very fast, and almost
// always globally optimal)
best_face = get_best_face(updated_faces);
} else {
// global search, slow but accurate (occurs rarely)
best_face = get_best_face(remaining_faces);
};
// mark as added
remaining_faces.erase(best_face);
// append to ordered list of triangles
cache_optimized_faces.push_back(best_face);
// clean lists of vertices and triangles whose score we will update
updated_vertices.clear();
updated_faces.clear();
// for each vertex in the just added triangle
MVertexPtr best_verts[] = {best_face->mv0, best_face->mv1, best_face->mv2};
BOOST_FOREACH(MVertexPtr mvertex, best_verts) {
// remove triangle from the triangle list of the vertex
mvertex->mfaces.erase(best_face);
// must update its score
updated_vertices.insert(mvertex);
insert_faces(updated_faces, mvertex);
};
// add each vertex to cache (score is updated later)
BOOST_FOREACH(MVertexPtr mvertex, best_verts) {
std::deque<MVertexPtr>::const_iterator it = std::find(cache.begin(), cache.end(), mvertex);
if (it == cache.end()) {
cache.push_front(mvertex);
if (cache.size() > VCACHE_CACHE_SIZE) {
// cache overflow!
// remove vertex from cache
MVertexPtr removed_mvertex = cache.back();
cache.pop_back();
// update its cache position
removed_mvertex->cache_position = -1;
// must update its score
updated_vertices.insert(removed_mvertex);
insert_faces(updated_faces, removed_mvertex);
}
};
};
// for each vertex in the cache (this includes those from the
// just added triangle)
int cache_pos = 0;
BOOST_FOREACH(MVertexPtr mvertex, cache) {
// update cache positions
mvertex->cache_position = cache_pos;
// must update its score
updated_vertices.insert(mvertex);
insert_faces(updated_faces, mvertex);
++cache_pos;
};
// update scores
BOOST_FOREACH(MVertexPtr mvertex, updated_vertices) {
mvertex->score =
vertex_score.get(
mvertex->cache_position,
mvertex->mfaces.size());
};
BOOST_FOREACH(MFacePtr mface, updated_faces) {
mface->score =
mface->mv0->score +
mface->mv1->score +
mface->mv2->score;
};
};
// return result
return cache_optimized_faces;
}
<|endoftext|> |
<commit_before>//===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-reg-info"
#include "Mips.h"
#include "MipsSubtarget.h"
#include "MipsRegisterInfo.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
const TargetInstrInfo &tii)
: MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const unsigned* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
// Mips callee-save register range is $16-$23, $f20-$f30
static const unsigned SingleFloatOnlyCalleeSavedRegs[] = {
Mips::F31, Mips::F30, Mips::F29, Mips::F28, Mips::F27, Mips::F26,
Mips::F25, Mips::F24, Mips::F23, Mips::F22, Mips::F21, Mips::F20,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
static const unsigned Mips32CalleeSavedRegs[] = {
Mips::D15, Mips::D14, Mips::D13, Mips::D12, Mips::D11, Mips::D10,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
static const unsigned N32CalleeSavedRegs[] = {
Mips::D31_64, Mips::D29_64, Mips::D27_64, Mips::D25_64, Mips::D23_64,
Mips::D21_64,
Mips::RA_64, Mips::FP_64, Mips::GP_64, Mips::S7_64, Mips::S6_64,
Mips::S5_64, Mips::S4_64, Mips::S3_64, Mips::S2_64, Mips::S1_64,
Mips::S0_64, 0
};
static const unsigned N64CalleeSavedRegs[] = {
Mips::D31_64, Mips::D30_64, Mips::D29_64, Mips::D28_64, Mips::D27_64,
Mips::D26_64, Mips::D25_64, Mips::D24_64,
Mips::RA_64, Mips::FP_64, Mips::GP_64, Mips::S7_64, Mips::S6_64,
Mips::S5_64, Mips::S4_64, Mips::S3_64, Mips::S2_64, Mips::S1_64,
Mips::S0_64, 0
};
if (Subtarget.isSingleFloat())
return SingleFloatOnlyCalleeSavedRegs;
else if (!Subtarget.hasMips64())
return Mips32CalleeSavedRegs;
else if (Subtarget.isABI_N32())
return N32CalleeSavedRegs;
assert(Subtarget.isABI_N64());
return N64CalleeSavedRegs;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
static const unsigned ReservedCPURegs[] = {
Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
Mips::GP, Mips::SP, Mips::FP, Mips::RA
};
static const unsigned ReservedCPU64Regs[] = {
Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
Mips::GP_64, Mips::SP_64, Mips::FP_64, Mips::RA_64
};
BitVector Reserved(getNumRegs());
typedef TargetRegisterClass::iterator RegIter;
for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
Reserved.set(ReservedCPURegs[I]);
if (Subtarget.hasMips64()) {
for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
Reserved.set(ReservedCPU64Regs[I]);
// Reserve all registers in AFGR64.
for (RegIter Reg = Mips::AFGR64RegisterClass->begin();
Reg != Mips::AFGR64RegisterClass->end(); ++Reg)
Reserved.set(*Reg);
}
else {
// Reserve all registers in CPU64Regs & FGR64.
for (RegIter Reg = Mips::CPU64RegsRegisterClass->begin();
Reg != Mips::CPU64RegsRegisterClass->end(); ++Reg)
Reserved.set(*Reg);
for (RegIter Reg = Mips::FGR64RegisterClass->begin();
Reg != Mips::FGR64RegisterClass->end(); ++Reg)
Reserved.set(*Reg);
}
return Reserved;
}
// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
// Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
MBB.erase(I);
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
MachineFrameInfo *MFI = MF.getFrameInfo();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(i).getIndex();
int stackSize = MF.getFrameInfo()->getStackSize();
int spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
int MinCSFI = 0;
int MaxCSFI = -1;
if (CSI.size()) {
MinCSFI = CSI[0].getFrameIdx();
MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
}
// The following stack frame objects are always referenced relative to $sp:
// 1. Outgoing arguments.
// 2. Pointer to dynamically allocated stack space.
// 3. Locations for callee-saved registers.
// Everything else is referenced relative to whatever register
// getFrameRegister() returns.
unsigned FrameReg;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
(FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
FrameReg = Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
else
FrameReg = getFrameRegister(MF);
// Calculate final offset.
// - There is no need to change the offset if the frame object is one of the
// following: an outgoing argument, pointer to a dynamically allocated
// stack space or a $gp restore location,
// - If the frame object is any of the following, its offset must be adjusted
// by adding the size of the stack:
// incoming argument, callee-saved register location or local variable.
int Offset;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
MipsFI->isDynAllocFI(FrameIndex))
Offset = spOffset;
else
Offset = spOffset + stackSize;
Offset += MI.getOperand(i+1).getImm();
DEBUG(errs() << "Offset : " << Offset << "\n" << "<--------->\n");
// If MI is not a debug value, make sure Offset fits in the 16-bit immediate
// field.
if (!MI.isDebugValue() && (Offset >= 0x8000 || Offset < -0x8000)) {
MachineBasicBlock &MBB = *MI.getParent();
DebugLoc DL = II->getDebugLoc();
int ImmHi = (((unsigned)Offset & 0xffff0000) >> 16) +
((Offset & 0x8000) != 0);
// FIXME: change this when mips goes MC".
BuildMI(MBB, II, DL, TII.get(Mips::NOAT));
BuildMI(MBB, II, DL, TII.get(Mips::LUi), Mips::AT).addImm(ImmHi);
BuildMI(MBB, II, DL, TII.get(Mips::ADDu), Mips::AT).addReg(FrameReg)
.addReg(Mips::AT);
FrameReg = Mips::AT;
Offset = (short)(Offset & 0xffff);
BuildMI(MBB, ++II, MI.getDebugLoc(), TII.get(Mips::ATMACRO));
}
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(Offset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
bool IsN64 = Subtarget.isABI_N64();
return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
(IsN64 ? Mips::SP_64 : Mips::SP);
}
unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
}
unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
}
<commit_msg>Modify MipsRegisterInfo::eliminateFrameIndex to use MipsAnalyzeImmediate to expand offsets that do not fit in the 16-bit immediate field of load and store instructions. Also change the types of variables so that they are sufficiently large to handle 64-bit pointers.<commit_after>//===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-reg-info"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsSubtarget.h"
#include "MipsRegisterInfo.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
const TargetInstrInfo &tii)
: MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const unsigned* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
// Mips callee-save register range is $16-$23, $f20-$f30
static const unsigned SingleFloatOnlyCalleeSavedRegs[] = {
Mips::F31, Mips::F30, Mips::F29, Mips::F28, Mips::F27, Mips::F26,
Mips::F25, Mips::F24, Mips::F23, Mips::F22, Mips::F21, Mips::F20,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
static const unsigned Mips32CalleeSavedRegs[] = {
Mips::D15, Mips::D14, Mips::D13, Mips::D12, Mips::D11, Mips::D10,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
static const unsigned N32CalleeSavedRegs[] = {
Mips::D31_64, Mips::D29_64, Mips::D27_64, Mips::D25_64, Mips::D23_64,
Mips::D21_64,
Mips::RA_64, Mips::FP_64, Mips::GP_64, Mips::S7_64, Mips::S6_64,
Mips::S5_64, Mips::S4_64, Mips::S3_64, Mips::S2_64, Mips::S1_64,
Mips::S0_64, 0
};
static const unsigned N64CalleeSavedRegs[] = {
Mips::D31_64, Mips::D30_64, Mips::D29_64, Mips::D28_64, Mips::D27_64,
Mips::D26_64, Mips::D25_64, Mips::D24_64,
Mips::RA_64, Mips::FP_64, Mips::GP_64, Mips::S7_64, Mips::S6_64,
Mips::S5_64, Mips::S4_64, Mips::S3_64, Mips::S2_64, Mips::S1_64,
Mips::S0_64, 0
};
if (Subtarget.isSingleFloat())
return SingleFloatOnlyCalleeSavedRegs;
else if (!Subtarget.hasMips64())
return Mips32CalleeSavedRegs;
else if (Subtarget.isABI_N32())
return N32CalleeSavedRegs;
assert(Subtarget.isABI_N64());
return N64CalleeSavedRegs;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
static const unsigned ReservedCPURegs[] = {
Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
Mips::GP, Mips::SP, Mips::FP, Mips::RA
};
static const unsigned ReservedCPU64Regs[] = {
Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
Mips::GP_64, Mips::SP_64, Mips::FP_64, Mips::RA_64
};
BitVector Reserved(getNumRegs());
typedef TargetRegisterClass::iterator RegIter;
for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
Reserved.set(ReservedCPURegs[I]);
if (Subtarget.hasMips64()) {
for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
Reserved.set(ReservedCPU64Regs[I]);
// Reserve all registers in AFGR64.
for (RegIter Reg = Mips::AFGR64RegisterClass->begin();
Reg != Mips::AFGR64RegisterClass->end(); ++Reg)
Reserved.set(*Reg);
}
else {
// Reserve all registers in CPU64Regs & FGR64.
for (RegIter Reg = Mips::CPU64RegsRegisterClass->begin();
Reg != Mips::CPU64RegsRegisterClass->end(); ++Reg)
Reserved.set(*Reg);
for (RegIter Reg = Mips::FGR64RegisterClass->begin();
Reg != Mips::FGR64RegisterClass->end(); ++Reg)
Reserved.set(*Reg);
}
return Reserved;
}
// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
// Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
MBB.erase(I);
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
MachineFrameInfo *MFI = MF.getFrameInfo();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(i).getIndex();
uint64_t stackSize = MF.getFrameInfo()->getStackSize();
int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
int MinCSFI = 0;
int MaxCSFI = -1;
if (CSI.size()) {
MinCSFI = CSI[0].getFrameIdx();
MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
}
// The following stack frame objects are always referenced relative to $sp:
// 1. Outgoing arguments.
// 2. Pointer to dynamically allocated stack space.
// 3. Locations for callee-saved registers.
// Everything else is referenced relative to whatever register
// getFrameRegister() returns.
unsigned FrameReg;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
(FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
FrameReg = Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
else
FrameReg = getFrameRegister(MF);
// Calculate final offset.
// - There is no need to change the offset if the frame object is one of the
// following: an outgoing argument, pointer to a dynamically allocated
// stack space or a $gp restore location,
// - If the frame object is any of the following, its offset must be adjusted
// by adding the size of the stack:
// incoming argument, callee-saved register location or local variable.
int64_t Offset;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
MipsFI->isDynAllocFI(FrameIndex))
Offset = spOffset;
else
Offset = spOffset + (int64_t)stackSize;
Offset += MI.getOperand(i+1).getImm();
DEBUG(errs() << "Offset : " << Offset << "\n" << "<--------->\n");
// If MI is not a debug value, make sure Offset fits in the 16-bit immediate
// field.
if (!MI.isDebugValue() && !isInt<16>(Offset)) {
MachineBasicBlock &MBB = *MI.getParent();
DebugLoc DL = II->getDebugLoc();
MipsAnalyzeImmediate AnalyzeImm;
unsigned Size = Subtarget.isABI_N64() ? 64 : 32;
unsigned LUi = Subtarget.isABI_N64() ? Mips::LUi64 : Mips::LUi;
unsigned ADDu = Subtarget.isABI_N64() ? Mips::DADDu : Mips::ADDu;
unsigned ZEROReg = Subtarget.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
unsigned ATReg = Subtarget.isABI_N64() ? Mips::AT_64 : Mips::AT;
const MipsAnalyzeImmediate::InstSeq &Seq =
AnalyzeImm.Analyze(Offset, Size, true /* LastInstrIsADDiu */);
MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
// FIXME: change this when mips goes MC".
BuildMI(MBB, II, DL, TII.get(Mips::NOAT));
// The first instruction can be a LUi, which is different from other
// instructions (ADDiu, ORI and SLL) in that it does not have a register
// operand.
if (Inst->Opc == LUi)
BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
.addImm(SignExtend64<16>(Inst->ImmOpnd));
else
BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
.addImm(SignExtend64<16>(Inst->ImmOpnd));
// Build the remaining instructions in Seq except for the last one.
for (++Inst; Inst != Seq.end() - 1; ++Inst)
BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
.addImm(SignExtend64<16>(Inst->ImmOpnd));
BuildMI(MBB, II, DL, TII.get(ADDu), ATReg).addReg(FrameReg).addReg(ATReg);
FrameReg = ATReg;
Offset = SignExtend64<16>(Inst->ImmOpnd);
BuildMI(MBB, ++II, MI.getDebugLoc(), TII.get(Mips::ATMACRO));
}
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(Offset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
bool IsN64 = Subtarget.isABI_N64();
return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
(IsN64 ? Mips::SP_64 : Mips::SP);
}
unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
}
unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/socket_io.hpp" // print_endpoint
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::multimap<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << print_endpoint(c.socket().remote_endpoint(ec))
<< std::endl;
// this is not necessarily true when using a proxy and proxying hostnames
// TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
TORRENT_ASSERT(size == 0 || parser.finished());
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, 1024*1024, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings ps, int port)
{
if (ps.type != proxy_settings::none)
{
ps.port = start_proxy(ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
printf("\n\n********************** using %s proxy **********************\n"
, test_name[ps.type]);
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
char url[256];
snprintf(url, sizeof(url), "%s://127.0.0.1:%d/", protocol.c_str(), port);
std::string url_base(url);
run_test(url_base + "relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(url_base + "test_file", 3216, 200, 1, error_code(), ps);
run_test(url_base + "test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(url_base + "non-existing-file", -1, 404, 1, err(), ps);
// only run the tests to handle NX_DOMAIN if we have a proper internet
// connection that doesn't inject false DNS responses (like Comcast does)
hostent* h = gethostbyname("non-existent-domain.se");
if (h == 0 && h_errno == HOST_NOT_FOUND)
{
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
}
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
error_code ec;
file test_file("test_file", file::write_only, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
file::iovec_t b = { data_buffer, 3216};
test_file.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
int port = 0;
port = start_web_server();
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps, port);
}
stop_web_server();
#ifdef TORRENT_USE_OPENSSL
port = start_web_server(true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps, port);
}
stop_web_server();
#endif
// test chunked encoding
port = start_web_server(false, true);
ps.type = proxy_settings::none;
run_suite("http", ps, port);
stop_web_server();
std::remove("test_file");
return 0;
}
<commit_msg>debug output for test_http_connection<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/socket_io.hpp" // print_endpoint
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::multimap<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << print_endpoint(c.socket().remote_endpoint(ec))
<< std::endl;
// this is not necessarily true when using a proxy and proxying hostnames
// TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
TORRENT_ASSERT(size == 0 || parser.finished());
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, 1024*1024, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings ps, int port)
{
if (ps.type != proxy_settings::none)
{
ps.port = start_proxy(ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
printf("\n\n********************** using %s proxy **********************\n"
, test_name[ps.type]);
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
char url[256];
snprintf(url, sizeof(url), "%s://127.0.0.1:%d/", protocol.c_str(), port);
std::string url_base(url);
run_test(url_base + "relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(url_base + "test_file", 3216, 200, 1, error_code(), ps);
run_test(url_base + "test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(url_base + "non-existing-file", -1, 404, 1, err(), ps);
// only run the tests to handle NX_DOMAIN if we have a proper internet
// connection that doesn't inject false DNS responses (like Comcast does)
hostent* h = gethostbyname("non-existent-domain.se");
printf("gethostbyname(\"non-existent-domain.se\") = %p. h_errno = %d\n", h, h_errno);
if (h == 0 && h_errno == HOST_NOT_FOUND)
{
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
}
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
error_code ec;
file test_file("test_file", file::write_only, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
file::iovec_t b = { data_buffer, 3216};
test_file.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
int port = 0;
port = start_web_server();
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps, port);
}
stop_web_server();
#ifdef TORRENT_USE_OPENSSL
port = start_web_server(true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps, port);
}
stop_web_server();
#endif
// test chunked encoding
port = start_web_server(false, true);
ps.type = proxy_settings::none;
run_suite("http", ps, port);
stop_web_server();
std::remove("test_file");
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Constant magnetic field class
// Used by AliRun class
// Author:
//-------------------------------------------------------------------------
#include <stdlib.h>
#include "AliMagFC.h"
ClassImp(AliMagFC)
//________________________________________
AliMagFC::AliMagFC(const char *name, const char *title, const Int_t integ,
const Float_t factor, const Float_t fmax)
: AliMagF(name,title,integ,factor,fmax)
{
//
// Standard constructor
//
fType = kConst;
fMap = 1;
printf("Constant Field %s created: map= %d, factor= %f\n",fName.Data(),fMap,
factor);
}
//________________________________________
void AliMagFC::Field(Float_t *x, Float_t *b)
{
//
// Method to return the field in a point
//
b[0]=b[1]=b[2]=0;
if(fMap==1) {
if(TMath::Abs(x[2])<700 && x[0]*x[0]+(x[1]+30)*(x[1]+30) < 560*560) {
b[2]=2;
} else {
if ( -725 >= x[2] && x[2] >= -1225 ) {
Float_t dz = TMath::Abs(-975-x[2])*0.01;
b[0] = - (1-0.1*dz*dz)*7;
}
else {
ZDCField(x, b);
}
}
if(fFactor!=1) {
b[0]*=fFactor;
b[1]*=fFactor;
b[2]*=fFactor;
}
} else {
printf("Invalid field map for constant field %d\n",fMap);
exit(1);
}
}
void AliMagFC::ZDCField(Float_t *x, Float_t *b)
{
//This is the ZDC part
Float_t rad2=x[0]*x[0]+x[1]*x[1];
if(x[2] < kCORBEG2 && x[2] > kCOREND2){
if(rad2<kCOR2RA2){
b[0] = - kFCORN2;
}
}
else if(x[2] < kZ1BEG && x[2] > kZ1END){
if(rad2<kZ1RA2){
b[0] = kG1*x[1];
b[1] = -kG1*x[0];
}
}
else if(x[2] < kZ2BEG && x[2] > kZ2END){
if(rad2<kZ2RA2){
b[0] = -kG1*x[1];
b[1] = kG1*x[0];
}
}
else if(x[2] < kZ3BEG && x[2] > kZ3END){
if(rad2<kZ3RA2){
b[0] = -kG1*x[1];
b[1] = kG1*x[0];
}
}
else if(x[2] < kZ4BEG && x[2] > kZ4END){
if(rad2<kZ4RA2){
b[0] = kG1*x[1];
b[1] = -kG1*x[0];
}
}
else if(x[2] < kD1BEG && x[2] > kD1END){
if(rad2<kD1RA2){
b[1] = -kFDIP;
}
}
else if(x[2] < kD2BEG && x[2] > kD2END){
if(((x[0]-kXCEN1D2)*(x[0]-kXCEN1D2)+(x[1]-kYCEN1D2)*(x[1]-kYCEN1D2))<kD2RA2
|| ((x[0]-kXCEN2D2)*(x[0]-kXCEN2D2)+(x[1]-kYCEN2D2)*(x[1]-kYCEN2D2))<kD2RA2){
b[1] = kFDIP;
}
}
}
<commit_msg>Remove message from constructor.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Constant magnetic field class
// Used by AliRun class
// Author:
//-------------------------------------------------------------------------
#include <stdlib.h>
#include "AliMagFC.h"
ClassImp(AliMagFC)
//________________________________________
AliMagFC::AliMagFC(const char *name, const char *title, const Int_t integ,
const Float_t factor, const Float_t fmax)
: AliMagF(name,title,integ,factor,fmax)
{
//
// Standard constructor
//
fType = kConst;
fMap = 1;
}
//________________________________________
void AliMagFC::Field(Float_t *x, Float_t *b)
{
//
// Method to return the field in a point
//
b[0]=b[1]=b[2]=0;
if(fMap==1) {
if(TMath::Abs(x[2])<700 && x[0]*x[0]+(x[1]+30)*(x[1]+30) < 560*560) {
b[2]=2;
} else {
if ( -725 >= x[2] && x[2] >= -1225 ) {
Float_t dz = TMath::Abs(-975-x[2])*0.01;
b[0] = - (1-0.1*dz*dz)*7;
}
else {
ZDCField(x, b);
}
}
if(fFactor!=1) {
b[0]*=fFactor;
b[1]*=fFactor;
b[2]*=fFactor;
}
} else {
printf("Invalid field map for constant field %d\n",fMap);
exit(1);
}
}
void AliMagFC::ZDCField(Float_t *x, Float_t *b)
{
//This is the ZDC part
Float_t rad2=x[0]*x[0]+x[1]*x[1];
if(x[2] < kCORBEG2 && x[2] > kCOREND2){
if(rad2<kCOR2RA2){
b[0] = - kFCORN2;
}
}
else if(x[2] < kZ1BEG && x[2] > kZ1END){
if(rad2<kZ1RA2){
b[0] = kG1*x[1];
b[1] = -kG1*x[0];
}
}
else if(x[2] < kZ2BEG && x[2] > kZ2END){
if(rad2<kZ2RA2){
b[0] = -kG1*x[1];
b[1] = kG1*x[0];
}
}
else if(x[2] < kZ3BEG && x[2] > kZ3END){
if(rad2<kZ3RA2){
b[0] = -kG1*x[1];
b[1] = kG1*x[0];
}
}
else if(x[2] < kZ4BEG && x[2] > kZ4END){
if(rad2<kZ4RA2){
b[0] = kG1*x[1];
b[1] = -kG1*x[0];
}
}
else if(x[2] < kD1BEG && x[2] > kD1END){
if(rad2<kD1RA2){
b[1] = -kFDIP;
}
}
else if(x[2] < kD2BEG && x[2] > kD2END){
if(((x[0]-kXCEN1D2)*(x[0]-kXCEN1D2)+(x[1]-kYCEN1D2)*(x[1]-kYCEN1D2))<kD2RA2
|| ((x[0]-kXCEN2D2)*(x[0]-kXCEN2D2)+(x[1]-kYCEN2D2)*(x[1]-kYCEN2D2))<kD2RA2){
b[1] = kFDIP;
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/socket_io.hpp" // print_endpoint
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::multimap<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << print_endpoint(c.socket().remote_endpoint(ec))
<< std::endl;
// this is not necessarily true when using a proxy and proxying hostnames
// TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
TORRENT_ASSERT(size == 0 || parser.finished());
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, 1024*1024, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings ps, int port)
{
if (ps.type != proxy_settings::none)
{
ps.port = start_proxy(ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
printf("\n\n********************** using %s proxy **********************\n"
, test_name[ps.type]);
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
char url[256];
snprintf(url, sizeof(url), "%s://127.0.0.1:%d/", protocol.c_str(), port);
std::string url_base(url);
run_test(url_base + "relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(url_base + "test_file", 3216, 200, 1, error_code(), ps);
run_test(url_base + "test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(url_base + "non-existing-file", -1, 404, 1, err(), ps);
// only run the tests to handle NX_DOMAIN if we have a proper internet
// connection that doesn't inject false DNS responses (like Comcast does)
hostent* h = gethostbyname("non-existent-domain.se");
if (h == 0 && h_errno == HOST_NOT_FOUND)
{
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
}
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
error_code ec;
file test_file("test_file", file::write_only, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
file::iovec_t b = { data_buffer, 3216};
test_file.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
int port = 0;
port = start_web_server();
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps, port);
}
stop_web_server();
#ifdef TORRENT_USE_OPENSSL
port = start_web_server(true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps, port);
}
stop_web_server();
#endif
// test chunked encoding
port = start_web_server(false, true);
ps.type = proxy_settings::none;
run_suite("http", ps, port);
stop_web_server();
std::remove("test_file");
return 0;
}
<commit_msg>debug output for test_http_connection<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/socket_io.hpp" // print_endpoint
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::multimap<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << print_endpoint(c.socket().remote_endpoint(ec))
<< std::endl;
// this is not necessarily true when using a proxy and proxying hostnames
// TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
TORRENT_ASSERT(size == 0 || parser.finished());
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, 1024*1024, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings ps, int port)
{
if (ps.type != proxy_settings::none)
{
ps.port = start_proxy(ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
printf("\n\n********************** using %s proxy **********************\n"
, test_name[ps.type]);
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
char url[256];
snprintf(url, sizeof(url), "%s://127.0.0.1:%d/", protocol.c_str(), port);
std::string url_base(url);
run_test(url_base + "relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "redirect", 3216, 200, 2, error_code(), ps);
run_test(url_base + "infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(url_base + "test_file", 3216, 200, 1, error_code(), ps);
run_test(url_base + "test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(url_base + "non-existing-file", -1, 404, 1, err(), ps);
// only run the tests to handle NX_DOMAIN if we have a proper internet
// connection that doesn't inject false DNS responses (like Comcast does)
hostent* h = gethostbyname("non-existent-domain.se");
printf("gethostbyname(\"non-existent-domain.se\") = %p. h_errno = %d\n", h, h_errno);
if (h == 0 && h_errno == HOST_NOT_FOUND)
{
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
}
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
error_code ec;
file test_file("test_file", file::write_only, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
file::iovec_t b = { data_buffer, 3216};
test_file.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
int port = 0;
port = start_web_server();
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps, port);
}
stop_web_server();
#ifdef TORRENT_USE_OPENSSL
port = start_web_server(true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps, port);
}
stop_web_server();
#endif
// test chunked encoding
port = start_web_server(false, true);
ps.type = proxy_settings::none;
run_suite("http", ps, port);
stop_web_server();
std::remove("test_file");
return 0;
}
<|endoftext|> |
<commit_before>#include "amatrix.h"
#include "checks.h"
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixIteratorAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
for (auto i = a_matrix.begin(); i != a_matrix.end(); i++)
*i = 2.33 * (++memberwise_coeficient);
memberwise_coeficient = 0.00;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
double value = 2.33 * (++memberwise_coeficient);
AMATRIX_CHECK_EQUAL(a_matrix(i, j), value);
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixIteratorForwardBackward() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
auto i_value = a_matrix.begin();
for (; i_value != a_matrix.end(); i_value++)
*i_value = 2.33 * (++memberwise_coeficient);
for (int i = a_matrix.size1() - 1; i >= 0; i--)
for (int j = a_matrix.size2() - 1; j >= 0; j--) {
i_value--;
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *i_value);
}
for (; i_value != a_matrix.end(); ++i_value)
*i_value = 1.34 * (++memberwise_coeficient);
for (int i = a_matrix.size1() - 1; i >= 0; i--)
for (int j = a_matrix.size2() - 1; j >= 0; j--) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *(--i_value));
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixIteratorArithmetic() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
auto i_value = a_matrix.begin();
for (; i_value != a_matrix.end(); i_value++)
*i_value = (++memberwise_coeficient);
// test -= and +=
i_value -= a_matrix.size();
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *i_value);
i_value += 1;
}
for (int i = a_matrix.size1() - 1; i >= 0; i--)
for (int j = a_matrix.size2() - 1; j >= 0; j--) {
i_value -= 1;
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *i_value);
}
// test it + n operator
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
*(a_matrix.begin() + (i * a_matrix.size2() + j)));
}
// test n + it operator
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
*((i * a_matrix.size2() + j) + a_matrix.begin()));
}
// test it - n operator
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
*(a_matrix.end() -
(a_matrix.size() - i * a_matrix.size2() - j)));
}
// test it1 - it2 operator
AMATRIX_CHECK_EQUAL(a_matrix.size(), a_matrix.end() - a_matrix.begin());
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixForEachIteratorAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
for (auto& value : a_matrix)
value = 2.33 * (++memberwise_coeficient);
memberwise_coeficient = 0.00;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
double value = 2.33 * (++memberwise_coeficient);
AMATRIX_CHECK_EQUAL(a_matrix(i, j), value);
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixInequality() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix(AMatrix::ZeroMatrix<double>(TSize1, TSize2));
for(auto i = a_matrix.begin() ; i != a_matrix.end() ; i++){
AMATRIX_CHECK(i >= a_matrix.begin());
AMATRIX_CHECK(i <= a_matrix.end());
}
for(auto i = a_matrix.begin() + 1 ; i != a_matrix.end() ; i++){
AMATRIX_CHECK(i > a_matrix.begin());
}
for(auto i = a_matrix.begin() ; i != a_matrix.end() - 1 ; i++){
AMATRIX_CHECK(i < a_matrix.end());
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixConstIterator() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
for (auto& value : a_matrix)
value = 2.33 * (++memberwise_coeficient);
memberwise_coeficient = 0.00;
AMatrix::Matrix<double, TSize1, TSize2>::const_iterator i_const = a_matrix.begin();
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
double value = 2.33 * (++memberwise_coeficient);
AMATRIX_CHECK_EQUAL(*(i_const++), value);
}
return 0; // not failed
}
int main() {
std::size_t number_of_failed_tests = 0;
number_of_failed_tests += TestMatrixIteratorAssign<1, 1>();
number_of_failed_tests += TestMatrixIteratorAssign<1, 2>();
number_of_failed_tests += TestMatrixIteratorAssign<2, 1>();
number_of_failed_tests += TestMatrixIteratorAssign<2, 2>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 1>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 2>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixIteratorAssign<1, 3>();
number_of_failed_tests += TestMatrixIteratorAssign<2, 3>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<1, 1>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<1, 2>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<2, 1>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<2, 2>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 1>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 2>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<1, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<2, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<1, 1>();
number_of_failed_tests += TestMatrixIteratorArithmetic<1, 2>();
number_of_failed_tests += TestMatrixIteratorArithmetic<2, 1>();
number_of_failed_tests += TestMatrixIteratorArithmetic<2, 2>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 1>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 2>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<1, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<2, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<1, 1>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<1, 2>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<2, 1>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<2, 2>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 1>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 2>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<1, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<2, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixInequality<1, 1>();
number_of_failed_tests += TestMatrixInequality<1, 2>();
number_of_failed_tests += TestMatrixInequality<2, 1>();
number_of_failed_tests += TestMatrixInequality<2, 2>();
number_of_failed_tests += TestMatrixInequality<3, 1>();
number_of_failed_tests += TestMatrixInequality<3, 2>();
number_of_failed_tests += TestMatrixInequality<3, 3>();
number_of_failed_tests += TestMatrixInequality<1, 3>();
number_of_failed_tests += TestMatrixInequality<2, 3>();
number_of_failed_tests += TestMatrixInequality<3, 3>();
number_of_failed_tests += TestMatrixConstIterator<1, 1>();
number_of_failed_tests += TestMatrixConstIterator<1, 2>();
number_of_failed_tests += TestMatrixConstIterator<2, 1>();
number_of_failed_tests += TestMatrixConstIterator<2, 2>();
number_of_failed_tests += TestMatrixConstIterator<3, 1>();
number_of_failed_tests += TestMatrixConstIterator<3, 2>();
number_of_failed_tests += TestMatrixConstIterator<3, 3>();
number_of_failed_tests += TestMatrixConstIterator<1, 3>();
number_of_failed_tests += TestMatrixConstIterator<2, 3>();
number_of_failed_tests += TestMatrixConstIterator<3, 3>();
std::cout << number_of_failed_tests << "tests failed" << std::endl;
return number_of_failed_tests;
}
<commit_msg>Fixing compiler error due to missing typename<commit_after>#include "amatrix.h"
#include "checks.h"
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixIteratorAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
for (auto i = a_matrix.begin(); i != a_matrix.end(); i++)
*i = 2.33 * (++memberwise_coeficient);
memberwise_coeficient = 0.00;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
double value = 2.33 * (++memberwise_coeficient);
AMATRIX_CHECK_EQUAL(a_matrix(i, j), value);
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixIteratorForwardBackward() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
auto i_value = a_matrix.begin();
for (; i_value != a_matrix.end(); i_value++)
*i_value = 2.33 * (++memberwise_coeficient);
for (int i = a_matrix.size1() - 1; i >= 0; i--)
for (int j = a_matrix.size2() - 1; j >= 0; j--) {
i_value--;
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *i_value);
}
for (; i_value != a_matrix.end(); ++i_value)
*i_value = 1.34 * (++memberwise_coeficient);
for (int i = a_matrix.size1() - 1; i >= 0; i--)
for (int j = a_matrix.size2() - 1; j >= 0; j--) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *(--i_value));
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixIteratorArithmetic() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
auto i_value = a_matrix.begin();
for (; i_value != a_matrix.end(); i_value++)
*i_value = (++memberwise_coeficient);
// test -= and +=
i_value -= a_matrix.size();
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *i_value);
i_value += 1;
}
for (int i = a_matrix.size1() - 1; i >= 0; i--)
for (int j = a_matrix.size2() - 1; j >= 0; j--) {
i_value -= 1;
AMATRIX_CHECK_EQUAL(a_matrix(i, j), *i_value);
}
// test it + n operator
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
*(a_matrix.begin() + (i * a_matrix.size2() + j)));
}
// test n + it operator
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
*((i * a_matrix.size2() + j) + a_matrix.begin()));
}
// test it - n operator
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
*(a_matrix.end() -
(a_matrix.size() - i * a_matrix.size2() - j)));
}
// test it1 - it2 operator
AMATRIX_CHECK_EQUAL(a_matrix.size(), a_matrix.end() - a_matrix.begin());
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixForEachIteratorAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
for (auto& value : a_matrix)
value = 2.33 * (++memberwise_coeficient);
memberwise_coeficient = 0.00;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
double value = 2.33 * (++memberwise_coeficient);
AMATRIX_CHECK_EQUAL(a_matrix(i, j), value);
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixInequality() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix(AMatrix::ZeroMatrix<double>(TSize1, TSize2));
for(auto i = a_matrix.begin() ; i != a_matrix.end() ; i++){
AMATRIX_CHECK(i >= a_matrix.begin());
AMATRIX_CHECK(i <= a_matrix.end());
}
for(auto i = a_matrix.begin() + 1 ; i != a_matrix.end() ; i++){
AMATRIX_CHECK(i > a_matrix.begin());
}
for(auto i = a_matrix.begin() ; i != a_matrix.end() - 1 ; i++){
AMATRIX_CHECK(i < a_matrix.end());
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixConstIterator() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
double memberwise_coeficient = 0.00;
for (auto& value : a_matrix)
value = 2.33 * (++memberwise_coeficient);
memberwise_coeficient = 0.00;
typename AMatrix::Matrix<double, TSize1, TSize2>::const_iterator i_const = a_matrix.begin();
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++) {
double value = 2.33 * (++memberwise_coeficient);
AMATRIX_CHECK_EQUAL(*(i_const++), value);
}
return 0; // not failed
}
int main() {
std::size_t number_of_failed_tests = 0;
number_of_failed_tests += TestMatrixIteratorAssign<1, 1>();
number_of_failed_tests += TestMatrixIteratorAssign<1, 2>();
number_of_failed_tests += TestMatrixIteratorAssign<2, 1>();
number_of_failed_tests += TestMatrixIteratorAssign<2, 2>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 1>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 2>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixIteratorAssign<1, 3>();
number_of_failed_tests += TestMatrixIteratorAssign<2, 3>();
number_of_failed_tests += TestMatrixIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<1, 1>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<1, 2>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<2, 1>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<2, 2>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 1>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 2>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<1, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<2, 3>();
number_of_failed_tests += TestMatrixIteratorForwardBackward<3, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<1, 1>();
number_of_failed_tests += TestMatrixIteratorArithmetic<1, 2>();
number_of_failed_tests += TestMatrixIteratorArithmetic<2, 1>();
number_of_failed_tests += TestMatrixIteratorArithmetic<2, 2>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 1>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 2>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<1, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<2, 3>();
number_of_failed_tests += TestMatrixIteratorArithmetic<3, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<1, 1>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<1, 2>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<2, 1>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<2, 2>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 1>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 2>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<1, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<2, 3>();
number_of_failed_tests += TestMatrixForEachIteratorAssign<3, 3>();
number_of_failed_tests += TestMatrixInequality<1, 1>();
number_of_failed_tests += TestMatrixInequality<1, 2>();
number_of_failed_tests += TestMatrixInequality<2, 1>();
number_of_failed_tests += TestMatrixInequality<2, 2>();
number_of_failed_tests += TestMatrixInequality<3, 1>();
number_of_failed_tests += TestMatrixInequality<3, 2>();
number_of_failed_tests += TestMatrixInequality<3, 3>();
number_of_failed_tests += TestMatrixInequality<1, 3>();
number_of_failed_tests += TestMatrixInequality<2, 3>();
number_of_failed_tests += TestMatrixInequality<3, 3>();
number_of_failed_tests += TestMatrixConstIterator<1, 1>();
number_of_failed_tests += TestMatrixConstIterator<1, 2>();
number_of_failed_tests += TestMatrixConstIterator<2, 1>();
number_of_failed_tests += TestMatrixConstIterator<2, 2>();
number_of_failed_tests += TestMatrixConstIterator<3, 1>();
number_of_failed_tests += TestMatrixConstIterator<3, 2>();
number_of_failed_tests += TestMatrixConstIterator<3, 3>();
number_of_failed_tests += TestMatrixConstIterator<1, 3>();
number_of_failed_tests += TestMatrixConstIterator<2, 3>();
number_of_failed_tests += TestMatrixConstIterator<3, 3>();
std::cout << number_of_failed_tests << "tests failed" << std::endl;
return number_of_failed_tests;
}
<|endoftext|> |
<commit_before>//
// IndexBox.h
// InternetMap
//
// Created by Alexander on 11.12.12.
// Copyright (c) 2012 Peer1. All rights reserved.
//
#ifndef InternetMap_IndexBox_hpp
#define InternetMap_IndexBox_hpp
#include "Types.hpp"
#include <set>
static const float IndexBoxMinX = -8;
static const float IndexBoxMaxX = 8;
static const float IndexBoxMinY = -2;
static const float IndexBoxMaxY = 2;
static const float IndexBoxMinZ = -2;
static const float IndexBoxMaxZ = 2;
static const float lengthX = -IndexBoxMinX + IndexBoxMaxX;
static const float lengthY = -IndexBoxMinY + IndexBoxMaxY;
static const float lengthZ = -IndexBoxMinZ + IndexBoxMaxZ;
static const int numberOfCellsX = 32;
static const int numberOfCellsY = 4;
static const int numberOfCellsZ = 4;
static const float boxSizeXWithoutOverlap = lengthX/numberOfCellsX;
static const float boxSizeYWithoutOverlap = lengthY/numberOfCellsY;
static const float boxSizeZWithoutOverlap = lengthZ/numberOfCellsZ;
class IndexBox {
Point3 _parameters[2];
Point3 _center;
Point3 _minCorner;
Point3 _maxCorner;
public:
std::set<int> indices;
bool isPointInside(const Point3& point);
bool doesLineIntersectOptimized(const Vector3& origin, const Vector3& invertedDirection, int* sign);
Point3 minCorner();
Point3 maxCorner();
Point3 center();
void setMinCorner(const Point3& minCorner);
void setMaxCorner(const Point3& maxCorner);
void setCenter(const Point3& center);
};
typedef shared_ptr<IndexBox> IndexBoxPointer;
#endif
<commit_msg>Puff out the index boxes a little. Some of the timeline data is right on the edge of the old bounds, which causes problems.<commit_after>//
// IndexBox.h
// InternetMap
//
// Created by Alexander on 11.12.12.
// Copyright (c) 2012 Peer1. All rights reserved.
//
#ifndef InternetMap_IndexBox_hpp
#define InternetMap_IndexBox_hpp
#include "Types.hpp"
#include <set>
static const float IndexBoxMinX = -8;
static const float IndexBoxMaxX = 8;
static const float IndexBoxMinY = -2.1;
static const float IndexBoxMaxY = 2.1;
static const float IndexBoxMinZ = -2.1;
static const float IndexBoxMaxZ = 2.1;
static const float lengthX = -IndexBoxMinX + IndexBoxMaxX;
static const float lengthY = -IndexBoxMinY + IndexBoxMaxY;
static const float lengthZ = -IndexBoxMinZ + IndexBoxMaxZ;
static const int numberOfCellsX = 32;
static const int numberOfCellsY = 4;
static const int numberOfCellsZ = 4;
static const float boxSizeXWithoutOverlap = lengthX/numberOfCellsX;
static const float boxSizeYWithoutOverlap = lengthY/numberOfCellsY;
static const float boxSizeZWithoutOverlap = lengthZ/numberOfCellsZ;
class IndexBox {
Point3 _parameters[2];
Point3 _center;
Point3 _minCorner;
Point3 _maxCorner;
public:
std::set<int> indices;
bool isPointInside(const Point3& point);
bool doesLineIntersectOptimized(const Vector3& origin, const Vector3& invertedDirection, int* sign);
Point3 minCorner();
Point3 maxCorner();
Point3 center();
void setMinCorner(const Point3& minCorner);
void setMaxCorner(const Point3& maxCorner);
void setCenter(const Point3& center);
};
typedef shared_ptr<IndexBox> IndexBoxPointer;
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCollection.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkCollection.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkCollection* vtkCollection::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCollection");
if(ret)
{
return (vtkCollection*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCollection;
}
// Construct with empty list.
vtkCollection::vtkCollection()
{
this->NumberOfItems = 0;
this->Top = NULL;
this->Bottom = NULL;
this->Current = NULL;
}
// Desctructor for the vtkCollection class. This removes all
// objects from the collection.
vtkCollection::~vtkCollection()
{
this->RemoveAllItems();
}
// protected function to delete an element. Internal use only.
void vtkCollection::DeleteElement(vtkCollectionElement *e)
{
if (e->Item != NULL)
{
e->Item->UnRegister(this);
}
delete e;
}
// Add an object to the list. Does not prevent duplicate entries.
void vtkCollection::AddItem(vtkObject *a)
{
vtkCollectionElement *elem;
elem = new vtkCollectionElement;
if (!this->Top)
{
this->Top = elem;
}
else
{
this->Bottom->Next = elem;
}
this->Bottom = elem;
a->Register(this);
elem->Item = a;
elem->Next = NULL;
this->Modified();
this->NumberOfItems++;
}
// Remove an object from the list. Removes the first object found, not
// all occurrences. If no object found, list is unaffected. See warning
// in description of RemoveItem(int).
void vtkCollection::RemoveItem(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
this->RemoveItem(i);
this->Modified();
return;
}
else
{
elem = elem->Next;
}
}
}
// Remove all objects from the list.
void vtkCollection::RemoveAllItems()
{
vtkCollectionElement *elem;
while (this->NumberOfItems )
{
elem = this->Top;
this->Top = elem->Next;
this->Current = elem->Next;
this->DeleteElement(elem);
this->NumberOfItems--;
}
this->Modified();
}
// Search for an object and return location in list. If location == 0,
// object was not found.
int vtkCollection::IsItemPresent(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return 0;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
return i + 1;
}
else
{
elem = elem->Next;
}
}
return 0;
}
// Return the number of objects in the list.
int vtkCollection::GetNumberOfItems()
{
return this->NumberOfItems;
}
void vtkCollection::PrintSelf(ostream& os, vtkIndent indent)
{
vtkObject::PrintSelf(os,indent);
os << indent << "Number Of Items: " << this->NumberOfItems << "\n";
}
// Get the i'th item in the collection. NULL is returned if i is out
// of range
vtkObject *vtkCollection::GetItemAsObject(int i)
{
vtkCollectionElement *elem=this->Top;
if (i < 0)
{
return NULL;
}
while (elem != NULL && i > 0)
{
elem = elem->Next;
i--;
}
if ( elem != NULL )
{
return elem->Item;
}
else
{
return NULL;
}
}
// Replace the i'th item in the collection with a
void vtkCollection::ReplaceItem(int i, vtkObject *a)
{
vtkCollectionElement *elem;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
elem = this->Top;
for (int j = 0; j < i; j++, elem = elem->Next )
{}
// Take care of reference counting
if (elem->Item != NULL)
{
elem->Item->UnRegister(this);
}
a->Register(this);
// j == i
elem->Item = a;
this->Modified();
}
// Remove the i'th item in the list.
// Be careful if using this function during traversal of the list using
// GetNextItemAsObject (or GetNextItem in derived class). The list WILL
// be shortened if a valid index is given! If this->Current is equal to the
// element being removed, have it point to then next element in the list.
void vtkCollection::RemoveItem(int i)
{
vtkCollectionElement *elem,*prev;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
this->Modified();
elem = this->Top;
prev = NULL;
for (int j = 0; j < i; j++)
{
prev = elem;
elem = elem->Next;
}
// j == i
if (prev)
{
prev->Next = elem->Next;
}
else
{
this->Top = elem->Next;
}
if (!elem->Next)
{
this->Bottom = prev;
}
if ( this->Current == elem )
{
this->Current = elem->Next;
}
this->DeleteElement(elem);
this->NumberOfItems--;
}
<commit_msg>minor fix to destructor<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCollection.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkCollection.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkCollection* vtkCollection::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCollection");
if(ret)
{
return (vtkCollection*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCollection;
}
// Construct with empty list.
vtkCollection::vtkCollection()
{
this->NumberOfItems = 0;
this->Top = NULL;
this->Bottom = NULL;
this->Current = NULL;
}
// Desctructor for the vtkCollection class. This removes all
// objects from the collection.
vtkCollection::~vtkCollection()
{
vtkCollectionElement *elem;
while (this->NumberOfItems )
{
elem = this->Top;
this->Top = elem->Next;
this->Current = elem->Next;
this->DeleteElement(elem);
this->NumberOfItems--;
}
}
// protected function to delete an element. Internal use only.
void vtkCollection::DeleteElement(vtkCollectionElement *e)
{
if (e->Item != NULL)
{
e->Item->UnRegister(this);
}
delete e;
}
// Add an object to the list. Does not prevent duplicate entries.
void vtkCollection::AddItem(vtkObject *a)
{
vtkCollectionElement *elem;
elem = new vtkCollectionElement;
if (!this->Top)
{
this->Top = elem;
}
else
{
this->Bottom->Next = elem;
}
this->Bottom = elem;
a->Register(this);
elem->Item = a;
elem->Next = NULL;
this->Modified();
this->NumberOfItems++;
}
// Remove an object from the list. Removes the first object found, not
// all occurrences. If no object found, list is unaffected. See warning
// in description of RemoveItem(int).
void vtkCollection::RemoveItem(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
this->RemoveItem(i);
this->Modified();
return;
}
else
{
elem = elem->Next;
}
}
}
// Remove all objects from the list.
void vtkCollection::RemoveAllItems()
{
vtkCollectionElement *elem;
while (this->NumberOfItems )
{
elem = this->Top;
this->Top = elem->Next;
this->Current = elem->Next;
this->DeleteElement(elem);
this->NumberOfItems--;
}
this->Modified();
}
// Search for an object and return location in list. If location == 0,
// object was not found.
int vtkCollection::IsItemPresent(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return 0;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
return i + 1;
}
else
{
elem = elem->Next;
}
}
return 0;
}
// Return the number of objects in the list.
int vtkCollection::GetNumberOfItems()
{
return this->NumberOfItems;
}
void vtkCollection::PrintSelf(ostream& os, vtkIndent indent)
{
vtkObject::PrintSelf(os,indent);
os << indent << "Number Of Items: " << this->NumberOfItems << "\n";
}
// Get the i'th item in the collection. NULL is returned if i is out
// of range
vtkObject *vtkCollection::GetItemAsObject(int i)
{
vtkCollectionElement *elem=this->Top;
if (i < 0)
{
return NULL;
}
while (elem != NULL && i > 0)
{
elem = elem->Next;
i--;
}
if ( elem != NULL )
{
return elem->Item;
}
else
{
return NULL;
}
}
// Replace the i'th item in the collection with a
void vtkCollection::ReplaceItem(int i, vtkObject *a)
{
vtkCollectionElement *elem;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
elem = this->Top;
for (int j = 0; j < i; j++, elem = elem->Next )
{}
// Take care of reference counting
if (elem->Item != NULL)
{
elem->Item->UnRegister(this);
}
a->Register(this);
// j == i
elem->Item = a;
this->Modified();
}
// Remove the i'th item in the list.
// Be careful if using this function during traversal of the list using
// GetNextItemAsObject (or GetNextItem in derived class). The list WILL
// be shortened if a valid index is given! If this->Current is equal to the
// element being removed, have it point to then next element in the list.
void vtkCollection::RemoveItem(int i)
{
vtkCollectionElement *elem,*prev;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
this->Modified();
elem = this->Top;
prev = NULL;
for (int j = 0; j < i; j++)
{
prev = elem;
elem = elem->Next;
}
// j == i
if (prev)
{
prev->Next = elem->Next;
}
else
{
this->Top = elem->Next;
}
if (!elem->Next)
{
this->Bottom = prev;
}
if ( this->Current == elem )
{
this->Current = elem->Next;
}
this->DeleteElement(elem);
this->NumberOfItems--;
}
<|endoftext|> |
<commit_before><commit_msg>Fix a few unresolved symbols.<commit_after><|endoftext|> |
<commit_before>#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <fstream> // NOLINT(readability/streams)
#include <iostream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "caffe/data_transformer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/layers/bbtxt_data_layer.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
// The maximum number of bounding boxes (annotations) in one image - we set the label blob shape according
// to this number
#define MAX_NUM_BBS_PER_IMAGE 20
namespace caffe {
namespace {
/**
* @brief Computes the number of bounding boxes in the annotation
* @param labels Annotation of one image (dimensions 1 x MAX_NUM_BBS_PER_IMAGE x 5)
* @return Number of bounding boxes in this label
*/
template <typename Dtype>
int numBBs (const Blob<Dtype> &labels)
{
for (int i = 0; i < labels.shape(1); ++i)
{
// Data are stored like this [label, xmin, ymin, xmax, ymax]
const Dtype *data = labels.cpu_data() + labels.offset(0, i);
// If the label is -1, there are no more bounding boxes
if (data[0] == Dtype(-1.0f)) return i;
}
return labels.shape(1);
}
}
template <typename Dtype>
BBTXTDataLayer<Dtype>::BBTXTDataLayer (const LayerParameter ¶m)
: BasePrefetchingDataLayer<Dtype>(param)
{
}
template <typename Dtype>
BBTXTDataLayer<Dtype>::~BBTXTDataLayer<Dtype> ()
{
this->StopInternalThread();
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::DataLayerSetUp (const vector<Blob<Dtype>*> &bottom,
const vector<Blob<Dtype>*> &top)
{
CHECK(this->layer_param_.has_bbtxt_param()) << "BBTXTParam is mandatory!";
CHECK(this->layer_param_.bbtxt_param().has_height()) << "Height must be set!";
CHECK(this->layer_param_.bbtxt_param().has_width()) << "Width must be set!";
CHECK(this->layer_param_.bbtxt_param().has_reference_size()) << "Reference size must be set!";
const int height = this->layer_param_.bbtxt_param().height();
const int width = this->layer_param_.bbtxt_param().width();
const int batch_size = this->layer_param_.image_data_param().batch_size();
this->_rng.reset(new Caffe::RNG(caffe_rng_rand()));
// Load the BBTXT file with 2D bounding box annotations
this->_loadBBTXTFile();
this->_i_global = 0;
CHECK(!this->_images.empty()) << "The given BBTXT file is empty!";
LOG(INFO) << "There are " << this->_images.size() << " images in the dataset set.";
if (this->layer_param_.image_data_param().shuffle())
{
// Initialize the random number generator for shuffling and shuffle the images
this->_shuffleImages();
}
// This is the shape of the input blob
std::vector<int> top_shape = {1, 3, height, width};
this->transformed_data_.Reshape(top_shape); // For prefetching
top_shape[0] = batch_size;
top[0]->Reshape(top_shape);
// Label blob
std::vector<int> label_shape = {1, MAX_NUM_BBS_PER_IMAGE, 5};
this->transformed_label_.Reshape(label_shape); // For prefetching
label_shape[0] = batch_size;
top[1]->Reshape(label_shape);
// Initialize prefetching
// We also have to reshape the prefetching blobs to the correct batch size
for (int i = 0; i < this->prefetch_.size(); ++i)
{
this->prefetch_[i]->data_.Reshape(top_shape);
this->prefetch_[i]->label_.Reshape(label_shape);
}
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::load_batch (Batch<Dtype> *batch)
{
// This function is called on a prefetch thread
CHECK(batch->data_.count());
CHECK(this->transformed_data_.count());
const int batch_size = this->layer_param_.image_data_param().batch_size();
Dtype* prefetch_data = batch->data_.mutable_cpu_data();
Dtype* prefetch_label = batch->label_.mutable_cpu_data();
for (int b = 0; b < batch_size; ++b)
{
// get a blob
cv::Mat cv_img = cv::imread(this->_images[this->_i_global].first, CV_LOAD_IMAGE_COLOR);
CHECK(cv_img.data) << "Could not open " << this->_images[this->_i_global].first;
// Prepare the blob for the annotation (bounding boxes)
int offset_label = batch->label_.offset(b);
this->transformed_label_.set_cpu_data(prefetch_label + offset_label);
// Copy the annotation - we really have to copy it because it will be altered during image
// transformations like cropping or scaling
std::shared_ptr<Blob<Dtype>> plabel = this->_images[this->_i_global].second;
caffe_copy(plabel->count(), plabel->cpu_data(), this->transformed_label_.mutable_cpu_data());
// Prepare the blob for the current image
int offset_image = batch->data_.offset(b);
this->transformed_data_.set_cpu_data(prefetch_data + offset_image);
// Apply transformations (mirror, crop...) to the image and resize the image to the input blob shape
// of the network - setting the transformed_data_ and transformed_label_ sets it directly in the batch
this->_transformImage(cv_img, this->transformed_data_, this->transformed_label_);
// Move index to the next image
this->_i_global++;
if (this->_i_global >= this->_images.size())
{
// Restart the counter from the begining
if (this->layer_param_.image_data_param().shuffle()) this->_shuffleImages();
this->_i_global = 0;
}
}
}
// ----------------------------------------- PROTECTED METHODS ----------------------------------------- //
template <typename Dtype>
void BBTXTDataLayer<Dtype>::_loadBBTXTFile ()
{
const std::string& source = this->layer_param_.image_data_param().source();
std::ifstream infile(source.c_str(), std::ios::in);
CHECK(infile.is_open()) << "BBTXT file '" << source << "' could not be opened!";
std::string line;
std::vector<std::string> data;
std::string current_filename = "";
int i = 0;
// Read the whole file and create entries in the _images for all images
while (std::getline(infile, line))
{
// Split the line - entries separated by space [filename label confidence xmin ymin xmax ymax]
boost::split(data, line, boost::is_any_of(" "));
CHECK_EQ(data.size(), 7) << "Line '" << line << "' corrupted!";
if (current_filename != data[0])
{
// This is a label to a new image
if (this->_images.size() > 0 && i < MAX_NUM_BBS_PER_IMAGE)
{
// Finalize the last annotation - we put -1 as next bounding box label to signalize
// the end - this is because each image can have a different number of bounding boxes
int offset = this->_images.back().second->offset(i);
Dtype* bb_position = this->_images.back().second->mutable_cpu_data() + offset;
bb_position[0] = Dtype(-1.0f);
}
CHECK(boost::filesystem::exists(data[0])) << "File '" << data[0] << "' not found!";
// Create new image entry
this->_images.push_back(std::make_pair(data[0],
std::make_shared<Blob<Dtype>>(MAX_NUM_BBS_PER_IMAGE, 5, 1, 1)));
i = 0;
current_filename = data[0];
}
// Write the bounding box info into the blob
if (i < MAX_NUM_BBS_PER_IMAGE)
{
int offset = this->_images.back().second->offset(i);
Dtype* bb_position = this->_images.back().second->mutable_cpu_data() + offset;
bb_position[0] = Dtype(std::stof(data[1])); // label
bb_position[1] = Dtype(std::stof(data[3])); // xmin
bb_position[2] = Dtype(std::stof(data[4])); // ymin
bb_position[3] = Dtype(std::stof(data[5])); // xmax
bb_position[4] = Dtype(std::stof(data[6])); // ymax
i++;
}
else
{
LOG(WARNING) << "Skipping bb - max number of bounding boxes per image reached.";
}
}
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::_shuffleImages ()
{
caffe::rng_t* prefetch_rng = static_cast<caffe::rng_t*>(_rng->generator());
shuffle(this->_images.begin(), this->_images.end(), prefetch_rng);
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::_transformImage (const cv::Mat &cv_img, Blob<Dtype> &transformed_image,
Blob<Dtype> &transformed_label)
{
static int imi = 0;
CHECK_EQ(cv_img.channels(), 3) << "Image must have 3 color channels";
// Input dimensions of the network
const int height = this->layer_param_.bbtxt_param().height();
const int width = this->layer_param_.bbtxt_param().width();
// This is the size of the bounding box that is detected by this network
const int reference_size = this->layer_param_.bbtxt_param().reference_size();
caffe::rng_t* rng = static_cast<caffe::rng_t*>(this->_rng->generator());
// We select a bounding box from the image and then make a crop such that the bounding box is inside
// of it and it has the reference size
cv::Mat cv_img_cropped;
if (transformed_label.cpu_data()[0] == Dtype(-1.0f))
{
// The label of the first bounding box is -1, that means that this image contains no bounding boxes
cv::resize(cv_img, cv_img_cropped, cv::Size(width, height));
}
else
{
std::cout << "Doing this.................." << std::endl;
// There are bounding boxes - lets select one
const int num_bbs = numBBs(transformed_label);
boost::random::uniform_int_distribution<> dist(0, num_bbs-1);
const int bb_id = dist(*rng); // Random bounding box id
// Get dimensions of the bounding box - format [label, xmin, ymin, xmax, ymax]
const Dtype * bb_data = transformed_label.cpu_data() + transformed_label.offset(0, bb_id);
const Dtype x = bb_data[1];
const Dtype y = bb_data[2];
const Dtype w = bb_data[3] - bb_data[1];
const Dtype h = bb_data[4] - bb_data[2];
const Dtype size = std::max(w, h);
const int crop_width = double(width) / reference_size * size;
const int crop_height = double(height) / reference_size * size;
// Select a random position of the crop, but it has to fully contain the bounding box
boost::random::uniform_int_distribution<> distx(x+w-crop_width, x);
boost::random::uniform_int_distribution<> disty(y+h-crop_height, y);
const int crop_x = distx(*rng);
const int crop_y = disty(*rng);
// Now if the crop spans outside the image we have to pad the image
int border_top = 0; int border_bottom = 0; int border_left = 0; int border_right = 0;
if (crop_x < 0) border_left = -crop_x;
if (crop_y < 0) border_top = -crop_y;
if (crop_x+crop_width > cv_img.cols) border_right = crop_x+crop_width - cv_img.cols;
if (crop_y+crop_height > cv_img.rows) border_bottom = crop_y+crop_height - cv_img.rows;
cv::Mat cv_img_padded;
cv::copyMakeBorder(cv_img, cv_img_padded, border_top, border_bottom, border_left, border_right,
cv::BORDER_REPLICATE);
// Crop
cv_img_cropped = cv_img_padded(cv::Rect(crop_x+border_left, crop_y+border_top, crop_width, crop_height));
// Resize
cv::resize(cv_img_cropped, cv_img_cropped, cv::Size(width, height));
// Update the bounding box coordinates - we need to update all annotations
Dtype x_scaling = float(width) / crop_width;
Dtype y_scaling = float(height) / crop_height;
for (int b = 0; b < num_bbs; ++b)
{
// Data are stored like this [label, xmin, ymin, xmax, ymax]
Dtype *data = transformed_label.mutable_cpu_data() + transformed_label.offset(0, b);
// Align with x, y of the crop
data[1] -= crop_x;
data[2] -= crop_y;
data[3] -= crop_x;
data[4] -= crop_y;
// Now the scaling
data[1] *= x_scaling;
data[2] *= y_scaling;
data[3] *= x_scaling;
data[4] *= y_scaling;
// cv::rectangle(cv_img_cropped, cv::Rect(data[1], data[2], data[3]-data[1], data[4]-data[2]), cv::Scalar(0,0,255), 2);
}
// cv::imwrite("cropped" + std::to_string(imi++) + ".png", cv_img_cropped);
// Mirror
}
CHECK(cv_img_cropped.data) << "Something went wrong with cropping!";
CHECK_EQ(cv_img_cropped.rows, transformed_image.shape(2)) << "Wrong crop height! Does not match network!";
CHECK_EQ(cv_img_cropped.cols, transformed_image.shape(3)) << "Wrong crop width! Does not match network!";
// Normalize to 0 mean and unit variance and copy the image to the transformed_image
// + apply exposure, noise, hue, saturation, ...
Dtype* transformed_data = transformed_image.mutable_cpu_data();
for (int i = 0; i < height; ++i)
{
const uchar* ptr = cv_img_cropped.ptr<uchar>(i);
int img_index = 0; // Index in the cv_img_cropped
for (int j = 0; j < width; ++j)
{
for (int c = 0; c < 3; ++c)
{
const int top_index = (c * height + i) * width + j;
// Zero mean and unit variance
transformed_data[top_index] = (ptr[img_index++] - Dtype(128.0f)) / Dtype(128.0f);
}
}
}
}
// ---------------------------------------- LAYER INSTANTIATION ---------------------------------------- //
INSTANTIATE_CLASS(BBTXTDataLayer);
REGISTER_LAYER_CLASS(BBTXTData);
} // namespace caffe
#endif // USE_OPENCV
<commit_msg>Removed debug output<commit_after>#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <fstream> // NOLINT(readability/streams)
#include <iostream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "caffe/data_transformer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/layers/bbtxt_data_layer.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
// The maximum number of bounding boxes (annotations) in one image - we set the label blob shape according
// to this number
#define MAX_NUM_BBS_PER_IMAGE 20
namespace caffe {
namespace {
/**
* @brief Computes the number of bounding boxes in the annotation
* @param labels Annotation of one image (dimensions 1 x MAX_NUM_BBS_PER_IMAGE x 5)
* @return Number of bounding boxes in this label
*/
template <typename Dtype>
int numBBs (const Blob<Dtype> &labels)
{
for (int i = 0; i < labels.shape(1); ++i)
{
// Data are stored like this [label, xmin, ymin, xmax, ymax]
const Dtype *data = labels.cpu_data() + labels.offset(0, i);
// If the label is -1, there are no more bounding boxes
if (data[0] == Dtype(-1.0f)) return i;
}
return labels.shape(1);
}
}
template <typename Dtype>
BBTXTDataLayer<Dtype>::BBTXTDataLayer (const LayerParameter ¶m)
: BasePrefetchingDataLayer<Dtype>(param)
{
}
template <typename Dtype>
BBTXTDataLayer<Dtype>::~BBTXTDataLayer<Dtype> ()
{
this->StopInternalThread();
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::DataLayerSetUp (const vector<Blob<Dtype>*> &bottom,
const vector<Blob<Dtype>*> &top)
{
CHECK(this->layer_param_.has_bbtxt_param()) << "BBTXTParam is mandatory!";
CHECK(this->layer_param_.bbtxt_param().has_height()) << "Height must be set!";
CHECK(this->layer_param_.bbtxt_param().has_width()) << "Width must be set!";
CHECK(this->layer_param_.bbtxt_param().has_reference_size()) << "Reference size must be set!";
const int height = this->layer_param_.bbtxt_param().height();
const int width = this->layer_param_.bbtxt_param().width();
const int batch_size = this->layer_param_.image_data_param().batch_size();
this->_rng.reset(new Caffe::RNG(caffe_rng_rand()));
// Load the BBTXT file with 2D bounding box annotations
this->_loadBBTXTFile();
this->_i_global = 0;
CHECK(!this->_images.empty()) << "The given BBTXT file is empty!";
LOG(INFO) << "There are " << this->_images.size() << " images in the dataset set.";
if (this->layer_param_.image_data_param().shuffle())
{
// Initialize the random number generator for shuffling and shuffle the images
this->_shuffleImages();
}
// This is the shape of the input blob
std::vector<int> top_shape = {1, 3, height, width};
this->transformed_data_.Reshape(top_shape); // For prefetching
top_shape[0] = batch_size;
top[0]->Reshape(top_shape);
// Label blob
std::vector<int> label_shape = {1, MAX_NUM_BBS_PER_IMAGE, 5};
this->transformed_label_.Reshape(label_shape); // For prefetching
label_shape[0] = batch_size;
top[1]->Reshape(label_shape);
// Initialize prefetching
// We also have to reshape the prefetching blobs to the correct batch size
for (int i = 0; i < this->prefetch_.size(); ++i)
{
this->prefetch_[i]->data_.Reshape(top_shape);
this->prefetch_[i]->label_.Reshape(label_shape);
}
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::load_batch (Batch<Dtype> *batch)
{
// This function is called on a prefetch thread
CHECK(batch->data_.count());
CHECK(this->transformed_data_.count());
const int batch_size = this->layer_param_.image_data_param().batch_size();
Dtype* prefetch_data = batch->data_.mutable_cpu_data();
Dtype* prefetch_label = batch->label_.mutable_cpu_data();
for (int b = 0; b < batch_size; ++b)
{
// get a blob
cv::Mat cv_img = cv::imread(this->_images[this->_i_global].first, CV_LOAD_IMAGE_COLOR);
CHECK(cv_img.data) << "Could not open " << this->_images[this->_i_global].first;
// Prepare the blob for the annotation (bounding boxes)
int offset_label = batch->label_.offset(b);
this->transformed_label_.set_cpu_data(prefetch_label + offset_label);
// Copy the annotation - we really have to copy it because it will be altered during image
// transformations like cropping or scaling
std::shared_ptr<Blob<Dtype>> plabel = this->_images[this->_i_global].second;
caffe_copy(plabel->count(), plabel->cpu_data(), this->transformed_label_.mutable_cpu_data());
// Prepare the blob for the current image
int offset_image = batch->data_.offset(b);
this->transformed_data_.set_cpu_data(prefetch_data + offset_image);
// Apply transformations (mirror, crop...) to the image and resize the image to the input blob shape
// of the network - setting the transformed_data_ and transformed_label_ sets it directly in the batch
this->_transformImage(cv_img, this->transformed_data_, this->transformed_label_);
// Move index to the next image
this->_i_global++;
if (this->_i_global >= this->_images.size())
{
// Restart the counter from the begining
if (this->layer_param_.image_data_param().shuffle()) this->_shuffleImages();
this->_i_global = 0;
}
}
}
// ----------------------------------------- PROTECTED METHODS ----------------------------------------- //
template <typename Dtype>
void BBTXTDataLayer<Dtype>::_loadBBTXTFile ()
{
const std::string& source = this->layer_param_.image_data_param().source();
std::ifstream infile(source.c_str(), std::ios::in);
CHECK(infile.is_open()) << "BBTXT file '" << source << "' could not be opened!";
std::string line;
std::vector<std::string> data;
std::string current_filename = "";
int i = 0;
// Read the whole file and create entries in the _images for all images
while (std::getline(infile, line))
{
// Split the line - entries separated by space [filename label confidence xmin ymin xmax ymax]
boost::split(data, line, boost::is_any_of(" "));
CHECK_EQ(data.size(), 7) << "Line '" << line << "' corrupted!";
if (current_filename != data[0])
{
// This is a label to a new image
if (this->_images.size() > 0 && i < MAX_NUM_BBS_PER_IMAGE)
{
// Finalize the last annotation - we put -1 as next bounding box label to signalize
// the end - this is because each image can have a different number of bounding boxes
int offset = this->_images.back().second->offset(i);
Dtype* bb_position = this->_images.back().second->mutable_cpu_data() + offset;
bb_position[0] = Dtype(-1.0f);
}
CHECK(boost::filesystem::exists(data[0])) << "File '" << data[0] << "' not found!";
// Create new image entry
this->_images.push_back(std::make_pair(data[0],
std::make_shared<Blob<Dtype>>(MAX_NUM_BBS_PER_IMAGE, 5, 1, 1)));
i = 0;
current_filename = data[0];
}
// Write the bounding box info into the blob
if (i < MAX_NUM_BBS_PER_IMAGE)
{
int offset = this->_images.back().second->offset(i);
Dtype* bb_position = this->_images.back().second->mutable_cpu_data() + offset;
bb_position[0] = Dtype(std::stof(data[1])); // label
bb_position[1] = Dtype(std::stof(data[3])); // xmin
bb_position[2] = Dtype(std::stof(data[4])); // ymin
bb_position[3] = Dtype(std::stof(data[5])); // xmax
bb_position[4] = Dtype(std::stof(data[6])); // ymax
i++;
}
else
{
LOG(WARNING) << "Skipping bb - max number of bounding boxes per image reached.";
}
}
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::_shuffleImages ()
{
caffe::rng_t* prefetch_rng = static_cast<caffe::rng_t*>(_rng->generator());
shuffle(this->_images.begin(), this->_images.end(), prefetch_rng);
}
template <typename Dtype>
void BBTXTDataLayer<Dtype>::_transformImage (const cv::Mat &cv_img, Blob<Dtype> &transformed_image,
Blob<Dtype> &transformed_label)
{
static int imi = 0;
CHECK_EQ(cv_img.channels(), 3) << "Image must have 3 color channels";
// Input dimensions of the network
const int height = this->layer_param_.bbtxt_param().height();
const int width = this->layer_param_.bbtxt_param().width();
// This is the size of the bounding box that is detected by this network
const int reference_size = this->layer_param_.bbtxt_param().reference_size();
caffe::rng_t* rng = static_cast<caffe::rng_t*>(this->_rng->generator());
// We select a bounding box from the image and then make a crop such that the bounding box is inside
// of it and it has the reference size
cv::Mat cv_img_cropped;
if (transformed_label.cpu_data()[0] == Dtype(-1.0f))
{
// The label of the first bounding box is -1, that means that this image contains no bounding boxes
cv::resize(cv_img, cv_img_cropped, cv::Size(width, height));
}
else
{
// There are bounding boxes - lets select one
const int num_bbs = numBBs(transformed_label);
boost::random::uniform_int_distribution<> dist(0, num_bbs-1);
const int bb_id = dist(*rng); // Random bounding box id
// Get dimensions of the bounding box - format [label, xmin, ymin, xmax, ymax]
const Dtype * bb_data = transformed_label.cpu_data() + transformed_label.offset(0, bb_id);
const Dtype x = bb_data[1];
const Dtype y = bb_data[2];
const Dtype w = bb_data[3] - bb_data[1];
const Dtype h = bb_data[4] - bb_data[2];
const Dtype size = std::max(w, h);
const int crop_width = double(width) / reference_size * size;
const int crop_height = double(height) / reference_size * size;
// Select a random position of the crop, but it has to fully contain the bounding box
boost::random::uniform_int_distribution<> distx(x+w-crop_width, x);
boost::random::uniform_int_distribution<> disty(y+h-crop_height, y);
const int crop_x = distx(*rng);
const int crop_y = disty(*rng);
// Now if the crop spans outside the image we have to pad the image
int border_top = 0; int border_bottom = 0; int border_left = 0; int border_right = 0;
if (crop_x < 0) border_left = -crop_x;
if (crop_y < 0) border_top = -crop_y;
if (crop_x+crop_width > cv_img.cols) border_right = crop_x+crop_width - cv_img.cols;
if (crop_y+crop_height > cv_img.rows) border_bottom = crop_y+crop_height - cv_img.rows;
cv::Mat cv_img_padded;
cv::copyMakeBorder(cv_img, cv_img_padded, border_top, border_bottom, border_left, border_right,
cv::BORDER_REPLICATE);
// Crop
cv_img_cropped = cv_img_padded(cv::Rect(crop_x+border_left, crop_y+border_top, crop_width, crop_height));
// Resize
cv::resize(cv_img_cropped, cv_img_cropped, cv::Size(width, height));
// Update the bounding box coordinates - we need to update all annotations
Dtype x_scaling = float(width) / crop_width;
Dtype y_scaling = float(height) / crop_height;
for (int b = 0; b < num_bbs; ++b)
{
// Data are stored like this [label, xmin, ymin, xmax, ymax]
Dtype *data = transformed_label.mutable_cpu_data() + transformed_label.offset(0, b);
// Align with x, y of the crop
data[1] -= crop_x;
data[2] -= crop_y;
data[3] -= crop_x;
data[4] -= crop_y;
// Now the scaling
data[1] *= x_scaling;
data[2] *= y_scaling;
data[3] *= x_scaling;
data[4] *= y_scaling;
// cv::rectangle(cv_img_cropped, cv::Rect(data[1], data[2], data[3]-data[1], data[4]-data[2]), cv::Scalar(0,0,255), 2);
}
// cv::imwrite("cropped" + std::to_string(imi++) + ".png", cv_img_cropped);
// Mirror
}
CHECK(cv_img_cropped.data) << "Something went wrong with cropping!";
CHECK_EQ(cv_img_cropped.rows, transformed_image.shape(2)) << "Wrong crop height! Does not match network!";
CHECK_EQ(cv_img_cropped.cols, transformed_image.shape(3)) << "Wrong crop width! Does not match network!";
// Normalize to 0 mean and unit variance and copy the image to the transformed_image
// + apply exposure, noise, hue, saturation, ...
Dtype* transformed_data = transformed_image.mutable_cpu_data();
for (int i = 0; i < height; ++i)
{
const uchar* ptr = cv_img_cropped.ptr<uchar>(i);
int img_index = 0; // Index in the cv_img_cropped
for (int j = 0; j < width; ++j)
{
for (int c = 0; c < 3; ++c)
{
const int top_index = (c * height + i) * width + j;
// Zero mean and unit variance
transformed_data[top_index] = (ptr[img_index++] - Dtype(128.0f)) / Dtype(128.0f);
}
}
}
}
// ---------------------------------------- LAYER INSTANTIATION ---------------------------------------- //
INSTANTIATE_CLASS(BBTXTDataLayer);
REGISTER_LAYER_CLASS(BBTXTData);
} // namespace caffe
#endif // USE_OPENCV
<|endoftext|> |
<commit_before>#include <iostream>
using std::cin;
using std::cout;
class VarString {
public:
VarString() {};
VarString(char* init);
~VarString();
int length();
char characterAt(int pos);
void append(char c);
void concatenate(const VarString s2);
private:
typedef char* string;
string _s;
};
int VarString::length()
{
int count = 0;
while (_s[count] != 0) {
count++;
}
return count;
}
char VarString::characterAt(int pos)
{
return _s[pos];
}
void VarString::append(char c)
{
int oldLength = 0;
while (_s[oldLength] != 0) {
oldLength++;
}
string newS = new char[oldLength + 2];
for (int i = 0; i < oldLength; i++) {
newS[i] = _s[i];
}
newS[oldLength] = c;
newS[oldLength + 1] = 0;
delete[] _s;
_s = newS;
}
void VarString::concatenate(const VarString& s2)
{
int s1_oldLength = length(_s);
int s2_length = length(s2);
int s1_newLength = s1_oldLength + s2_length;
string newS = new char[s1_newLength + 1];
for (int i = 0; i < s1_oldLength; i++) {
newS[i] = _s[i];
}
for (int i = 0; i < s2_length; i++) {
newS[s1_oldLength + i] = s2[i];
}
newS[s1_newLength] = 0;
delete[] _s;
_s = newS;
}
int main()
{
return 0;
}
<commit_msg>methods implemented. not all tested<commit_after>#include <iostream>
using namespace std;
class VarString {
public:
VarString();
VarString(const char* init);
~VarString();
int length() const;
void append(char c);
void concatenate(const VarString& s2);
char operator[](int pos) const;
VarString& operator=(const VarString& rhs);
private:
typedef char* string;
string _s;
};
VarString::VarString()
{
_s = new char[1] {0};
}
VarString::VarString(const char* init)
{
int count = 0;
for (int i = 0; init[i] != 0; i++) {
count++;
}
string newS = new char[count];
for (int i = 0; init[i] != 0; i++) {
newS[i] = init[i];
}
_s = newS;
}
int VarString::length() const
{
int count = 0;
while (_s[count] != 0) {
count++;
}
return count;
}
char VarString::operator[](int pos) const
{
return _s[pos];
}
void VarString::append(char c)
{
int oldLength = 0;
while (_s[oldLength] != 0) {
oldLength++;
}
string newS = new char[oldLength + 2];
for (int i = 0; i < oldLength; i++) {
newS[i] = _s[i];
}
newS[oldLength] = c;
newS[oldLength + 1] = 0;
delete[] _s;
_s = newS;
}
void VarString::concatenate(const VarString& s2)
{
int s1_oldLength = this->length();
int s2_length = s2.length();
int s1_newLength = s1_oldLength + s2_length;
string newS = new char[s1_newLength + 1];
for (int i = 0; i < s1_oldLength; i++) {
newS[i] = _s[i];
}
for (int i = 0; i < s2_length; i++) {
newS[s1_oldLength + i] = s2._s[i];
}
newS[s1_newLength] = 0;
delete[] _s;
_s = newS;
}
VarString& VarString::operator=(const VarString& rhs)
{
int length = rhs.length() + 1;
string copy = new char[length];
for (int i = 0; i < length; i++) {
copy[i] = rhs._s[i];
}
copy[length] = 0;
_s = copy;
delete[] copy;
return *this;
}
ostream& operator<<(ostream& ost, const VarString& rhs)
{
for (int i = 0; rhs[i] != 0; i++) {
ost << rhs[i];
}
return ost;
}
VarString::~VarString()
{
delete[] _s;
}
int main()
{ //Test all methods
VarString s1("This is a variable string");
VarString s2;
s2.concatenate(s1);
cout << s1 << '\n';
cout << s2 << '\n';
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(ENABLE_GPU)
#include "base/process_util.h"
#include "base/shared_memory.h"
#include "build/build_config.h"
#include "chrome/common/gpu_messages.h"
#include "chrome/gpu/gpu_channel.h"
#include "chrome/gpu/gpu_command_buffer_stub.h"
using gpu::Buffer;
GpuCommandBufferStub::GpuCommandBufferStub(GpuChannel* channel,
gfx::PluginWindowHandle handle,
GpuCommandBufferStub* parent,
const gfx::Size& size,
uint32 parent_texture_id,
int32 route_id)
: channel_(channel),
handle_(handle),
parent_(parent),
initial_size_(size),
parent_texture_id_(parent_texture_id),
route_id_(route_id) {
}
GpuCommandBufferStub::~GpuCommandBufferStub() {
if (processor_.get()) {
processor_->Destroy();
}
}
void GpuCommandBufferStub::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(GpuCommandBufferStub, message)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Initialize, OnInitialize);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_GetState, OnGetState);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncGetState, OnAsyncGetState);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Flush, OnFlush);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncFlush, OnAsyncFlush);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateTransferBuffer,
OnCreateTransferBuffer);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyTransferBuffer,
OnDestroyTransferBuffer);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_GetTransferBuffer,
OnGetTransferBuffer);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_ResizeOffscreenFrameBuffer,
OnResizeOffscreenFrameBuffer);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
bool GpuCommandBufferStub::Send(IPC::Message* message) {
return channel_->Send(message);
}
void GpuCommandBufferStub::OnInitialize(
int32 size,
base::SharedMemoryHandle* ring_buffer) {
DCHECK(!command_buffer_.get());
*ring_buffer = base::SharedMemory::NULLHandle();
command_buffer_.reset(new gpu::CommandBufferService);
// Initialize the CommandBufferService and GPUProcessor.
if (command_buffer_->Initialize(size)) {
Buffer buffer = command_buffer_->GetRingBuffer();
if (buffer.shared_memory) {
gpu::GPUProcessor* parent_processor =
parent_ ? parent_->processor_.get() : NULL;
processor_.reset(new gpu::GPUProcessor(command_buffer_.get()));
// TODO(apatrick): The reinterpret_cast below is only valid on windows.
if (processor_->Initialize(
handle_,
initial_size_,
parent_processor,
parent_texture_id_)) {
command_buffer_->SetPutOffsetChangeCallback(
NewCallback(processor_.get(),
&gpu::GPUProcessor::ProcessCommands));
// Assume service is responsible for duplicating the handle from the
// calling process.
buffer.shared_memory->ShareToProcess(channel_->renderer_handle(),
ring_buffer);
} else {
processor_.reset();
command_buffer_.reset();
}
}
}
}
void GpuCommandBufferStub::OnGetState(gpu::CommandBuffer::State* state) {
*state = command_buffer_->GetState();
}
void GpuCommandBufferStub::OnAsyncGetState() {
gpu::CommandBuffer::State state = command_buffer_->GetState();
Send(new GpuCommandBufferMsg_UpdateState(route_id_, state));
}
void GpuCommandBufferStub::OnFlush(int32 put_offset,
gpu::CommandBuffer::State* state) {
*state = command_buffer_->Flush(put_offset);
}
void GpuCommandBufferStub::OnAsyncFlush(int32 put_offset) {
gpu::CommandBuffer::State state = command_buffer_->Flush(put_offset);
Send(new GpuCommandBufferMsg_UpdateState(route_id_, state));
}
void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size, int32* id) {
*id = command_buffer_->CreateTransferBuffer(size);
}
void GpuCommandBufferStub::OnDestroyTransferBuffer(int32 id) {
command_buffer_->DestroyTransferBuffer(id);
}
void GpuCommandBufferStub::OnGetTransferBuffer(
int32 id,
base::SharedMemoryHandle* transfer_buffer,
uint32* size) {
*transfer_buffer = base::SharedMemoryHandle();
*size = 0;
Buffer buffer = command_buffer_->GetTransferBuffer(id);
if (buffer.shared_memory) {
// Assume service is responsible for duplicating the handle to the calling
// process.
buffer.shared_memory->ShareToProcess(channel_->renderer_handle(),
transfer_buffer);
*size = buffer.shared_memory->max_size();
}
}
void GpuCommandBufferStub::OnResizeOffscreenFrameBuffer(const gfx::Size& size) {
processor_->ResizeOffscreenFrameBuffer(size);
}
#endif // ENABLE_GPU
<commit_msg>Remove outdated TODO<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(ENABLE_GPU)
#include "base/process_util.h"
#include "base/shared_memory.h"
#include "build/build_config.h"
#include "chrome/common/gpu_messages.h"
#include "chrome/gpu/gpu_channel.h"
#include "chrome/gpu/gpu_command_buffer_stub.h"
using gpu::Buffer;
GpuCommandBufferStub::GpuCommandBufferStub(GpuChannel* channel,
gfx::PluginWindowHandle handle,
GpuCommandBufferStub* parent,
const gfx::Size& size,
uint32 parent_texture_id,
int32 route_id)
: channel_(channel),
handle_(handle),
parent_(parent),
initial_size_(size),
parent_texture_id_(parent_texture_id),
route_id_(route_id) {
}
GpuCommandBufferStub::~GpuCommandBufferStub() {
if (processor_.get()) {
processor_->Destroy();
}
}
void GpuCommandBufferStub::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(GpuCommandBufferStub, message)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Initialize, OnInitialize);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_GetState, OnGetState);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncGetState, OnAsyncGetState);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Flush, OnFlush);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncFlush, OnAsyncFlush);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateTransferBuffer,
OnCreateTransferBuffer);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyTransferBuffer,
OnDestroyTransferBuffer);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_GetTransferBuffer,
OnGetTransferBuffer);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_ResizeOffscreenFrameBuffer,
OnResizeOffscreenFrameBuffer);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
bool GpuCommandBufferStub::Send(IPC::Message* message) {
return channel_->Send(message);
}
void GpuCommandBufferStub::OnInitialize(
int32 size,
base::SharedMemoryHandle* ring_buffer) {
DCHECK(!command_buffer_.get());
*ring_buffer = base::SharedMemory::NULLHandle();
command_buffer_.reset(new gpu::CommandBufferService);
// Initialize the CommandBufferService and GPUProcessor.
if (command_buffer_->Initialize(size)) {
Buffer buffer = command_buffer_->GetRingBuffer();
if (buffer.shared_memory) {
gpu::GPUProcessor* parent_processor =
parent_ ? parent_->processor_.get() : NULL;
processor_.reset(new gpu::GPUProcessor(command_buffer_.get()));
if (processor_->Initialize(
handle_,
initial_size_,
parent_processor,
parent_texture_id_)) {
command_buffer_->SetPutOffsetChangeCallback(
NewCallback(processor_.get(),
&gpu::GPUProcessor::ProcessCommands));
// Assume service is responsible for duplicating the handle from the
// calling process.
buffer.shared_memory->ShareToProcess(channel_->renderer_handle(),
ring_buffer);
} else {
processor_.reset();
command_buffer_.reset();
}
}
}
}
void GpuCommandBufferStub::OnGetState(gpu::CommandBuffer::State* state) {
*state = command_buffer_->GetState();
}
void GpuCommandBufferStub::OnAsyncGetState() {
gpu::CommandBuffer::State state = command_buffer_->GetState();
Send(new GpuCommandBufferMsg_UpdateState(route_id_, state));
}
void GpuCommandBufferStub::OnFlush(int32 put_offset,
gpu::CommandBuffer::State* state) {
*state = command_buffer_->Flush(put_offset);
}
void GpuCommandBufferStub::OnAsyncFlush(int32 put_offset) {
gpu::CommandBuffer::State state = command_buffer_->Flush(put_offset);
Send(new GpuCommandBufferMsg_UpdateState(route_id_, state));
}
void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size, int32* id) {
*id = command_buffer_->CreateTransferBuffer(size);
}
void GpuCommandBufferStub::OnDestroyTransferBuffer(int32 id) {
command_buffer_->DestroyTransferBuffer(id);
}
void GpuCommandBufferStub::OnGetTransferBuffer(
int32 id,
base::SharedMemoryHandle* transfer_buffer,
uint32* size) {
*transfer_buffer = base::SharedMemoryHandle();
*size = 0;
Buffer buffer = command_buffer_->GetTransferBuffer(id);
if (buffer.shared_memory) {
// Assume service is responsible for duplicating the handle to the calling
// process.
buffer.shared_memory->ShareToProcess(channel_->renderer_handle(),
transfer_buffer);
*size = buffer.shared_memory->max_size();
}
}
void GpuCommandBufferStub::OnResizeOffscreenFrameBuffer(const gfx::Size& size) {
processor_->ResizeOffscreenFrameBuffer(size);
}
#endif // ENABLE_GPU
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// See the corresponding header file for description of the functions in this
// file.
#include "chrome/installer/util/install_util.h"
#include <shellapi.h>
#include <shlobj.h>
#include <algorithm>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/registry.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"
bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
const std::wstring& params,
DWORD* exit_code) {
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = L"runas";
info.lpFile = exe.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
if (::ShellExecuteEx(&info) == FALSE)
return false;
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (!::GetExitCodeProcess(info.hProcess, &ret_val))
return false;
if (exit_code)
*exit_code = ret_val;
return true;
}
std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
RegKey key(root, dist->GetUninstallRegPath().c_str());
std::wstring uninstall_cmd;
key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
return uninstall_cmd;
}
installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
RegKey key;
std::wstring version_str;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
!key.ReadValue(google_update::kRegVersionField, &version_str)) {
LOG(INFO) << "No existing Chrome install found.";
key.Close();
return NULL;
}
key.Close();
LOG(INFO) << "Existing Chrome version found " << version_str;
return installer::Version::GetVersionFromString(version_str);
}
bool InstallUtil::IsOSSupported() {
int major, minor;
win_util::WinVersion version = win_util::GetWinVersion();
win_util::GetServicePackLevel(&major, &minor);
// We do not support Win2K or older, or XP without service pack 1.
LOG(INFO) << "Windows Version: " << version
<< ", Service Pack: " << major << "." << minor;
if ((version > win_util::WINVERSION_XP) ||
(version == win_util::WINVERSION_XP && major >= 1)) {
return true;
}
return false;
}
void InstallUtil::WriteInstallerResult(bool system_install,
installer_util::InstallStatus status,
int string_resource_id,
const std::wstring* const launch_cmd) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
std::wstring key = dist->GetStateKey();
int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
install_list->AddCreateRegKeyWorkItem(root, key);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
installer_result, true);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
status, true);
if (string_resource_id != 0) {
std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
msg, true);
}
// TODO(rahulk) verify that the absence of InstallerSuccessLaunchCmdLine
// for non-system installs does not break the gcapi.dll.
if ((launch_cmd != NULL) && system_install) {
install_list->AddSetRegValueWorkItem(root, key,
L"InstallerSuccessLaunchCmdLine",
*launch_cmd, true);
}
if (!install_list->Do())
LOG(ERROR) << "Failed to record installer error information in registry.";
}
bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
wchar_t program_files_path[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
SHGFP_TYPE_CURRENT, program_files_path))) {
return !StartsWith(exe_path, program_files_path, false);
} else {
NOTREACHED();
}
return true;
}
bool InstallUtil::BuildDLLRegistrationList(const std::wstring& install_path,
const wchar_t** const dll_names,
int dll_names_count,
bool do_register,
WorkItemList* registration_list) {
DCHECK(NULL != registration_list);
bool success = true;
for (int i = 0; i < dll_names_count; i++) {
std::wstring dll_file_path(install_path);
file_util::AppendToPath(&dll_file_path, dll_names[i]);
success = registration_list->AddSelfRegWorkItem(dll_file_path,
do_register) && success;
}
return (dll_names_count > 0) && success;
}
<commit_msg>Roll back double launch of chrome fix<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// See the corresponding header file for description of the functions in this
// file.
#include "chrome/installer/util/install_util.h"
#include <shellapi.h>
#include <shlobj.h>
#include <algorithm>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/registry.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"
bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
const std::wstring& params,
DWORD* exit_code) {
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = L"runas";
info.lpFile = exe.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
if (::ShellExecuteEx(&info) == FALSE)
return false;
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (!::GetExitCodeProcess(info.hProcess, &ret_val))
return false;
if (exit_code)
*exit_code = ret_val;
return true;
}
std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
RegKey key(root, dist->GetUninstallRegPath().c_str());
std::wstring uninstall_cmd;
key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
return uninstall_cmd;
}
installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
RegKey key;
std::wstring version_str;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
!key.ReadValue(google_update::kRegVersionField, &version_str)) {
LOG(INFO) << "No existing Chrome install found.";
key.Close();
return NULL;
}
key.Close();
LOG(INFO) << "Existing Chrome version found " << version_str;
return installer::Version::GetVersionFromString(version_str);
}
bool InstallUtil::IsOSSupported() {
int major, minor;
win_util::WinVersion version = win_util::GetWinVersion();
win_util::GetServicePackLevel(&major, &minor);
// We do not support Win2K or older, or XP without service pack 1.
LOG(INFO) << "Windows Version: " << version
<< ", Service Pack: " << major << "." << minor;
if ((version > win_util::WINVERSION_XP) ||
(version == win_util::WINVERSION_XP && major >= 1)) {
return true;
}
return false;
}
void InstallUtil::WriteInstallerResult(bool system_install,
installer_util::InstallStatus status,
int string_resource_id,
const std::wstring* const launch_cmd) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
std::wstring key = dist->GetStateKey();
int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
install_list->AddCreateRegKeyWorkItem(root, key);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
installer_result, true);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
status, true);
if (string_resource_id != 0) {
std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
msg, true);
}
if (launch_cmd != NULL) {
install_list->AddSetRegValueWorkItem(root, key,
L"InstallerSuccessLaunchCmdLine",
*launch_cmd, true);
}
if (!install_list->Do())
LOG(ERROR) << "Failed to record installer error information in registry.";
}
bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
wchar_t program_files_path[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
SHGFP_TYPE_CURRENT, program_files_path))) {
return !StartsWith(exe_path, program_files_path, false);
} else {
NOTREACHED();
}
return true;
}
bool InstallUtil::BuildDLLRegistrationList(const std::wstring& install_path,
const wchar_t** const dll_names,
int dll_names_count,
bool do_register,
WorkItemList* registration_list) {
DCHECK(NULL != registration_list);
bool success = true;
for (int i = 0; i < dll_names_count; i++) {
std::wstring dll_file_path(install_path);
file_util::AppendToPath(&dll_file_path, dll_names[i]);
success = registration_list->AddSelfRegWorkItem(dll_file_path,
do_register) && success;
}
return (dll_names_count > 0) && success;
}
<|endoftext|> |
<commit_before>/* Kernel modules can handle sub-microsecond interrupts: http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond
cat /proc/timer_list indicates that high-res timer (hrtimer) resolution is actually 1 ns
hrtimer is available to userspace programs. http://elinux.org/High_Resolution_Timers
Or is it kernel modules? http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond
hrtimers are now used in Posix timers and nanosleep and itimers: http://lwn.net/Articles/168399/
https://www.kernel.org/doc/Documentation/timers/hrtimers.txt
Distributions for testSleepPrecision() @ 1/2 second:
Ubuntu Laptop (40 samples): mean: 206546.75 ns, sd: 40484.71056 ns, about 40 uSec
Raspberry Pi (40 samples): mean: 107167.375 ns, sd: 8504.03636 ns, about 8.5 uSec
What precision is needed?
Aiming for 100 mm/sec extrusion. Assume 10 steps per mm, then 1000 steps/sec = 1 step per 1000 uSec.
Distributions for testSleepAndSpinPrecision() @ 1/2 second:
Ubuntu Laptop (40 samples, 240000 ns buffer): mean: 2784.875 ns, sd: 7604.23667 ns (multiple outliers)
Raspberry Pi (40 samples, 130000 ns buffer): mean: 2315.925 ns, sd: 9485.23442 ns (14 ns w/o the outlier)
Raspberry Pi (40 samples, 130000 ns buffer, nice: -10): mean: 1911.775, sd: 8231.99072
Raspberry Pi (40 samples, 130000 ns buffer, nice: -20): mean: 388.525, sd: 1745.81225 (repeatable thrice to within sd=2500 ns)
RPi appears to have resolution of 1 uSec (samples looked like 5 4 3 2 1 0 999 998 997 ...)
Can use Linux process "niceness"; -20 for most priority, +19 for least.
*/
#include <time.h>
#include <stdio.h>
long avgCostOfGetTime;
timespec* timespec_add(struct timespec * tv_a, const struct timespec * tv_b) { //a is modified
tv_a->tv_sec += tv_b->tv_sec;
tv_a->tv_nsec += tv_b->tv_nsec;
if (tv_a->tv_nsec > 999999999) {
tv_a->tv_sec += 1;
tv_a->tv_nsec -= 1000000000;
}
return tv_a;
}
timespec* timespec_sub(struct timespec * tv_a, const struct timespec * tv_b) { //a is modified
tv_a->tv_sec -= tv_b->tv_sec;
tv_a->tv_nsec -= tv_b->tv_nsec;
if (tv_a->tv_nsec < 0) {
tv_a->tv_sec -= 1;
tv_a->tv_nsec += 1000000000;
}
return tv_a;
}
long timespec_to_nano(struct timespec *t) {
return (long)t->tv_sec * 1000000000 + (long)t->tv_nsec;
}
void getClockInfo() {
clockid_t types[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, (clockid_t)-1};
struct timespec spec;
for (int i=0; types[i] != (clockid_t)-1; i++) {
if (clock_getres( types[i], &spec ) != 0) {
printf("Timer %d not supported.\n", types[i]);
} else {
printf("Timer: %d, Seconds: %ld Nanos: %ld\n", i, spec.tv_sec, spec.tv_nsec);
}
}
}
void logTime(int clockId) {
struct timespec time;
clock_gettime(clockId, &time);
printf("Time: %lu.%lu\n", time.tv_sec, time.tv_nsec);
}
void testNanoSleep() {
struct timespec tim, tim2;
tim.tv_sec = 0;
tim.tv_nsec = 500000000;
logTime(0);
nanosleep(&tim, &tim2);
logTime(0);
}
long testSleepPrecision() {
struct timespec sleepDur, remaining, startTime, endTime;
sleepDur.tv_sec = 0;
sleepDur.tv_nsec = 500000000;
clock_gettime(0, &startTime);
nanosleep(&sleepDur, &remaining);
clock_gettime(0, &endTime);
//endTime.tv_sec -= startTime.tv_sec;
timespec_sub(&endTime, &sleepDur);
timespec_sub(&endTime, &startTime);
return timespec_to_nano(&endTime);
//return (endTime.tv_sec - sleepDur.tv_sec)*1000000000 + (endTime.tv_nsec - startTime.tv_nsec - sleepDur.tv_nsec);
}
long testSleepAndSpinPrecision() {
struct timespec sleepDur, remaining, startTime, curTime, desiredEndTime, sleepPad;
sleepDur.tv_sec = 0;
sleepDur.tv_nsec = 500000000;
sleepPad.tv_sec = 0;
sleepPad.tv_nsec = 220000;
//endTime.tv_sec = 0;
//endTime.tv_nsec = 0;
clock_gettime(0, &startTime);
desiredEndTime.tv_sec = startTime.tv_sec;
desiredEndTime.tv_nsec = startTime.tv_nsec;
timespec_add(&desiredEndTime, &sleepDur);
timespec_sub(&sleepDur, &sleepPad);
nanosleep(&sleepDur, &remaining);
//while (endTime.tv_sec < desiredEndTime.tv_sec || endTime.tv_nsec < desiredEndTime.tv_nsec) {
do {
clock_gettime(0, &curTime);
} while (timespec_to_nano(timespec_sub(&curTime, &desiredEndTime)) < -avgCostOfGetTime);
//timespec_sub(&endTime, &desiredEndTime);
//return timespec_to_nano(&endTime);
return timespec_to_nano(&curTime);
}
long costOfGetTime() {
struct timespec t1, t2;
clock_gettime(0, &t1);
clock_gettime(0, &t2);
timespec_sub(&t2, &t1);
return timespec_to_nano(&t2);
}
long getAvgCostOfGetTime(int n=40) {
long sum = 0;
for (int i=0; i<n; ++i) {
sum += costOfGetTime();
}
return sum/n;
}
int main(int argc, char** argv) {
struct timespec a, b;
a.tv_sec = 0;
a.tv_nsec = 1;
b.tv_sec = 0;
b.tv_nsec = 2;
printf("Test timespec_sub: %ld\n", timespec_to_nano(timespec_sub(&a, &b)));
getClockInfo();
avgCostOfGetTime = getAvgCostOfGetTime();
printf("Average cost of gettime: %lu\n", avgCostOfGetTime);
testNanoSleep();
for (int i=0; i<40; ++i) {
//printf("%ld, \n", testSleepPrecision());
printf("%ld, \n", testSleepAndSpinPrecision());
//printf("%ld, \n", costOfGetTime());
}
}
<commit_msg>Forgot factor of 0.5 for avgCostOfGetTime<commit_after>/* Kernel modules can handle sub-microsecond interrupts: http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond
cat /proc/timer_list indicates that high-res timer (hrtimer) resolution is actually 1 ns
hrtimer is available to userspace programs. http://elinux.org/High_Resolution_Timers
Or is it kernel modules? http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond
hrtimers are now used in Posix timers and nanosleep and itimers: http://lwn.net/Articles/168399/
https://www.kernel.org/doc/Documentation/timers/hrtimers.txt
Distributions for testSleepPrecision() @ 1/2 second:
Ubuntu Laptop (40 samples): mean: 206546.75 ns, sd: 40484.71056 ns, about 40 uSec
Raspberry Pi (40 samples): mean: 107167.375 ns, sd: 8504.03636 ns, about 8.5 uSec
What precision is needed?
Aiming for 100 mm/sec extrusion. Assume 10 steps per mm, then 1000 steps/sec = 1 step per 1000 uSec.
Distributions for testSleepAndSpinPrecision() @ 1/2 second:
Ubuntu Laptop (40 samples, 240000 ns buffer): mean: 2784.875 ns, sd: 7604.23667 ns (multiple outliers)
Raspberry Pi (40 samples, 130000 ns buffer): mean: 2315.925 ns, sd: 9485.23442 ns (14 ns w/o the outlier)
Raspberry Pi (40 samples, 130000 ns buffer, nice: -10): mean: 1911.775, sd: 8231.99072
Raspberry Pi (40 samples, 130000 ns buffer, nice: -20): mean: 388.525, sd: 1745.81225 (repeatable thrice to within sd=2500 ns)
RPi appears to take 1 uSec to gettime. (samples looked like 5 4 3 2 1 0 999 998 997 ...)
Can use Linux process "niceness"; -20 for most priority, +19 for least.
*/
#include <time.h>
#include <stdio.h>
long avgCostOfGetTime;
timespec* timespec_add(struct timespec * tv_a, const struct timespec * tv_b) { //a is modified
tv_a->tv_sec += tv_b->tv_sec;
tv_a->tv_nsec += tv_b->tv_nsec;
if (tv_a->tv_nsec > 999999999) {
tv_a->tv_sec += 1;
tv_a->tv_nsec -= 1000000000;
}
return tv_a;
}
timespec* timespec_sub(struct timespec * tv_a, const struct timespec * tv_b) { //a is modified
tv_a->tv_sec -= tv_b->tv_sec;
tv_a->tv_nsec -= tv_b->tv_nsec;
if (tv_a->tv_nsec < 0) {
tv_a->tv_sec -= 1;
tv_a->tv_nsec += 1000000000;
}
return tv_a;
}
long timespec_to_nano(struct timespec *t) {
return (long)t->tv_sec * 1000000000 + (long)t->tv_nsec;
}
void getClockInfo() {
clockid_t types[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, (clockid_t)-1};
struct timespec spec;
for (int i=0; types[i] != (clockid_t)-1; i++) {
if (clock_getres( types[i], &spec ) != 0) {
printf("Timer %d not supported.\n", types[i]);
} else {
printf("Timer: %d, Seconds: %ld Nanos: %ld\n", i, spec.tv_sec, spec.tv_nsec);
}
}
}
void logTime(int clockId) {
struct timespec time;
clock_gettime(clockId, &time);
printf("Time: %lu.%lu\n", time.tv_sec, time.tv_nsec);
}
void testNanoSleep() {
struct timespec tim, tim2;
tim.tv_sec = 0;
tim.tv_nsec = 500000000;
logTime(0);
nanosleep(&tim, &tim2);
logTime(0);
}
long testSleepPrecision() {
struct timespec sleepDur, remaining, startTime, endTime;
sleepDur.tv_sec = 0;
sleepDur.tv_nsec = 500000000;
clock_gettime(0, &startTime);
nanosleep(&sleepDur, &remaining);
clock_gettime(0, &endTime);
//endTime.tv_sec -= startTime.tv_sec;
timespec_sub(&endTime, &sleepDur);
timespec_sub(&endTime, &startTime);
return timespec_to_nano(&endTime);
//return (endTime.tv_sec - sleepDur.tv_sec)*1000000000 + (endTime.tv_nsec - startTime.tv_nsec - sleepDur.tv_nsec);
}
long testSleepAndSpinPrecision() {
struct timespec sleepDur, remaining, startTime, curTime, desiredEndTime, sleepPad;
sleepDur.tv_sec = 0;
sleepDur.tv_nsec = 500000000;
sleepPad.tv_sec = 0;
sleepPad.tv_nsec = 220000;
//endTime.tv_sec = 0;
//endTime.tv_nsec = 0;
clock_gettime(0, &startTime);
desiredEndTime.tv_sec = startTime.tv_sec;
desiredEndTime.tv_nsec = startTime.tv_nsec;
timespec_add(&desiredEndTime, &sleepDur);
timespec_sub(&sleepDur, &sleepPad);
nanosleep(&sleepDur, &remaining);
//while (endTime.tv_sec < desiredEndTime.tv_sec || endTime.tv_nsec < desiredEndTime.tv_nsec) {
do {
clock_gettime(0, &curTime);
} while (timespec_to_nano(timespec_sub(&curTime, &desiredEndTime)) < -avgCostOfGetTime/2);
//timespec_sub(&endTime, &desiredEndTime);
//return timespec_to_nano(&endTime);
return timespec_to_nano(&curTime);
}
long costOfGetTime() {
struct timespec t1, t2;
clock_gettime(0, &t1);
clock_gettime(0, &t2);
timespec_sub(&t2, &t1);
return timespec_to_nano(&t2);
}
long getAvgCostOfGetTime(int n=40) {
long sum = 0;
for (int i=0; i<n; ++i) {
sum += costOfGetTime();
}
return sum/n;
}
int main(int argc, char** argv) {
struct timespec a, b;
a.tv_sec = 0;
a.tv_nsec = 1;
b.tv_sec = 0;
b.tv_nsec = 2;
printf("Test timespec_sub: %ld\n", timespec_to_nano(timespec_sub(&a, &b)));
getClockInfo();
avgCostOfGetTime = getAvgCostOfGetTime();
printf("Average cost of gettime: %lu\n", avgCostOfGetTime);
testNanoSleep();
for (int i=0; i<40; ++i) {
//printf("%ld, \n", testSleepPrecision());
printf("%ld, \n", testSleepAndSpinPrecision());
//printf("%ld, \n", costOfGetTime());
}
}
<|endoftext|> |
<commit_before>#pragma once
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#include "php.h"
#define PHP_XHP_VERSION "1.3.0"
#define PHP_XHP_EXTNAME "xhp"
extern zend_module_entry xhp_module_entry;
#define phpext_xhp &xhp_module_entry
<commit_msg>Bump to 1.3.1<commit_after>#pragma once
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#include "php.h"
#define PHP_XHP_VERSION "1.3.1"
#define PHP_XHP_EXTNAME "xhp"
extern zend_module_entry xhp_module_entry;
#define phpext_xhp &xhp_module_entry
<|endoftext|> |
<commit_before>#include "genesis.h"
Genesis::Genesis() : map(28) {
engine.init(TITLE, WIDTH, HEIGHT, 0);
engine.bypassSplash(4231998);
running=true;
vector<Tile> tmp1, tmp2;
tmp1 = map.loadMaps("wall", "res/avery.wall", "res/wall.bmp", engine.renderScreen(), TILE_SIZE, TILE_SIZE, 1, 7);
tmp2 = map.loadMaps("blocks", "res/avery.map", "res/blocks.bmp", engine.renderScreen(), TILE_SIZE, TILE_SIZE, 1, 22);
engine.setBackground("res/bkg.bmp");
player.setImage("res/player.bmp", engine.renderScreen());
player.setSource(0, 0, TILE_SIZE, 45);
player.center(WIDTH, HEIGHT);
engine.setColor(0x9f, 0x9f, 0x9f);
map.setWindowSize(WIDTH, HEIGHT);
map.centerCamera(50);
map.centerLens(50);
engine.preLoop();
input.reset();
map.setSolid(1);
//map.setAng(45);
speed = 5;
start();
}
Genesis::~Genesis() {
engine.deconstruct();
}
void Genesis::start() {
while(running) {
checkInput();
engine.preLoop();
draw();
engine.endLoop();
}
}
void Genesis::draw() {
engine.pushToScreen(background);
tiles = map.getTilesToRender();
for(int i = 0; i<tiles.size(); i++) { tiles[i].setAng(45); engine.pushToScreen(tiles[i]); }// player=colCheck.calibrate(player, tiles[i]);}
engine.pushToScreen(player);
}
void Genesis::checkInput() {
input.logPress();
if(input.checkKey(input.right)) {
player = map.move(speed, 0, player);
}
if(input.checkKey(input.left)) {
player = map.move(-speed, 0, player);
}
if(input.checkKey(input.up)) {
player = map.move(0, speed, player);
}
if(input.checkKey(input.down)) {
player = map.move(0, -speed, player);
}
if(input.checkKey(input.quit)) { running=false; }
if(input.checkKey(input.esc)) { running=false; }
}
<commit_msg>currently working on collision and angles<commit_after>#include "genesis.h"
Genesis::Genesis() : map(28) {
engine.init(TITLE, WIDTH, HEIGHT, 0);
engine.bypassSplash(4231998);
running=true;
vector<Tile> tmp1, tmp2;
tmp1 = map.loadMaps("wall", "res/avery.wall", "res/wall.bmp", engine.renderScreen(), TILE_SIZE, TILE_SIZE, 1, 7);
tmp2 = map.loadMaps("blocks", "res/avery.map", "res/blocks.bmp", engine.renderScreen(), TILE_SIZE, TILE_SIZE, 1, 22);
map.setPassable(3, 4, 2);
map.setPassable(8, 10, 2);
map.setPassable(13, 2);
map.setPassable(15, 2);
map.setPassable(17, 2);
map.setPassable(19, 2);
map.setPassable(21, 2);
engine.setBackground("res/bkg.bmp");
player.setImage("res/player.bmp", engine.renderScreen());
player.setSource(0, 0, TILE_SIZE, 45);
player.center(WIDTH, HEIGHT);
engine.setColor(0x9f, 0x9f, 0x9f);
map.setWindowSize(WIDTH, HEIGHT);
map.centerCamera(50);
map.centerLens(50);
engine.preLoop();
input.reset();
map.setSolid(1);
map.setAng(45);
speed = 5;
start();
}
Genesis::~Genesis() {
engine.deconstruct();
}
void Genesis::start() {
while(running) {
checkInput();
engine.preLoop();
draw();
engine.endLoop();
}
}
void Genesis::draw() {
engine.pushToScreen(background);
tiles = map.getTilesToRender();
for(int i = 0; i<tiles.size(); i++) {engine.pushToScreen(tiles[i]); player=colCheck.calibrate(player, tiles[i]);}
engine.pushToScreen(player);
}
void Genesis::checkInput() {
input.logPress();
if(input.checkKey(input.right)) {
player = map.move(speed, 0, player);
}
if(input.checkKey(input.left)) {
player = map.move(-speed, 0, player);
}
if(input.checkKey(input.up)) {
player = map.move(0, speed, player);
}
if(input.checkKey(input.down)) {
player = map.move(0, -speed, player);
}
if(input.checkKey(input.quit)) { running=false; }
if(input.checkKey(input.esc)) { running=false; }
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
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 VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3519
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3519 to 3520<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
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 VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3520
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
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 VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3466
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3466 to 3467<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
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 VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3467
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <string.h>
#include <round/Round.h>
#include "RoundTest.h"
#include "TestNode.h"
using namespace std;
using namespace Round;
BOOST_AUTO_TEST_SUITE(node)
BOOST_AUTO_TEST_CASE(LocalNodeEqualTest) {
TestLocalNode localNode01("192.168.0.1", 80);
TestLocalNode localNode02("192.168.0.1", 80);
TestLocalNode localNode03("192.168.0.2", 80);
TestLocalNode localNode04("192.168.0.1", 81);
TestLocalNode localNode05("192.168.0.2", 81);
BOOST_CHECK(localNode01.equals(&localNode01));
BOOST_CHECK(localNode01.equals(&localNode02));
BOOST_CHECK(!localNode01.equals(&localNode03));
BOOST_CHECK(!localNode01.equals(&localNode04));
BOOST_CHECK(!localNode01.equals(&localNode05));
}
BOOST_AUTO_TEST_CASE(LocalNodeBasisMethodTest) {
TestLocalNode node;
Error err;
std::string clusterName;
BOOST_CHECK(node.getClusterName(&clusterName, &err));
BOOST_CHECK(0 < clusterName.length());
}
BOOST_AUTO_TEST_CASE(LocalNodConfigGraphTest) {
LocalNodeConfig nodeConfig;
Error error;
std::string retStringValue;
int retIntValue;
const std::string testHttpAddr = "testAddr";
// LocalNodeConfig::getHttpdBindAddress() returns a default value when the value is not specified.
//BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindAddress(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setHttpdBindAddress(testHttpAddr));
BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindAddress(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testHttpAddr, retStringValue);
const int testHttpdPort = 8483;
BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindPort(&retIntValue, &error), false);
BOOST_CHECK(nodeConfig.setHttpdBindPort(testHttpdPort));
BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindPort(&retIntValue, &error), true);
BOOST_CHECK_EQUAL(testHttpdPort, retIntValue);
const std::string testCluster = "testCluster";
BOOST_CHECK_EQUAL(nodeConfig.getCluster(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setCluster(testCluster));
BOOST_CHECK_EQUAL(nodeConfig.getCluster(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testCluster, retStringValue);
const std::string testDatabaseDir = "testDir";
BOOST_CHECK_EQUAL(nodeConfig.getDatabaseDirectory(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setDatabaseDirectory(testDatabaseDir));
BOOST_CHECK_EQUAL(nodeConfig.getDatabaseDirectory(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testDatabaseDir, retStringValue);
const std::string testLogFilename = "testLogFilename";
BOOST_CHECK_EQUAL(nodeConfig.getLogFilename(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setLogFilename(testLogFilename));
BOOST_CHECK_EQUAL(nodeConfig.getLogFilename(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testLogFilename, retStringValue);
const std::string testErrorLogFilename = "testErrorFilename";
BOOST_CHECK_EQUAL(nodeConfig.getErrorLogFilename(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setErrorLogFilename(testErrorLogFilename));
BOOST_CHECK_EQUAL(nodeConfig.getErrorLogFilename(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testErrorLogFilename, retStringValue);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(rpc)
BOOST_AUTO_TEST_CASE(LocalNodeScriptManagerTest) {
TestLocalNode node;
NodeTestController nodeTestController;
nodeTestController.runScriptManagerTest(&node);
}
BOOST_AUTO_TEST_CASE(LocalNodeSystemMethodTest) {
TestLocalNode node;
NodeTestController nodeTestController;
nodeTestController.runSystemMethodTest(&node);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>* Removed LocalNodeBasisMethodTest.<commit_after>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <string.h>
#include <round/Round.h>
#include "RoundTest.h"
#include "TestNode.h"
using namespace std;
using namespace Round;
BOOST_AUTO_TEST_SUITE(node)
BOOST_AUTO_TEST_CASE(LocalNodeEqualTest) {
TestLocalNode localNode01("192.168.0.1", 80);
TestLocalNode localNode02("192.168.0.1", 80);
TestLocalNode localNode03("192.168.0.2", 80);
TestLocalNode localNode04("192.168.0.1", 81);
TestLocalNode localNode05("192.168.0.2", 81);
BOOST_CHECK(localNode01.equals(&localNode01));
BOOST_CHECK(localNode01.equals(&localNode02));
BOOST_CHECK(!localNode01.equals(&localNode03));
BOOST_CHECK(!localNode01.equals(&localNode04));
BOOST_CHECK(!localNode01.equals(&localNode05));
}
BOOST_AUTO_TEST_CASE(LocalNodConfigGraphTest) {
LocalNodeConfig nodeConfig;
Error error;
std::string retStringValue;
int retIntValue;
const std::string testHttpAddr = "testAddr";
// LocalNodeConfig::getHttpdBindAddress() returns a default value when the value is not specified.
//BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindAddress(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setHttpdBindAddress(testHttpAddr));
BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindAddress(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testHttpAddr, retStringValue);
const int testHttpdPort = 8483;
BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindPort(&retIntValue, &error), false);
BOOST_CHECK(nodeConfig.setHttpdBindPort(testHttpdPort));
BOOST_CHECK_EQUAL(nodeConfig.getHttpdBindPort(&retIntValue, &error), true);
BOOST_CHECK_EQUAL(testHttpdPort, retIntValue);
const std::string testCluster = "testCluster";
BOOST_CHECK_EQUAL(nodeConfig.getCluster(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setCluster(testCluster));
BOOST_CHECK_EQUAL(nodeConfig.getCluster(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testCluster, retStringValue);
const std::string testDatabaseDir = "testDir";
BOOST_CHECK_EQUAL(nodeConfig.getDatabaseDirectory(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setDatabaseDirectory(testDatabaseDir));
BOOST_CHECK_EQUAL(nodeConfig.getDatabaseDirectory(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testDatabaseDir, retStringValue);
const std::string testLogFilename = "testLogFilename";
BOOST_CHECK_EQUAL(nodeConfig.getLogFilename(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setLogFilename(testLogFilename));
BOOST_CHECK_EQUAL(nodeConfig.getLogFilename(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testLogFilename, retStringValue);
const std::string testErrorLogFilename = "testErrorFilename";
BOOST_CHECK_EQUAL(nodeConfig.getErrorLogFilename(&retStringValue, &error), false);
BOOST_CHECK(nodeConfig.setErrorLogFilename(testErrorLogFilename));
BOOST_CHECK_EQUAL(nodeConfig.getErrorLogFilename(&retStringValue, &error), true);
BOOST_CHECK_EQUAL(testErrorLogFilename, retStringValue);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(rpc)
BOOST_AUTO_TEST_CASE(LocalNodeScriptManagerTest) {
TestLocalNode node;
NodeTestController nodeTestController;
nodeTestController.runScriptManagerTest(&node);
}
BOOST_AUTO_TEST_CASE(LocalNodeSystemMethodTest) {
TestLocalNode node;
NodeTestController nodeTestController;
nodeTestController.runSystemMethodTest(&node);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "fakevimhandler.h"
#include <QDebug>
#include <QApplication>
#include <QMainWindow>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextEdit>
using namespace FakeVim::Internal;
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
: QObject(parent), m_widget(widget), m_mainWindow(mw)
{}
public slots:
void changeSelection(const QList<QTextEdit::ExtraSelection> &s)
{
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget))
ed->setExtraSelections(s);
else if (QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget))
ed->setExtraSelections(s);
}
void changeStatusData(const QString &info)
{
m_statusData = info;
updateStatusBar();
}
void changeStatusMessage(const QString &contents, int cursorPos)
{
m_statusMessage = cursorPos == -1 ? contents
: contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
updateStatusBar();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_widget, "Information", info);
}
void updateStatusBar()
{
int slack = 80 - m_statusMessage.size() - m_statusData.size();
QString msg = m_statusMessage + QString(slack, QChar(' ')) + m_statusData;
m_mainWindow->statusBar()->showMessage(msg);
}
private:
QWidget *m_widget;
QMainWindow *m_mainWindow;
QString m_statusMessage;
QString m_statusData;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList args = app.arguments();
(void) args.takeFirst();
QWidget *widget = 0;
QString title;
bool usePlainTextEdit = args.size() < 2;
if (usePlainTextEdit) {
QPlainTextEdit *w = new QPlainTextEdit;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
title = "PlainTextEdit";
widget = w;
} else {
QTextEdit *w = new QTextEdit;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
title = "TextEdit";
widget = w;
}
widget->setObjectName("Editor");
//widget->resize(450, 350);
widget->setFocus();
QMainWindow mw;
Proxy proxy(widget, &mw);
FakeVimHandler handler(widget, 0);
mw.setWindowTitle("Fakevim (" + title + ")");
mw.setCentralWidget(widget);
mw.resize(600, 650);
mw.move(0, 0);
mw.show();
QFont font = widget->font();
//: -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1
//font.setFamily("Misc");
font.setFamily("Monospace");
//font.setStretch(QFont::SemiCondensed);
widget->setFont(font);
mw.statusBar()->setFont(font);
QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int)),
&proxy, SLOT(changeStatusMessage(QString,int)));
//QObject::connect(&handler, SIGNAL(quitRequested(bool)),
// &app, SLOT(quit()));
QObject::connect(&handler,
SIGNAL(selectionChanged(QList<QTextEdit::ExtraSelection>)),
&proxy, SLOT(changeSelection(QList<QTextEdit::ExtraSelection>)));
QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)),
&proxy, SLOT(changeExtraInformation(QString)));
QObject::connect(&handler, SIGNAL(statusDataChanged(QString)),
&proxy, SLOT(changeStatusData(QString)));
theFakeVimSetting(ConfigUseFakeVim)->setValue(true);
theFakeVimSetting(ConfigShiftWidth)->setValue(8);
theFakeVimSetting(ConfigTabStop)->setValue(8);
theFakeVimSetting(ConfigAutoIndent)->setValue(true);
theFakeVimSetting(ConfigIsKeyword)->setValue("@,48-57,_,192-255,a-z,A-Z");
handler.installEventFilter();
handler.setupWidget();
if (args.size() >= 1)
handler.handleCommand("r " + args.at(0));
return app.exec();
}
#include "main.moc"
<commit_msg>tests: fakevim: fix building with QT_NO_CAST_FROM_ASCII<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "fakevimhandler.h"
#include <QDebug>
#include <QApplication>
#include <QMainWindow>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextEdit>
using namespace FakeVim::Internal;
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
: QObject(parent), m_widget(widget), m_mainWindow(mw)
{}
public slots:
void changeSelection(const QList<QTextEdit::ExtraSelection> &s)
{
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget))
ed->setExtraSelections(s);
else if (QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget))
ed->setExtraSelections(s);
}
void changeStatusData(const QString &info)
{
m_statusData = info;
updateStatusBar();
}
void changeStatusMessage(const QString &contents, int cursorPos)
{
m_statusMessage = cursorPos == -1 ? contents
: contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
updateStatusBar();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_widget, tr("Information"), info);
}
void updateStatusBar()
{
int slack = 80 - m_statusMessage.size() - m_statusData.size();
QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
m_mainWindow->statusBar()->showMessage(msg);
}
private:
QWidget *m_widget;
QMainWindow *m_mainWindow;
QString m_statusMessage;
QString m_statusData;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList args = app.arguments();
(void) args.takeFirst();
QWidget *widget = 0;
QString title;
bool usePlainTextEdit = args.size() < 2;
if (usePlainTextEdit) {
QPlainTextEdit *w = new QPlainTextEdit;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
title = QLatin1String("PlainTextEdit");
widget = w;
} else {
QTextEdit *w = new QTextEdit;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
title = QLatin1String("TextEdit");
widget = w;
}
widget->setObjectName(QLatin1String("Editor"));
//widget->resize(450, 350);
widget->setFocus();
QMainWindow mw;
Proxy proxy(widget, &mw);
FakeVimHandler handler(widget, 0);
mw.setWindowTitle(QLatin1String("Fakevim (") + title + QLatin1Char(')'));
mw.setCentralWidget(widget);
mw.resize(600, 650);
mw.move(0, 0);
mw.show();
QFont font = widget->font();
//: -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1
//font.setFamily("Misc");
font.setFamily(QLatin1String("Monospace"));
//font.setStretch(QFont::SemiCondensed);
widget->setFont(font);
mw.statusBar()->setFont(font);
QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int)),
&proxy, SLOT(changeStatusMessage(QString,int)));
//QObject::connect(&handler, SIGNAL(quitRequested(bool)),
// &app, SLOT(quit()));
QObject::connect(&handler,
SIGNAL(selectionChanged(QList<QTextEdit::ExtraSelection>)),
&proxy, SLOT(changeSelection(QList<QTextEdit::ExtraSelection>)));
QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)),
&proxy, SLOT(changeExtraInformation(QString)));
QObject::connect(&handler, SIGNAL(statusDataChanged(QString)),
&proxy, SLOT(changeStatusData(QString)));
theFakeVimSetting(ConfigUseFakeVim)->setValue(true);
theFakeVimSetting(ConfigShiftWidth)->setValue(8);
theFakeVimSetting(ConfigTabStop)->setValue(8);
theFakeVimSetting(ConfigAutoIndent)->setValue(true);
theFakeVimSetting(ConfigIsKeyword)->setValue(QLatin1String("@,48-57,_,192-255,a-z,A-Z"));
handler.installEventFilter();
handler.setupWidget();
if (args.size() >= 1)
handler.handleCommand(QLatin1String("r ") + args.at(0));
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>//---------------------------- tensor_base.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2010 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- tensor_base.cc ---------------------------
// check serialization for Tensor<1,dim>
#include "../tests.h"
#include <base/tensor.h>
#include <base/logstream.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <sstream>
#include <fstream>
#include <iomanip>
template <typename T>
void verify (const T &t1,
T &t2)
{
// save data to archive
std::ostringstream oss;
{
boost::archive::text_oarchive oa(oss);
oa << t1;
// archive and stream closed when
// destructors are called
}
deallog << oss.str() << std::endl;
// verify correctness of the
// serialization
{
std::istringstream iss(oss.str());
boost::archive::text_iarchive ia(iss);
ia >> t2;
Assert (t1 == t2, ExcInternalError());
}
}
void test ()
{
const unsigned int dim=3;
const unsigned int rank=2;
double a1[3][3] = {{1., 2., 3.},
{4., 5., 6.},
{7., 8., 9.}
};
Tensor<rank,dim> t1(a1);
double a2[3][3] = {{10., 11., 12.},
{13., 14., 15.},
{16., 17., 18.}
};
Tensor<rank,dim> t2(a2);
verify (t1, t2);
}
int main ()
{
std::ofstream logfile("tensor/output");
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test ();
deallog << "OK" << std::endl;
}
<commit_msg>Rather than re-implementing things use them from the common header file.<commit_after>//---------------------------- tensor_base.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2010 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- tensor_base.cc ---------------------------
// check serialization for Tensor<1,dim>
#include "../tests.h"
#include "serialization.h"
#include <base/tensor.h>
#include <base/logstream.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <sstream>
#include <fstream>
#include <iomanip>
void test ()
{
const unsigned int dim=3;
const unsigned int rank=2;
double a1[3][3] = {{1., 2., 3.},
{4., 5., 6.},
{7., 8., 9.}
};
Tensor<rank,dim> t1(a1);
double a2[3][3] = {{10., 11., 12.},
{13., 14., 15.},
{16., 17., 18.}
};
Tensor<rank,dim> t2(a2);
verify (t1, t2);
}
int main ()
{
std::ofstream logfile("tensor/output");
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test ();
deallog << "OK" << std::endl;
}
<|endoftext|> |
<commit_before>// Copyright 2019 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "tcmalloc/cpu_cache.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tcmalloc/common.h"
#include "tcmalloc/internal/util.h"
#include "tcmalloc/parameters.h"
#include "tcmalloc/static_vars.h"
namespace tcmalloc {
namespace {
void* OOMHandler(size_t) { return nullptr; }
TEST(CpuCacheTest, Metadata) {
if (!subtle::percpu::IsFast()) {
return;
}
const int num_cpus = absl::base_internal::NumCPUs();
CPUCache& cache = *Static::cpu_cache();
// Since this test allocates memory, avoid activating the real fast path to
// minimize allocations against the per-CPU cache.
cache.Activate(CPUCache::ActivationMode::FastPathOffTestOnly);
PerCPUMetadataState r = cache.MetadataMemoryUsage();
EXPECT_EQ(r.virtual_size, num_cpus << CPUCache::kPerCpuShift);
if (Parameters::lazy_per_cpu_caches()) {
EXPECT_EQ(r.resident_size, 0);
} else {
EXPECT_EQ(r.resident_size, r.virtual_size);
}
auto count_cores = [&]() {
int populated_cores = 0;
for (int i = 0; i < num_cpus; i++) {
if (cache.HasPopulated(i)) {
populated_cores++;
}
}
return populated_cores;
};
EXPECT_EQ(0, count_cores());
int allowed_cpu_id;
const size_t kSizeClass = 3;
const size_t num_to_move = Static::sizemap()->num_objects_to_move(kSizeClass);
void* ptr;
{
// Restrict this thread to a single core while allocating and processing the
// slow path.
//
// TODO(b/151313823): Without this restriction, we may access--for reading
// only--other slabs if we end up being migrated. These may cause huge
// pages to be faulted for those cores, leading to test flakiness.
allowed_cpu_id = tcmalloc_internal::AllowedCpus()[0];
tcmalloc_internal::ScopedAffinityMask mask(allowed_cpu_id);
ptr = cache.Allocate<OOMHandler>(kSizeClass);
if (mask.Tampered()) {
return;
}
}
EXPECT_NE(ptr, nullptr);
EXPECT_EQ(1, count_cores());
r = cache.MetadataMemoryUsage();
EXPECT_EQ(r.virtual_size, num_cpus << CPUCache::kPerCpuShift);
if (Parameters::lazy_per_cpu_caches()) {
// We expect to fault in a single core, but we may end up faulting an
// entire hugepage worth of memory
const size_t core_slab_size = r.virtual_size / num_cpus;
const size_t upper_bound =
((core_slab_size + kHugePageSize - 1) & ~(kHugePageSize - 1));
// A single core may be less than the full slab (core_slab_size), since we
// do not touch every page within the slab.
EXPECT_GT(r.resident_size, 0);
EXPECT_LE(r.resident_size, upper_bound) << count_cores();
// This test is much more sensitive to implementation details of the per-CPU
// cache. It may need to be updated from time to time. These numbers were
// calculated by MADV_NOHUGEPAGE'ing the memory used for the slab and
// measuring the resident size.
//
// TODO(ckennelly): Allow CPUCache::Activate to accept a specific arena
// allocator, so we can MADV_NOHUGEPAGE the backing store in testing for
// more precise measurements.
switch (CPUCache::kPerCpuShift) {
case 12:
EXPECT_GE(r.resident_size, 4096);
break;
case 18:
EXPECT_GE(r.resident_size, 135168);
break;
default:
ASSUME(false);
break;
};
// Read stats from the CPU caches. This should not impact resident_size.
const size_t max_cpu_cache_size = Parameters::max_per_cpu_cache_size();
size_t total_used_bytes = 0;
for (int cpu = 0; cpu < num_cpus; ++cpu) {
size_t used_bytes = cache.UsedBytes(cpu);
total_used_bytes += used_bytes;
if (cpu == allowed_cpu_id) {
EXPECT_GT(used_bytes, 0);
EXPECT_TRUE(cache.HasPopulated(cpu));
} else {
EXPECT_EQ(used_bytes, 0);
EXPECT_FALSE(cache.HasPopulated(cpu));
}
EXPECT_LE(cache.Unallocated(cpu), max_cpu_cache_size);
}
for (int cl = 0; cl < kNumClasses; ++cl) {
// This is sensitive to the current growth policies of CPUCache. It may
// require updating from time-to-time.
EXPECT_EQ(cache.TotalObjectsOfClass(cl),
(cl == kSizeClass ? num_to_move - 1 : 0))
<< cl;
}
EXPECT_EQ(cache.TotalUsedBytes(), total_used_bytes);
PerCPUMetadataState post_stats = cache.MetadataMemoryUsage();
// Confirm stats are within expected bounds.
EXPECT_GT(post_stats.resident_size, 0);
EXPECT_LE(post_stats.resident_size, upper_bound) << count_cores();
// Confirm stats are unchanged.
EXPECT_EQ(r.resident_size, post_stats.resident_size);
} else {
EXPECT_EQ(r.resident_size, r.virtual_size);
}
// Tear down.
//
// TODO(ckennelly): We're interacting with the real TransferCache.
cache.Deallocate(ptr, kSizeClass);
for (int i = 0; i < num_cpus; i++) {
cache.Reclaim(i);
}
}
} // namespace
} // namespace tcmalloc
<commit_msg>Use vCPU for inspecting populated per-CPU cache.<commit_after>// Copyright 2019 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "tcmalloc/cpu_cache.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tcmalloc/common.h"
#include "tcmalloc/internal/util.h"
#include "tcmalloc/parameters.h"
#include "tcmalloc/static_vars.h"
namespace tcmalloc {
namespace {
void* OOMHandler(size_t) { return nullptr; }
TEST(CpuCacheTest, Metadata) {
if (!subtle::percpu::IsFast()) {
return;
}
const int num_cpus = absl::base_internal::NumCPUs();
CPUCache& cache = *Static::cpu_cache();
// Since this test allocates memory, avoid activating the real fast path to
// minimize allocations against the per-CPU cache.
cache.Activate(CPUCache::ActivationMode::FastPathOffTestOnly);
PerCPUMetadataState r = cache.MetadataMemoryUsage();
EXPECT_EQ(r.virtual_size, num_cpus << CPUCache::kPerCpuShift);
if (Parameters::lazy_per_cpu_caches()) {
EXPECT_EQ(r.resident_size, 0);
} else {
EXPECT_EQ(r.resident_size, r.virtual_size);
}
auto count_cores = [&]() {
int populated_cores = 0;
for (int i = 0; i < num_cpus; i++) {
if (cache.HasPopulated(i)) {
populated_cores++;
}
}
return populated_cores;
};
EXPECT_EQ(0, count_cores());
int allowed_cpu_id;
const size_t kSizeClass = 3;
const size_t num_to_move = Static::sizemap()->num_objects_to_move(kSizeClass);
void* ptr;
{
// Restrict this thread to a single core while allocating and processing the
// slow path.
//
// TODO(b/151313823): Without this restriction, we may access--for reading
// only--other slabs if we end up being migrated. These may cause huge
// pages to be faulted for those cores, leading to test flakiness.
tcmalloc_internal::ScopedAffinityMask mask(
tcmalloc_internal::AllowedCpus()[0]);
allowed_cpu_id = subtle::percpu::GetCurrentVirtualCpuUnsafe();
ptr = cache.Allocate<OOMHandler>(kSizeClass);
if (mask.Tampered() ||
allowed_cpu_id != subtle::percpu::GetCurrentVirtualCpuUnsafe()) {
return;
}
}
EXPECT_NE(ptr, nullptr);
EXPECT_EQ(1, count_cores());
r = cache.MetadataMemoryUsage();
EXPECT_EQ(r.virtual_size, num_cpus << CPUCache::kPerCpuShift);
if (Parameters::lazy_per_cpu_caches()) {
// We expect to fault in a single core, but we may end up faulting an
// entire hugepage worth of memory
const size_t core_slab_size = r.virtual_size / num_cpus;
const size_t upper_bound =
((core_slab_size + kHugePageSize - 1) & ~(kHugePageSize - 1));
// A single core may be less than the full slab (core_slab_size), since we
// do not touch every page within the slab.
EXPECT_GT(r.resident_size, 0);
EXPECT_LE(r.resident_size, upper_bound) << count_cores();
// This test is much more sensitive to implementation details of the per-CPU
// cache. It may need to be updated from time to time. These numbers were
// calculated by MADV_NOHUGEPAGE'ing the memory used for the slab and
// measuring the resident size.
//
// TODO(ckennelly): Allow CPUCache::Activate to accept a specific arena
// allocator, so we can MADV_NOHUGEPAGE the backing store in testing for
// more precise measurements.
switch (CPUCache::kPerCpuShift) {
case 12:
EXPECT_GE(r.resident_size, 4096);
break;
case 18:
EXPECT_GE(r.resident_size, 135168);
break;
default:
ASSUME(false);
break;
};
// Read stats from the CPU caches. This should not impact resident_size.
const size_t max_cpu_cache_size = Parameters::max_per_cpu_cache_size();
size_t total_used_bytes = 0;
for (int cpu = 0; cpu < num_cpus; ++cpu) {
size_t used_bytes = cache.UsedBytes(cpu);
total_used_bytes += used_bytes;
if (cpu == allowed_cpu_id) {
EXPECT_GT(used_bytes, 0);
EXPECT_TRUE(cache.HasPopulated(cpu));
} else {
EXPECT_EQ(used_bytes, 0);
EXPECT_FALSE(cache.HasPopulated(cpu));
}
EXPECT_LE(cache.Unallocated(cpu), max_cpu_cache_size);
}
for (int cl = 0; cl < kNumClasses; ++cl) {
// This is sensitive to the current growth policies of CPUCache. It may
// require updating from time-to-time.
EXPECT_EQ(cache.TotalObjectsOfClass(cl),
(cl == kSizeClass ? num_to_move - 1 : 0))
<< cl;
}
EXPECT_EQ(cache.TotalUsedBytes(), total_used_bytes);
PerCPUMetadataState post_stats = cache.MetadataMemoryUsage();
// Confirm stats are within expected bounds.
EXPECT_GT(post_stats.resident_size, 0);
EXPECT_LE(post_stats.resident_size, upper_bound) << count_cores();
// Confirm stats are unchanged.
EXPECT_EQ(r.resident_size, post_stats.resident_size);
} else {
EXPECT_EQ(r.resident_size, r.virtual_size);
}
// Tear down.
//
// TODO(ckennelly): We're interacting with the real TransferCache.
cache.Deallocate(ptr, kSizeClass);
for (int i = 0; i < num_cpus; i++) {
cache.Reclaim(i);
}
}
} // namespace
} // namespace tcmalloc
<|endoftext|> |
<commit_before>{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
#include <boost/python.hpp>
#include <cmath>
/* main postinclude */
BOOST_PYTHON_MODULE({{module.name}})
{
{{{precontent}}}
{{#module.namespaces}}
::boost::python::scope().attr("{{name}}") = {{!
}}::boost::python::object(::boost::python::handle<>({{!
}}::boost::python::borrowed(::PyImport_AddModule({{!
}}"{{#scope}}{{name}}{{^last}}.{{/last}}{{/scope}}"))));
{{/module.namespaces}}
{{#module.bindings}}
void {{.}}();
{{.}}();
{{/module.bindings}}
}
{{{postcontent}}}
{{{footer}}}
<commit_msg>Fixed typos in module-level namespace generator.<commit_after>{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
#include <boost/python.hpp>
#include <cmath>
/* main postinclude */
BOOST_PYTHON_MODULE({{module.name}})
{
{{{precontent}}}
{{#module.namespaces}}{{#name}}
::boost::python::scope(){{!
}}{{#scope}}{{#name}}.attr("{{name}}"){{/name}}{{/scope}}.attr("{{name}}") = {{!
}}::boost::python::object(::boost::python::handle<>({{!
}}::boost::python::borrowed(::PyImport_AddModule({{!
}}"{{module.name}}{{#scope}}{{#name}}.{{name}}{{/name}}{{/scope}}.{{name}}"))));
{{/name}}{{/module.namespaces}}
{{#module.bindings}}
void {{.}}();
{{.}}();
{{/module.bindings}}
}
{{{postcontent}}}
{{{footer}}}
<|endoftext|> |
<commit_before>/*
* This file is part of cryptopp-bindings-api.
*
* (c) Stephen Berquet <stephen.berquet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "test_api_assertions.h"
#include <ostream>
#include <string>
static char hexconvtab[] = "0123456789abcdef";
static std::string bin2hex(const byte *binary, const size_t binarySize) {
size_t i;
size_t j;
size_t hexSize = 2 * binarySize;
byte *result = new byte[hexSize];
for (i = j = 0; i < binarySize; i++) {
result[j++] = hexconvtab[binary[i] >> 4];
result[j++] = hexconvtab[binary[i] & 15];
}
std::string hex(reinterpret_cast<char*>(result), hexSize);
delete[] result;
return hex;
}
static std::string byteArrayEqualsFailure(const byte *expected, const size_t expectedSize, const byte *actual, const size_t actualSize, const bool isExpected) {
// convert to hex
std::string hexExpected = bin2hex(expected, expectedSize);
std::string hexActual = bin2hex(actual, actualSize);
// build message
std::string strExpected = isExpected ? "Expected" : "Not expected";
std::stringstream msg;
msg << " Actual : (" << actualSize << ") " << hexActual;
msg << "\n " << strExpected << ": (" << expectedSize << ") " << hexExpected;
return msg.str();
}
::testing::AssertionResult ByteArrayEquals(const byte *expected, const size_t expectedSize, const byte *actual, const size_t actualSize) {
if (expectedSize != actualSize) {
std::string msg = byteArrayEqualsFailure(expected, expectedSize, actual, actualSize, true);
return ::testing::AssertionFailure() << msg;
}
for (size_t i(0); i < expectedSize; ++i) {
if (expected[i] != actual[i]) {
std::string msg = byteArrayEqualsFailure(expected, expectedSize, actual, actualSize, true);
return ::testing::AssertionFailure() << msg;
}
}
return ::testing::AssertionSuccess();
}
::testing::AssertionResult ByteArrayNotEquals(const byte *expected, const size_t expectedSize, const byte *actual, const size_t actualSize) {
if (expectedSize != actualSize) {
return ::testing::AssertionSuccess();
}
for (size_t i(0); i < expectedSize; ++i) {
// TODO fixme
if (expected[i] == actual[i]) {
std::string msg = byteArrayEqualsFailure(expected, expectedSize, actual, actualSize, false);
return ::testing::AssertionFailure() << msg;
}
}
return ::testing::AssertionSuccess();
}
<commit_msg>fixed ByteArrayNotEquals assertion<commit_after>/*
* This file is part of cryptopp-bindings-api.
*
* (c) Stephen Berquet <stephen.berquet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "test_api_assertions.h"
#include <ostream>
#include <string>
static char hexconvtab[] = "0123456789abcdef";
static std::string bin2hex(const byte *binary, const size_t binarySize) {
size_t i;
size_t j;
size_t hexSize = 2 * binarySize;
byte *result = new byte[hexSize];
for (i = j = 0; i < binarySize; i++) {
result[j++] = hexconvtab[binary[i] >> 4];
result[j++] = hexconvtab[binary[i] & 15];
}
std::string hex(reinterpret_cast<char*>(result), hexSize);
delete[] result;
return hex;
}
static std::string byteArrayEqualsFailure(const byte *expected, const size_t expectedSize, const byte *actual, const size_t actualSize, const bool isExpected) {
// convert to hex
std::string hexExpected = bin2hex(expected, expectedSize);
std::string hexActual = bin2hex(actual, actualSize);
// build message
std::string strExpected = isExpected ? "Expected" : "Not expected";
std::stringstream msg;
msg << " Actual : (" << actualSize << ") " << hexActual;
msg << "\n " << strExpected << ": (" << expectedSize << ") " << hexExpected;
return msg.str();
}
::testing::AssertionResult ByteArrayEquals(const byte *expected, const size_t expectedSize, const byte *actual, const size_t actualSize) {
if (expectedSize != actualSize) {
std::string msg = byteArrayEqualsFailure(expected, expectedSize, actual, actualSize, true);
return ::testing::AssertionFailure() << msg;
}
for (size_t i(0); i < expectedSize; ++i) {
if (expected[i] != actual[i]) {
std::string msg = byteArrayEqualsFailure(expected, expectedSize, actual, actualSize, true);
return ::testing::AssertionFailure() << msg;
}
}
return ::testing::AssertionSuccess();
}
::testing::AssertionResult ByteArrayNotEquals(const byte *expected, const size_t expectedSize, const byte *actual, const size_t actualSize) {
if (expectedSize != actualSize) {
return ::testing::AssertionSuccess();
}
for (size_t i(0); i < expectedSize; ++i) {
if (expected[i] != actual[i]) {
return ::testing::AssertionSuccess();
}
}
std::string msg = byteArrayEqualsFailure(expected, expectedSize, actual, actualSize, false);
return ::testing::AssertionFailure() << msg;
}
<|endoftext|> |
<commit_before>#include <Fastor/Fastor.h>
using namespace Fastor;
template<typename T, FASTOR_INDEX mm, FASTOR_INDEX nn>
void run_fixed_size() {
{
Tensor<T,mm,nn> a; a.iota(5);
Tensor<bool,mm,nn> ba1 = a == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba1(i,j) == true, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba2 = a != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba2(i,j) == false, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba3 = a < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba3(i,j) == false, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba4 = a >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba4(i,j) == true, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba5 = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// expr
ba5 = a + 1 == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5 = a + 1 != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a + 1 > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a - 1 < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a * 1 <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a * 2 >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// fixed views
ba5(fall,fall) = a == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(fall,fall) = a > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(fall,fall) = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// views
ba5(all,all) = a == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(all,all) = a > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(all,all) = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// expr fixed view
ba5(fall,fall) = a + 1 == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(fall,fall) = a + 1 != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a + 1 > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a - 1 < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a * 1 <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a * 2 >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// expr view
ba5(all,all) = a + 1 == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(all,all) = a + 1 != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a + 1 > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a - 1 < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a * 1 <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a * 2 >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
}
{
Tensor<T,mm,nn> a; a.iota(3);
Tensor<T,mm,nn> b; b.iota(3);
b(1,1) = 99;
Tensor<bool,mm,nn> bab1 = b == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
}
}
bab1 = b != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
}
}
bab1 = a < b;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
}
}
bab1 = b > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
}
}
bab1 = b >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
}
bab1 = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
}
}
{
Tensor<T> a(2);
Tensor<bool> ba = a==2;
FASTOR_EXIT_ASSERT(ba.toscalar() == true, "TEST FAILED");
ba = a>2;
FASTOR_EXIT_ASSERT(ba.toscalar() == false, "TEST FAILED");
ba = a<2;
FASTOR_EXIT_ASSERT(ba.toscalar() == false, "TEST FAILED");
ba = a>=2;
FASTOR_EXIT_ASSERT(ba.toscalar() == true, "TEST FAILED");
ba = a<=2;
FASTOR_EXIT_ASSERT(ba.toscalar() == true, "TEST FAILED");
}
}
template<typename T>
void run() {
run_fixed_size<T,2,2>();
print(FGRN(BOLD("All tests passed successfully")));
run_fixed_size<T,4,4>();
print(FGRN(BOLD("All tests passed successfully")));
run_fixed_size<T,8,8>();
print(FGRN(BOLD("All tests passed successfully")));
run_fixed_size<T,7,13>();
print(FGRN(BOLD("All tests passed successfully")));
}
int main() {
print(FBLU(BOLD("Testing binary comparison operators: single precision")));
run<float>();
print(FBLU(BOLD("Testing binary comparison operators: double precision")));
run<double>();
print(FBLU(BOLD("Testing binary comparison operators: int 32")));
run<int>();
print(FBLU(BOLD("Testing binary comparison operators: int 64")));
run<Int64>();
}
<commit_msg>Changes in test suite to reflect change all to fall<commit_after>#include <Fastor/Fastor.h>
using namespace Fastor;
template<typename T, FASTOR_INDEX mm, FASTOR_INDEX nn>
void run_fixed_size() {
constexpr seq sall = seq(0,-1,1);
{
Tensor<T,mm,nn> a; a.iota(5);
Tensor<bool,mm,nn> ba1 = a == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba1(i,j) == true, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba2 = a != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba2(i,j) == false, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba3 = a < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba3(i,j) == false, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba4 = a >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba4(i,j) == true, "TEST FAILED");
}
}
Tensor<bool,mm,nn> ba5 = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// expr
ba5 = a + 1 == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5 = a + 1 != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a + 1 > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a - 1 < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a * 1 <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5 = a * 2 >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// fixed views
ba5(fall,fall) = a == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(fall,fall) = a > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(fall,fall) = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// views
ba5(sall,sall) = a == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(sall,sall) = a < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(sall,sall) = a > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(sall,sall) = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(all,all) = a >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// expr fixed view
ba5(fall,fall) = a + 1 == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(fall,fall) = a + 1 != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a + 1 > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a - 1 < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a * 1 <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(fall,fall) = a * 2 >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
// expr view
ba5(sall,sall) = a + 1 == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == false, "TEST FAILED");
}
}
ba5(sall,sall) = a + 1 != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(sall,sall) = a + 1 > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(sall,sall) = a - 1 < a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(sall,sall) = a * 1 <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
ba5(sall,sall) = a * 2 >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(ba5(i,j) == true, "TEST FAILED");
}
}
}
{
Tensor<T,mm,nn> a; a.iota(3);
Tensor<T,mm,nn> b; b.iota(3);
b(1,1) = 99;
Tensor<bool,mm,nn> bab1 = b == a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
}
}
bab1 = b != a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
}
}
bab1 = a < b;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
}
}
bab1 = b > a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
if (i==1 && j==1) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
else {
FASTOR_EXIT_ASSERT(bab1(i,j) == false, "TEST FAILED");
}
}
}
bab1 = b >= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
}
bab1 = a <= a;
for (FASTOR_INDEX i=0; i<mm; ++i) {
for (FASTOR_INDEX j=0; j<nn; ++j) {
FASTOR_EXIT_ASSERT(bab1(i,j) == true, "TEST FAILED");
}
}
}
{
Tensor<T> a(2);
Tensor<bool> ba = a==2;
FASTOR_EXIT_ASSERT(ba.toscalar() == true, "TEST FAILED");
ba = a>2;
FASTOR_EXIT_ASSERT(ba.toscalar() == false, "TEST FAILED");
ba = a<2;
FASTOR_EXIT_ASSERT(ba.toscalar() == false, "TEST FAILED");
ba = a>=2;
FASTOR_EXIT_ASSERT(ba.toscalar() == true, "TEST FAILED");
ba = a<=2;
FASTOR_EXIT_ASSERT(ba.toscalar() == true, "TEST FAILED");
}
}
template<typename T>
void run() {
run_fixed_size<T,2,2>();
print(FGRN(BOLD("All tests passed successfully")));
run_fixed_size<T,4,4>();
print(FGRN(BOLD("All tests passed successfully")));
run_fixed_size<T,8,8>();
print(FGRN(BOLD("All tests passed successfully")));
run_fixed_size<T,7,13>();
print(FGRN(BOLD("All tests passed successfully")));
}
int main() {
print(FBLU(BOLD("Testing binary comparison operators: single precision")));
run<float>();
print(FBLU(BOLD("Testing binary comparison operators: double precision")));
run<double>();
print(FBLU(BOLD("Testing binary comparison operators: int 32")));
run<int>();
print(FBLU(BOLD("Testing binary comparison operators: int 64")));
run<Int64>();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"
using namespace mfem;
namespace ceed_test
{
double coeff_function(const Vector &x)
{
return 1.0 + x[0]*x[0];
}
// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
int dim = x.Size();
switch (dim)
{
case 1: v(0) = 1.0; break;
case 2: v(0) = sqrt(2./3.); v(1) = sqrt(1./3.); break;
case 3: v(0) = sqrt(3./6.); v(1) = sqrt(2./6.); v(2) = sqrt(1./6.); break;
}
}
static std::string getString(AssemblyLevel assembly)
{
switch (assembly)
{
case AssemblyLevel::NONE:
return "NONE";
break;
case AssemblyLevel::PARTIAL:
return "PARTIAL";
break;
case AssemblyLevel::ELEMENT:
return "ELEMENT";
break;
case AssemblyLevel::FULL:
return "FULL";
break;
case AssemblyLevel::LEGACYFULL:
return "LEGACYFULL";
break;
}
}
static std::string getString(CeedCoeff coeff_type)
{
switch (coeff_type)
{
case CeedCoeff::Const:
return "Const";
break;
case CeedCoeff::Grid:
return "Grid";
break;
case CeedCoeff::Quad:
return "Quad";
break;
case CeedCoeff::VecConst:
return "VecConst";
break;
case CeedCoeff::VecGrid:
return "VecGrid";
break;
case CeedCoeff::VecQuad:
return "VecQuad";
break;
}
}
enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};
static std::string getString(Problem pb)
{
switch (pb)
{
case Problem::Mass:
return "Mass";
break;
case Problem::Convection:
return "Convection";
break;
case Problem::Diffusion:
return "Diffusion";
break;
case Problem::VectorMass:
return "VectorMass";
break;
case Problem::VectorDiffusion:
return "VectorDiffusion";
break;
}
}
void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
const Problem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
BilinearForm k_test(&fes);
BilinearForm k_ref(&fes);
// Coefficient Initialization
// Scalar coefficient
FiniteElementSpace coeff_fes(&mesh, &fec);
GridFunction gf(&coeff_fes);
FunctionCoefficient f_coeff(coeff_function);
Coefficient *coeff = nullptr;
// Vector Coefficient
FiniteElementSpace vcoeff_fes(&mesh, &fec, dim);
GridFunction vgf(&vcoeff_fes);
VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
VectorCoefficient *vcoeff = nullptr;
switch (coeff_type)
{
case CeedCoeff::Const:
coeff = new ConstantCoefficient(1.0);
break;
case CeedCoeff::Grid:
gf.ProjectCoefficient(f_coeff);
coeff = new GridFunctionCoefficient(&gf);
break;
case CeedCoeff::Quad:
coeff = &f_coeff;
break;
case CeedCoeff::VecConst:
{
Vector val(dim);
for (size_t i = 0; i < dim; i++)
{
val(i) = 1.0;
}
vcoeff = new VectorConstantCoefficient(val);
}
break;
case CeedCoeff::VecGrid:
{
vgf.ProjectCoefficient(f_vcoeff);
vcoeff = new VectorGridFunctionCoefficient(&vgf);
}
break;
case CeedCoeff::VecQuad:
vcoeff = &f_vcoeff;
break;
}
// Build the BilinearForm
switch (pb)
{
case Problem::Mass:
k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
break;
case Problem::Convection:
k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
case Problem::Diffusion:
k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
break;
case Problem::VectorMass:
k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
break;
case Problem::VectorDiffusion:
k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
break;
}
k_ref.Assemble();
k_ref.Finalize();
k_test.SetAssemblyLevel(assembly);
k_test.Assemble();
// Compare ceed with mfem.
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
}
TEST_CASE("CEED mass & diffusion", "[CEED mass & diffusion]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
Problem::VectorMass,Problem::VectorDiffusion);
auto order = GENERATE(1,2,4);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/star-q3.mesh","../../data/fichera-q3.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
TEST_CASE("CEED convection", "[CEED convection]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
CeedCoeff::VecQuad);
auto pb = GENERATE(Problem::Convection);
auto order = GENERATE(1,2,4);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/star-q3.mesh","../../data/fichera-q3.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
} // namespace ceed_test
int main(int argc, char *argv[])
{
// There must be exactly one instance.
Catch::Session session;
const char *device_str = (argc == 1) ? "ceed-cpu" : argv[argc-1];
// Apply provided command line arguments.
int r = session.applyCommandLine((argc == 1) ? argc : argc - 1, argv);
if (r != 0)
{
return r;
}
Device device(device_str);
int result = session.run();
return result;
}
<commit_msg>Change velocity function.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"
using namespace mfem;
namespace ceed_test
{
double coeff_function(const Vector &x)
{
return 1.0 + x[0]*x[0];
}
// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
int dim = x.Size();
switch (dim)
{
case 1: v(0) = 1.0; break;
case 2: v(0) = 1.0; v(1) = 1.0; break;
case 3: v(0) = 1.0; v(1) = 1.0; v(2) = 1.0; break;
}
}
static std::string getString(AssemblyLevel assembly)
{
switch (assembly)
{
case AssemblyLevel::NONE:
return "NONE";
break;
case AssemblyLevel::PARTIAL:
return "PARTIAL";
break;
case AssemblyLevel::ELEMENT:
return "ELEMENT";
break;
case AssemblyLevel::FULL:
return "FULL";
break;
case AssemblyLevel::LEGACYFULL:
return "LEGACYFULL";
break;
}
}
static std::string getString(CeedCoeff coeff_type)
{
switch (coeff_type)
{
case CeedCoeff::Const:
return "Const";
break;
case CeedCoeff::Grid:
return "Grid";
break;
case CeedCoeff::Quad:
return "Quad";
break;
case CeedCoeff::VecConst:
return "VecConst";
break;
case CeedCoeff::VecGrid:
return "VecGrid";
break;
case CeedCoeff::VecQuad:
return "VecQuad";
break;
}
}
enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};
static std::string getString(Problem pb)
{
switch (pb)
{
case Problem::Mass:
return "Mass";
break;
case Problem::Convection:
return "Convection";
break;
case Problem::Diffusion:
return "Diffusion";
break;
case Problem::VectorMass:
return "VectorMass";
break;
case Problem::VectorDiffusion:
return "VectorDiffusion";
break;
}
}
void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
const Problem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
BilinearForm k_test(&fes);
BilinearForm k_ref(&fes);
// Coefficient Initialization
// Scalar coefficient
FiniteElementSpace coeff_fes(&mesh, &fec);
GridFunction gf(&coeff_fes);
FunctionCoefficient f_coeff(coeff_function);
Coefficient *coeff = nullptr;
// Vector Coefficient
FiniteElementSpace vcoeff_fes(&mesh, &fec, dim);
GridFunction vgf(&vcoeff_fes);
VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
VectorCoefficient *vcoeff = nullptr;
switch (coeff_type)
{
case CeedCoeff::Const:
coeff = new ConstantCoefficient(1.0);
break;
case CeedCoeff::Grid:
gf.ProjectCoefficient(f_coeff);
coeff = new GridFunctionCoefficient(&gf);
break;
case CeedCoeff::Quad:
coeff = &f_coeff;
break;
case CeedCoeff::VecConst:
{
Vector val(dim);
for (size_t i = 0; i < dim; i++)
{
val(i) = 1.0;
}
vcoeff = new VectorConstantCoefficient(val);
}
break;
case CeedCoeff::VecGrid:
{
vgf.ProjectCoefficient(f_vcoeff);
vcoeff = new VectorGridFunctionCoefficient(&vgf);
}
break;
case CeedCoeff::VecQuad:
vcoeff = &f_vcoeff;
break;
}
// Build the BilinearForm
switch (pb)
{
case Problem::Mass:
k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
break;
case Problem::Convection:
k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
case Problem::Diffusion:
k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
break;
case Problem::VectorMass:
k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
break;
case Problem::VectorDiffusion:
k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
break;
}
k_ref.Assemble();
k_ref.Finalize();
k_test.SetAssemblyLevel(assembly);
k_test.Assemble();
// Compare ceed with mfem.
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
}
TEST_CASE("CEED mass & diffusion", "[CEED mass & diffusion]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
Problem::VectorMass,Problem::VectorDiffusion);
auto order = GENERATE(1,2,4);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/star-q3.mesh","../../data/fichera-q3.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
TEST_CASE("CEED convection", "[CEED convection]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
CeedCoeff::VecQuad);
auto pb = GENERATE(Problem::Convection);
auto order = GENERATE(1,2,4);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/star-q3.mesh","../../data/fichera-q3.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
} // namespace ceed_test
int main(int argc, char *argv[])
{
// There must be exactly one instance.
Catch::Session session;
const char *device_str = (argc == 1) ? "ceed-cpu" : argv[argc-1];
// Apply provided command line arguments.
int r = session.applyCommandLine((argc == 1) ? argc : argc - 1, argv);
if (r != 0)
{
return r;
}
Device device(device_str);
int result = session.run();
return result;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Cloudius Systems
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE core
#include <boost/test/included/unit_test.hpp>
#include "core/sstring.hh"
#include "database.hh"
static sstring some_keyspace("ks");
static sstring some_column_family("cf");
static atomic_cell::one make_atomic_cell(bytes value) {
return atomic_cell::one::make_live(0, ttl_opt{}, std::move(value));
};
BOOST_AUTO_TEST_CASE(test_mutation_is_applied) {
auto s = make_lw_shared(schema(some_keyspace, some_column_family,
{{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type));
column_family cf(s);
column_definition& r1_col = *s->get_column_definition("r1");
partition_key key = to_bytes("key1");
clustering_key c_key = s->clustering_key_type->decompose_value({int32_type->decompose(2)});
mutation m(key, s);
m.set_clustered_cell(c_key, r1_col, make_atomic_cell(int32_type->decompose(3)));
cf.apply(std::move(m));
row& r = cf.find_or_create_row(key, c_key);
auto i = r.find(r1_col.id);
BOOST_REQUIRE(i != r.end());
auto cell = i->second.as_atomic_cell();
BOOST_REQUIRE(cell.is_live());
BOOST_REQUIRE(int32_type->equal(cell.value(), int32_type->decompose(3)));
}
BOOST_AUTO_TEST_CASE(test_row_tombstone_updates) {
auto s = make_lw_shared(schema(some_keyspace, some_column_family,
{{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type));
column_family cf(s);
partition_key key = to_bytes("key1");
clustering_key c_key1 = s->clustering_key_type->decompose_value(
{int32_type->decompose(1)}
);
clustering_key c_key2 = s->clustering_key_type->decompose_value(
{int32_type->decompose(2)}
);
auto ttl = gc_clock::now() + std::chrono::seconds(1);
mutation m(key, s);
m.p.apply_row_tombstone(s, c_key1, tombstone(1, ttl));
m.p.apply_row_tombstone(s, c_key2, tombstone(0, ttl));
BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key1), tombstone(1, ttl));
BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(0, ttl));
m.p.apply_row_tombstone(s, c_key2, tombstone(1, ttl));
BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(1, ttl));
}
<commit_msg>mutation_test: test maps<commit_after>/*
* Copyright 2015 Cloudius Systems
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE core
#include <boost/test/included/unit_test.hpp>
#include "core/sstring.hh"
#include "database.hh"
static sstring some_keyspace("ks");
static sstring some_column_family("cf");
static atomic_cell::one make_atomic_cell(bytes value) {
return atomic_cell::one::make_live(0, ttl_opt{}, std::move(value));
};
BOOST_AUTO_TEST_CASE(test_mutation_is_applied) {
auto s = make_lw_shared(schema(some_keyspace, some_column_family,
{{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type));
column_family cf(s);
column_definition& r1_col = *s->get_column_definition("r1");
partition_key key = to_bytes("key1");
clustering_key c_key = s->clustering_key_type->decompose_value({int32_type->decompose(2)});
mutation m(key, s);
m.set_clustered_cell(c_key, r1_col, make_atomic_cell(int32_type->decompose(3)));
cf.apply(std::move(m));
row& r = cf.find_or_create_row(key, c_key);
auto i = r.find(r1_col.id);
BOOST_REQUIRE(i != r.end());
auto cell = i->second.as_atomic_cell();
BOOST_REQUIRE(cell.is_live());
BOOST_REQUIRE(int32_type->equal(cell.value(), int32_type->decompose(3)));
}
BOOST_AUTO_TEST_CASE(test_row_tombstone_updates) {
auto s = make_lw_shared(schema(some_keyspace, some_column_family,
{{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type));
column_family cf(s);
partition_key key = to_bytes("key1");
clustering_key c_key1 = s->clustering_key_type->decompose_value(
{int32_type->decompose(1)}
);
clustering_key c_key2 = s->clustering_key_type->decompose_value(
{int32_type->decompose(2)}
);
auto ttl = gc_clock::now() + std::chrono::seconds(1);
mutation m(key, s);
m.p.apply_row_tombstone(s, c_key1, tombstone(1, ttl));
m.p.apply_row_tombstone(s, c_key2, tombstone(0, ttl));
BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key1), tombstone(1, ttl));
BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(0, ttl));
m.p.apply_row_tombstone(s, c_key2, tombstone(1, ttl));
BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(1, ttl));
}
BOOST_AUTO_TEST_CASE(test_map_mutations) {
auto my_map_type = map_type_impl::get_instance(int32_type, utf8_type, true);
auto s = make_lw_shared(schema(some_keyspace, some_column_family,
{{"p1", utf8_type}}, {{"c1", int32_type}}, {}, {{"s1", my_map_type}}, utf8_type));
column_family cf(s);
partition_key key = to_bytes("key1");
auto& column = *s->get_column_definition("s1");
map_type_impl::mutation mmut1{{int32_type->decompose(101), make_atomic_cell(utf8_type->decompose(sstring("101")))}};
mutation m1(key, s);
m1.set_static_cell(column, my_map_type->serialize_mutation_form(mmut1));
cf.apply(m1);
map_type_impl::mutation mmut2{{int32_type->decompose(102), make_atomic_cell(utf8_type->decompose(sstring("102")))}};
mutation m2(key, s);
m2.set_static_cell(column, my_map_type->serialize_mutation_form(mmut2));
cf.apply(m2);
map_type_impl::mutation mmut3{{int32_type->decompose(103), make_atomic_cell(utf8_type->decompose(sstring("103")))}};
mutation m3(key, s);
m3.set_static_cell(column, my_map_type->serialize_mutation_form(mmut3));
cf.apply(m3);
map_type_impl::mutation mmut2o{{int32_type->decompose(102), make_atomic_cell(utf8_type->decompose(sstring("102 override")))}};
mutation m2o(key, s);
m2o.set_static_cell(column, my_map_type->serialize_mutation_form(mmut2o));
cf.apply(m2o);
row& r = cf.find_or_create_partition(key).static_row();
auto i = r.find(column.id);
BOOST_REQUIRE(i != r.end());
auto cell = i->second.as_collection_mutation();
auto muts = my_map_type->deserialize_mutation_form(cell.data);
BOOST_REQUIRE(muts.size() == 3);
// FIXME: more strict tests
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.