text
stringlengths 54
60.6k
|
---|
<commit_before>eeed3d78-2e4e-11e5-9284-b827eb9e62be<commit_msg>eef238d2-2e4e-11e5-9284-b827eb9e62be<commit_after>eef238d2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_helper.h"
#include "base/android/jni_android.h"
#include "base/logging.h"
using base::android::AttachCurrentThread;
JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef()
: obj_(NULL) {
}
JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
const JavaObjectWeakGlobalRef& orig) {
Assign(orig);
}
JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj)
: obj_(env->NewWeakGlobalRef(obj)) {
DCHECK(obj_);
}
JavaObjectWeakGlobalRef::~JavaObjectWeakGlobalRef() {
reset();
}
void JavaObjectWeakGlobalRef::operator=(const JavaObjectWeakGlobalRef& rhs) {
Assign(rhs);
}
void JavaObjectWeakGlobalRef::reset() {
if (obj_) {
AttachCurrentThread()->DeleteWeakGlobalRef(obj_);
obj_ = NULL;
}
}
base::android::ScopedJavaLocalRef<jobject>
JavaObjectWeakGlobalRef::get(JNIEnv* env) const {
return GetRealObject(env, obj_);
}
base::android::ScopedJavaLocalRef<jobject> GetRealObject(
JNIEnv* env, jweak obj) {
jobject real = NULL;
if (obj) {
real = env->NewLocalRef(obj);
if (!real)
DLOG(ERROR) << "The real object has been deleted!";
}
return base::android::ScopedJavaLocalRef<jobject>(env, real);
}
void JavaObjectWeakGlobalRef::Assign(const JavaObjectWeakGlobalRef& other) {
JNIEnv* env = AttachCurrentThread();
obj_ = env->NewWeakGlobalRef(other.obj_);
}
<commit_msg>Fix JavaObjectWeakGlobalRef::operator= leaking jweaks<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_helper.h"
#include "base/android/jni_android.h"
#include "base/logging.h"
using base::android::AttachCurrentThread;
JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef()
: obj_(NULL) {
}
JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
const JavaObjectWeakGlobalRef& orig)
: obj_(NULL) {
Assign(orig);
}
JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj)
: obj_(env->NewWeakGlobalRef(obj)) {
DCHECK(obj_);
}
JavaObjectWeakGlobalRef::~JavaObjectWeakGlobalRef() {
reset();
}
void JavaObjectWeakGlobalRef::operator=(const JavaObjectWeakGlobalRef& rhs) {
Assign(rhs);
}
void JavaObjectWeakGlobalRef::reset() {
if (obj_) {
AttachCurrentThread()->DeleteWeakGlobalRef(obj_);
obj_ = NULL;
}
}
base::android::ScopedJavaLocalRef<jobject>
JavaObjectWeakGlobalRef::get(JNIEnv* env) const {
return GetRealObject(env, obj_);
}
base::android::ScopedJavaLocalRef<jobject> GetRealObject(
JNIEnv* env, jweak obj) {
jobject real = NULL;
if (obj) {
real = env->NewLocalRef(obj);
if (!real)
DLOG(ERROR) << "The real object has been deleted!";
}
return base::android::ScopedJavaLocalRef<jobject>(env, real);
}
void JavaObjectWeakGlobalRef::Assign(const JavaObjectWeakGlobalRef& other) {
if (&other == this)
return;
JNIEnv* env = AttachCurrentThread();
if (obj_)
env->DeleteWeakGlobalRef(obj_);
obj_ = other.obj_ ? env->NewWeakGlobalRef(other.obj_) : NULL;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include "api/types.hpp"
#include "configuration/Configuration.hpp"
#include "utils/Logger.hpp"
#include "ServerParser.hpp"
#include "ConfigurationParserException.hpp"
using namespace zhttpd;
using namespace zhttpd::parser;
ServerParser::ServerParser()
{
this->_confParsers["listen"] = &ServerParser::_parseListen;
this->_confParsers["modules-directory"] = &ServerParser::_parseModuleDirectory;
this->_confParsers["index-files"] = &ServerParser::_parseIndexFiles;
this->_confParsers["log"] = &ServerParser::_parseLogFile;
}
ServerParser::~ServerParser()
{
}
void ServerParser::parseServerConfNode(ticpp::Node* node, Configuration* conf)
{
std::string name = node->ToElement()->Value();
if (this->_confParsers.find(name) != this->_confParsers.end())
{
(this->*this->_confParsers[name])(node, conf);
return;
}
throw ConfigurationParserException("Invalid configuration for server: unknown option " + name);
}
void ServerParser::_parseListen(ticpp::Node* node, Configuration* conf)
{
try
{
api::uint16_t port;
node->ToElement()->GetAttribute("port", &port);
std::string iomodule = node->ToElement()->GetAttribute("io-module");
conf->addListenPort(port, iomodule);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("listen option misformed. Check if there is an integer 'port' attribute");
}
}
void ServerParser::_parseModuleDirectory(ticpp::Node* node, Configuration* conf)
{
try
{
std::string path;
node->ToElement()->GetAttribute("path", &path);
conf->addModuleDirectory(path);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("modules directory option misformed. It should have a 'path' attribute");
}
}
void ServerParser::_parseIndexFiles(ticpp::Node* node, Configuration* conf)
{
try
{
ticpp::Node* child = 0;
while ((child = node->IterateChildren("filename", child)))
this->_parseIndexFileName(child, conf);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("Index files configuration misformed");
}
catch (ConfigurationParserException&)
{
throw ;
}
}
void ServerParser::_parseIndexFileName(ticpp::Node* node, Configuration* conf)
{
try
{
std::string match;
node->ToElement()->GetAttribute("match", &match);
conf->addIndexFile(match);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("filename misformed in index files configuration. It should contain a 'match' attribute");
}
}
void ServerParser::_parseLogFile(ticpp::Node* node, Configuration*)
{
std::string match;
try
{
node->ToElement()->GetAttribute("file", &match);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("Wrong file in log configuration. It should contain a 'file' attribute");
}
try
{
std::ofstream* o = new std::ofstream(match.c_str(), std::ios_base::out | std::ios_base::app);
if (o->fail())
{
delete o;
throw std::runtime_error("Cannot open log file '" + match + "'");
}
Logger::getInstance()->setOutput(*o);
}
catch (std::exception& e)
{
throw ConfigurationParserException("Cannot set log file: " + Logger::toString(e.what()));
}
}
<commit_msg>log the file name of the log file when setted<commit_after>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include "api/types.hpp"
#include "configuration/Configuration.hpp"
#include "utils/Logger.hpp"
#include "ServerParser.hpp"
#include "ConfigurationParserException.hpp"
using namespace zhttpd;
using namespace zhttpd::parser;
ServerParser::ServerParser()
{
this->_confParsers["listen"] = &ServerParser::_parseListen;
this->_confParsers["modules-directory"] = &ServerParser::_parseModuleDirectory;
this->_confParsers["index-files"] = &ServerParser::_parseIndexFiles;
this->_confParsers["log"] = &ServerParser::_parseLogFile;
}
ServerParser::~ServerParser()
{
}
void ServerParser::parseServerConfNode(ticpp::Node* node, Configuration* conf)
{
std::string name = node->ToElement()->Value();
if (this->_confParsers.find(name) != this->_confParsers.end())
{
(this->*this->_confParsers[name])(node, conf);
return;
}
throw ConfigurationParserException("Invalid configuration for server: unknown option " + name);
}
void ServerParser::_parseListen(ticpp::Node* node, Configuration* conf)
{
try
{
api::uint16_t port;
node->ToElement()->GetAttribute("port", &port);
std::string iomodule = node->ToElement()->GetAttribute("io-module");
conf->addListenPort(port, iomodule);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("listen option misformed. Check if there is an integer 'port' attribute");
}
}
void ServerParser::_parseModuleDirectory(ticpp::Node* node, Configuration* conf)
{
try
{
std::string path;
node->ToElement()->GetAttribute("path", &path);
conf->addModuleDirectory(path);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("modules directory option misformed. It should have a 'path' attribute");
}
}
void ServerParser::_parseIndexFiles(ticpp::Node* node, Configuration* conf)
{
try
{
ticpp::Node* child = 0;
while ((child = node->IterateChildren("filename", child)))
this->_parseIndexFileName(child, conf);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("Index files configuration misformed");
}
catch (ConfigurationParserException&)
{
throw ;
}
}
void ServerParser::_parseIndexFileName(ticpp::Node* node, Configuration* conf)
{
try
{
std::string match;
node->ToElement()->GetAttribute("match", &match);
conf->addIndexFile(match);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("filename misformed in index files configuration. It should contain a 'match' attribute");
}
}
void ServerParser::_parseLogFile(ticpp::Node* node, Configuration*)
{
std::string match;
try
{
node->ToElement()->GetAttribute("file", &match);
}
catch (ticpp::Exception&)
{
throw ConfigurationParserException("Wrong file in log configuration. It should contain a 'file' attribute");
}
try
{
std::ofstream* o = new std::ofstream(match.c_str(), std::ios_base::out | std::ios_base::app);
if (o->fail())
{
delete o;
throw std::runtime_error("Cannot open log file '" + match + "'");
}
LOG_INFO("Set log file to '" + match + "'");
Logger::getInstance()->setOutput(*o);
}
catch (std::exception& e)
{
throw ConfigurationParserException("Cannot set log file: " + Logger::toString(e.what()));
}
}
<|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. *
**************************************************************************/
/*
$Log$
Revision 1.21 2002/03/25 14:46:16 morsch
Case kPyD0PbMNR added (N. Carrer).
Revision 1.20 2002/03/03 13:48:50 morsch
Option kPyCharmPbMNR added. Produce charm pairs in agreement with MNR
NLO calculations (Nicola Carrer).
Revision 1.19 2002/02/20 08:52:20 morsch
Correct documentation of SetNuclei method.
Revision 1.18 2002/02/07 10:43:06 morsch
Tuned pp-min.bias settings (M.Monteno, R.Ugoccioni and N.Carrer)
Revision 1.17 2001/12/19 15:40:43 morsch
For kPyJets enforce simple jet topology, i.e no initial or final state
gluon radiation and no primordial pT.
Revision 1.16 2001/10/12 11:13:59 morsch
Missing break statements added (thanks to Nicola Carrer)
Revision 1.15 2001/03/27 10:54:50 morsch
Add ResetDecayTable() and SsetDecayTable() methods.
Revision 1.14 2001/03/09 13:03:40 morsch
Process_t and Struc_Func_t moved to AliPythia.h
Revision 1.13 2000/12/18 08:55:35 morsch
Make AliPythia dependent generartors work with new scheme of random number generation
Revision 1.12 2000/11/30 07:12:50 alibrary
Introducing new Rndm and QA classes
Revision 1.11 2000/10/20 06:30:06 fca
Use version 0 to avoid streamer generation
Revision 1.10 2000/10/06 14:18:44 morsch
Upper cut of prim. pT distribution set to 5. GeV
Revision 1.9 2000/09/18 10:41:35 morsch
Add possibility to use nuclear structure functions from PDF library V8.
Revision 1.8 2000/09/06 14:26:24 morsch
Decayer functionality of AliPythia has been moved to AliDecayerPythia.
Class is now a singleton.
Revision 1.7 2000/06/09 20:34:50 morsch
All coding rule violations except RS3 corrected
Revision 1.6 1999/11/09 07:38:48 fca
Changes for compatibility with version 2.23 of ROOT
Revision 1.5 1999/11/03 17:43:20 fca
New version from G.Martinez & A.Morsch
Revision 1.4 1999/09/29 09:24:14 fca
Introduction of the Copyright and cvs Log
*/
#include "AliPythia.h"
ClassImp(AliPythia)
//_____________________________________________________________________________
AliPythia* AliPythia::fgAliPythia=NULL;
AliPythia::AliPythia()
{
// Default Constructor
//
// Set random number
if (!sRandom) sRandom=fRandom;
}
void AliPythia::ProcInit(Process_t process, Float_t energy, StrucFunc_t strucfunc)
{
// Initialise the process to generate
fProcess = process;
fEcms = energy;
fStrucFunc = strucfunc;
// don't decay p0
SetMDCY(Pycomp(111),1,0);
// select structure function
SetMSTP(52,2);
SetMSTP(51,strucfunc);
//
// Pythia initialisation for selected processes//
//
// Make MSEL clean
//
for (Int_t i=1; i<= 200; i++) {
SetMSUB(i,0);
}
// select charm production
switch (process)
{
case kPyCharm:
SetMSEL(4);
//
// heavy quark masses
SetPMAS(4,1,1.2);
SetMSTU(16,2);
//
// primordial pT
SetMSTP(91,1);
SetPARP(91,1.);
SetPARP(93,5.);
//
break;
case kPyBeauty:
SetMSEL(5);
SetPMAS(5,1,4.75);
SetMSTU(16,2);
break;
case kPyJpsi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
break;
case kPyJpsiChi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
// gg-> chi_0c g
SetMSUB(87,1);
// gg-> chi_1c g
SetMSUB(88,1);
// gg-> chi_2c g
SetMSUB(89,1);
break;
case kPyCharmUnforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
break;
case kPyBeautyUnforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
break;
case kPyMb:
// Minimum Bias pp-Collisions
//
//
// select Pythia min. bias model
SetMSEL(0);
SetMSUB(92,1); // single diffraction AB-->XB
SetMSUB(93,1); // single diffraction AB-->AX
SetMSUB(94,1); // double diffraction
SetMSUB(95,1); // low pt production
SetMSTP(81,1); // multiple interactions switched on
SetMSTP(82,3); // model with varying impact param. & a single Gaussian
SetPARP(82,3.47); // set value pT_0 for turn-off of the cross section of
// multiple interaction at a reference energy = 14000 GeV
SetPARP(89,14000.); // reference energy for the above parameter
SetPARP(90,0.174); // set exponent for energy dependence of pT_0
break;
case kPyJets:
SetMSEL(1);
// no initial state radiation
SetMSTP(61,0);
// no final state radiation
SetMSTP(71,0);
// no primordial pT
SetMSTP(91,0);
// SetMSTP(111,0);
SetMSTU(16,1);
SetMSTJ(1,1);
break;
case kPyDirectGamma:
SetMSEL(10);
break;
case kPyCharmPbMNR:
case kPyD0PbMNR:
// Tuning of Pythia parameters aimed to get a resonable agreement
// between with the NLO calculation by Mangano, Nason, Ridolfi for the
// c-cbar single inclusive and double differential distributions.
// This parameter settings are meant to work with Pb-Pb collisions
// (AliGenPythia::SetNuclei) and with kCTEQ_4L PDFs.
// To get a good agreement the minimum ptHard (AliGenPythia::SetPtHard)
// has to be set to 2.1GeV. Example in ConfigCharmPPR.C.
// All QCD processes
SetMSEL(1);
// No multiple interactions
SetMSTP(81,0);
SetPARP(81,0.0);
SetPARP(82,0.0);
// Initial/final parton shower on (Pythia default)
SetMSTP(61,1);
SetMSTP(71,1);
// 2nd order alpha_s
SetMSTP(2,2);
// QCD scales
SetMSTP(32,2);
SetPARP(34,1.0);
// Intrinsic <kT^2>
SetMSTP(91,1);
SetPARP(91,1.304);
SetPARP(93,6.52);
// Set c-quark mass
SetPMAS(4,1,1.2);
break;
case kPyBeautyPbMNR:
// Tuning of Pythia parameters aimed to get a resonable agreement
// between with the NLO calculation by Mangano, Nason, Ridolfi for the
// b-bbar single inclusive and double differential distributions.
// This parameter settings are meant to work with Pb-Pb collisions
// (AliGenPythia::SetNuclei) and with kCTEQ4L PDFs.
// To get a good agreement the minimum ptHard (AliGenPythia::SetPtHard)
// has to be set to 2.75GeV. Example in ConfigBeautyPPR.C.
// All QCD processes
SetMSEL(1);
// No multiple interactions
SetMSTP(81,0);
SetPARP(81,0.0);
SetPARP(82,0.0);
// Initial/final parton shower on (Pythia default)
SetMSTP(61,1);
SetMSTP(71,1);
// 2nd order alpha_s
SetMSTP(2,2);
// QCD scales
SetMSTP(32,2);
SetPARP(34,1.0);
SetPARP(67,1.0);
SetPARP(71,1.0);
// Intrinsic <kT^2>
SetMSTP(91,1);
SetPARP(91,2.035);
SetPARP(93,10.17);
// Set b-quark mass
SetPMAS(5,1,4.75);
break;
}
//
// Initialize PYTHIA
SetMSTP(41,1); // all resonance decays switched on
Initialize("CMS","p","p",fEcms);
}
Int_t AliPythia::CheckedLuComp(Int_t kf)
{
// Check Lund particle code (for debugging)
Int_t kc=Pycomp(kf);
printf("\n Lucomp kf,kc %d %d",kf,kc);
return kc;
}
void AliPythia::SetNuclei(Int_t a1, Int_t a2)
{
// Treat protons as inside nuclei with mass numbers a1 and a2
// The MSTP array in the PYPARS common block is used to enable and
// select the nuclear structure functions.
// MSTP(52) : (D=1) choice of proton and nuclear structure-function library
// =1: internal PYTHIA acording to MSTP(51)
// =2: PDFLIB proton s.f., with MSTP(51) = 1000xNGROUP+NSET
// If the following mass number both not equal zero, nuclear corrections of the stf are used.
// MSTP(192) : Mass number of nucleus side 1
// MSTP(193) : Mass number of nucleus side 2
SetMSTP(52,2);
SetMSTP(192, a1);
SetMSTP(193, a2);
}
AliPythia* AliPythia::Instance()
{
// Set random number generator
if (fgAliPythia) {
return fgAliPythia;
} else {
fgAliPythia = new AliPythia();
return fgAliPythia;
}
}
void AliPythia::PrintParticles()
{
// Print list of particl properties
Int_t np = 0;
for (Int_t kf=0; kf<1000000; kf++) {
for (Int_t c = 1; c > -2; c-=2) {
Int_t kc = Pycomp(c*kf);
if (kc) {
Float_t mass = GetPMAS(kc,1);
Float_t width = GetPMAS(kc,2);
Float_t tau = GetPMAS(kc,4);
char* name = new char[8];
Pyname(kf,name);
np++;
printf("\n mass, width, tau: %6d %s %10.3f %10.3e %10.3e",
c*kf, name, mass, width, tau);
}
}
}
printf("\n Number of particles %d \n \n", np);
}
void AliPythia::ResetDecayTable()
{
// Set default values for pythia decay switches
Int_t i;
for (i = 1; i < 501; i++) SetMDCY(i,1,fDefMDCY[i]);
for (i = 1; i < 2001; i++) SetMDME(i,1,fDefMDME[i]);
}
void AliPythia::SetDecayTable()
{
// Set default values for pythia decay switches
//
Int_t i;
for (i = 1; i < 501; i++) fDefMDCY[i] = GetMDCY(i,1);
for (i = 1; i < 2001; i++) fDefMDME[i] = GetMDME(i,1);
}
#ifndef WIN32
#define pyr pyr_
#define pyrset pyrset_
#define pyrget pyrget_
#else
#define pyr PYR
#define pyrset PYRSET
#define pyrget PYRGET
#endif
extern "C" {
Double_t pyr(Int_t*) {return sRandom->Rndm();}
void pyrset(Int_t*,Int_t*) {}
void pyrget(Int_t*,Int_t*) {}
}
<commit_msg>Pyr gives random number r in interval 0 < r < 1.<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. *
**************************************************************************/
/*
$Log$
Revision 1.22 2002/04/26 10:28:48 morsch
Option kPyBeautyPbMNR added (N. Carrer).
Revision 1.21 2002/03/25 14:46:16 morsch
Case kPyD0PbMNR added (N. Carrer).
Revision 1.20 2002/03/03 13:48:50 morsch
Option kPyCharmPbMNR added. Produce charm pairs in agreement with MNR
NLO calculations (Nicola Carrer).
Revision 1.19 2002/02/20 08:52:20 morsch
Correct documentation of SetNuclei method.
Revision 1.18 2002/02/07 10:43:06 morsch
Tuned pp-min.bias settings (M.Monteno, R.Ugoccioni and N.Carrer)
Revision 1.17 2001/12/19 15:40:43 morsch
For kPyJets enforce simple jet topology, i.e no initial or final state
gluon radiation and no primordial pT.
Revision 1.16 2001/10/12 11:13:59 morsch
Missing break statements added (thanks to Nicola Carrer)
Revision 1.15 2001/03/27 10:54:50 morsch
Add ResetDecayTable() and SsetDecayTable() methods.
Revision 1.14 2001/03/09 13:03:40 morsch
Process_t and Struc_Func_t moved to AliPythia.h
Revision 1.13 2000/12/18 08:55:35 morsch
Make AliPythia dependent generartors work with new scheme of random number generation
Revision 1.12 2000/11/30 07:12:50 alibrary
Introducing new Rndm and QA classes
Revision 1.11 2000/10/20 06:30:06 fca
Use version 0 to avoid streamer generation
Revision 1.10 2000/10/06 14:18:44 morsch
Upper cut of prim. pT distribution set to 5. GeV
Revision 1.9 2000/09/18 10:41:35 morsch
Add possibility to use nuclear structure functions from PDF library V8.
Revision 1.8 2000/09/06 14:26:24 morsch
Decayer functionality of AliPythia has been moved to AliDecayerPythia.
Class is now a singleton.
Revision 1.7 2000/06/09 20:34:50 morsch
All coding rule violations except RS3 corrected
Revision 1.6 1999/11/09 07:38:48 fca
Changes for compatibility with version 2.23 of ROOT
Revision 1.5 1999/11/03 17:43:20 fca
New version from G.Martinez & A.Morsch
Revision 1.4 1999/09/29 09:24:14 fca
Introduction of the Copyright and cvs Log
*/
#include "AliPythia.h"
ClassImp(AliPythia)
//_____________________________________________________________________________
AliPythia* AliPythia::fgAliPythia=NULL;
AliPythia::AliPythia()
{
// Default Constructor
//
// Set random number
if (!sRandom) sRandom=fRandom;
}
void AliPythia::ProcInit(Process_t process, Float_t energy, StrucFunc_t strucfunc)
{
// Initialise the process to generate
fProcess = process;
fEcms = energy;
fStrucFunc = strucfunc;
// don't decay p0
SetMDCY(Pycomp(111),1,0);
// select structure function
SetMSTP(52,2);
SetMSTP(51,strucfunc);
//
// Pythia initialisation for selected processes//
//
// Make MSEL clean
//
for (Int_t i=1; i<= 200; i++) {
SetMSUB(i,0);
}
// select charm production
switch (process)
{
case kPyCharm:
SetMSEL(4);
//
// heavy quark masses
SetPMAS(4,1,1.2);
SetMSTU(16,2);
//
// primordial pT
SetMSTP(91,1);
SetPARP(91,1.);
SetPARP(93,5.);
//
break;
case kPyBeauty:
SetMSEL(5);
SetPMAS(5,1,4.75);
SetMSTU(16,2);
break;
case kPyJpsi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
break;
case kPyJpsiChi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
// gg-> chi_0c g
SetMSUB(87,1);
// gg-> chi_1c g
SetMSUB(88,1);
// gg-> chi_2c g
SetMSUB(89,1);
break;
case kPyCharmUnforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
break;
case kPyBeautyUnforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
break;
case kPyMb:
// Minimum Bias pp-Collisions
//
//
// select Pythia min. bias model
SetMSEL(0);
SetMSUB(92,1); // single diffraction AB-->XB
SetMSUB(93,1); // single diffraction AB-->AX
SetMSUB(94,1); // double diffraction
SetMSUB(95,1); // low pt production
SetMSTP(81,1); // multiple interactions switched on
SetMSTP(82,3); // model with varying impact param. & a single Gaussian
SetPARP(82,3.47); // set value pT_0 for turn-off of the cross section of
// multiple interaction at a reference energy = 14000 GeV
SetPARP(89,14000.); // reference energy for the above parameter
SetPARP(90,0.174); // set exponent for energy dependence of pT_0
break;
case kPyJets:
SetMSEL(1);
// no initial state radiation
SetMSTP(61,0);
// no final state radiation
SetMSTP(71,0);
// no primordial pT
SetMSTP(91,0);
// SetMSTP(111,0);
SetMSTU(16,1);
SetMSTJ(1,1);
break;
case kPyDirectGamma:
SetMSEL(10);
break;
case kPyCharmPbMNR:
case kPyD0PbMNR:
// Tuning of Pythia parameters aimed to get a resonable agreement
// between with the NLO calculation by Mangano, Nason, Ridolfi for the
// c-cbar single inclusive and double differential distributions.
// This parameter settings are meant to work with Pb-Pb collisions
// (AliGenPythia::SetNuclei) and with kCTEQ_4L PDFs.
// To get a good agreement the minimum ptHard (AliGenPythia::SetPtHard)
// has to be set to 2.1GeV. Example in ConfigCharmPPR.C.
// All QCD processes
SetMSEL(1);
// No multiple interactions
SetMSTP(81,0);
SetPARP(81,0.0);
SetPARP(82,0.0);
// Initial/final parton shower on (Pythia default)
SetMSTP(61,1);
SetMSTP(71,1);
// 2nd order alpha_s
SetMSTP(2,2);
// QCD scales
SetMSTP(32,2);
SetPARP(34,1.0);
// Intrinsic <kT^2>
SetMSTP(91,1);
SetPARP(91,1.304);
SetPARP(93,6.52);
// Set c-quark mass
SetPMAS(4,1,1.2);
break;
case kPyBeautyPbMNR:
// Tuning of Pythia parameters aimed to get a resonable agreement
// between with the NLO calculation by Mangano, Nason, Ridolfi for the
// b-bbar single inclusive and double differential distributions.
// This parameter settings are meant to work with Pb-Pb collisions
// (AliGenPythia::SetNuclei) and with kCTEQ4L PDFs.
// To get a good agreement the minimum ptHard (AliGenPythia::SetPtHard)
// has to be set to 2.75GeV. Example in ConfigBeautyPPR.C.
// All QCD processes
SetMSEL(1);
// No multiple interactions
SetMSTP(81,0);
SetPARP(81,0.0);
SetPARP(82,0.0);
// Initial/final parton shower on (Pythia default)
SetMSTP(61,1);
SetMSTP(71,1);
// 2nd order alpha_s
SetMSTP(2,2);
// QCD scales
SetMSTP(32,2);
SetPARP(34,1.0);
SetPARP(67,1.0);
SetPARP(71,1.0);
// Intrinsic <kT^2>
SetMSTP(91,1);
SetPARP(91,2.035);
SetPARP(93,10.17);
// Set b-quark mass
SetPMAS(5,1,4.75);
break;
}
//
// Initialize PYTHIA
SetMSTP(41,1); // all resonance decays switched on
Initialize("CMS","p","p",fEcms);
}
Int_t AliPythia::CheckedLuComp(Int_t kf)
{
// Check Lund particle code (for debugging)
Int_t kc=Pycomp(kf);
printf("\n Lucomp kf,kc %d %d",kf,kc);
return kc;
}
void AliPythia::SetNuclei(Int_t a1, Int_t a2)
{
// Treat protons as inside nuclei with mass numbers a1 and a2
// The MSTP array in the PYPARS common block is used to enable and
// select the nuclear structure functions.
// MSTP(52) : (D=1) choice of proton and nuclear structure-function library
// =1: internal PYTHIA acording to MSTP(51)
// =2: PDFLIB proton s.f., with MSTP(51) = 1000xNGROUP+NSET
// If the following mass number both not equal zero, nuclear corrections of the stf are used.
// MSTP(192) : Mass number of nucleus side 1
// MSTP(193) : Mass number of nucleus side 2
SetMSTP(52,2);
SetMSTP(192, a1);
SetMSTP(193, a2);
}
AliPythia* AliPythia::Instance()
{
// Set random number generator
if (fgAliPythia) {
return fgAliPythia;
} else {
fgAliPythia = new AliPythia();
return fgAliPythia;
}
}
void AliPythia::PrintParticles()
{
// Print list of particl properties
Int_t np = 0;
for (Int_t kf=0; kf<1000000; kf++) {
for (Int_t c = 1; c > -2; c-=2) {
Int_t kc = Pycomp(c*kf);
if (kc) {
Float_t mass = GetPMAS(kc,1);
Float_t width = GetPMAS(kc,2);
Float_t tau = GetPMAS(kc,4);
char* name = new char[8];
Pyname(kf,name);
np++;
printf("\n mass, width, tau: %6d %s %10.3f %10.3e %10.3e",
c*kf, name, mass, width, tau);
}
}
}
printf("\n Number of particles %d \n \n", np);
}
void AliPythia::ResetDecayTable()
{
// Set default values for pythia decay switches
Int_t i;
for (i = 1; i < 501; i++) SetMDCY(i,1,fDefMDCY[i]);
for (i = 1; i < 2001; i++) SetMDME(i,1,fDefMDME[i]);
}
void AliPythia::SetDecayTable()
{
// Set default values for pythia decay switches
//
Int_t i;
for (i = 1; i < 501; i++) fDefMDCY[i] = GetMDCY(i,1);
for (i = 1; i < 2001; i++) fDefMDME[i] = GetMDME(i,1);
}
#ifndef WIN32
#define pyr pyr_
#define pyrset pyrset_
#define pyrget pyrget_
#else
#define pyr PYR
#define pyrset PYRSET
#define pyrget PYRGET
#endif
extern "C" {
Double_t pyr(Int_t*)
{
Float_t r;
do r=sRandom->Rndm(); while(0 >= r || r >= 1);
return r;
}
void pyrset(Int_t*,Int_t*) {}
void pyrget(Int_t*,Int_t*) {}
}
<|endoftext|> |
<commit_before>#include "controlpanel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
controlPanel::controlPanel(QWidget *parent) :
QWidget(parent),
_playPauseButton(new QPushButton("Play/Pause")),
_nextButton(new QPushButton("Next")),
_previousButton(new QPushButton("Previous")),
_volumeSlider(new QSlider(Qt::Horizontal)),
_currentState(controlPanel::Paused)
{
_volumeSlider->setRange(0,100);
_volumeSlider->setValue(50);
QVBoxLayout * layout = new QVBoxLayout;
QHBoxLayout * buttonLayout = new QHBoxLayout;
QHBoxLayout * optionsLayout = new QHBoxLayout;
buttonLayout->addWidget(_previousButton);
buttonLayout->addWidget(_playPauseButton);
buttonLayout->addWidget(_nextButton);
optionsLayout->addWidget(_volumeSlider);
layout->addLayout(optionsLayout);
layout->addLayout(buttonLayout);
connect(_playPauseButton, SIGNAL(clicked()), this, SLOT(togglePlayPauseState()));
connect(_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(recieveNewVolumeSliderValue(int)));
this->setLayout(layout);
}
const QObject * controlPanel::widget(Widget widget)
{
if(widget == controlPanel::PlayPauseButton)
return _playPauseButton;
else if(widget == controlPanel::NextButton)
return _nextButton;
else if(widget == controlPanel::PreviousButton)
return _previousButton;
else return new QObject;
}
void controlPanel::setPlayButtonIcon(const QIcon &icon)
{
_playButtonIcon = icon;
if(_currentState == controlPanel::Paused)
{
_playPauseButton->setText("");
_playPauseButton->setIcon(icon);
}
}
void controlPanel::setPauseButtonIcon(const QIcon &icon)
{
_pauseButtonIcon = icon;
if(_currentState == controlPanel::Playing)
{
_playPauseButton->setText("");
_playPauseButton->setIcon(icon);
}
}
void controlPanel::setNextButtonIcon(const QIcon &icon)
{
_nextButton->setText("");
_nextButton->setIcon(icon);
}
void controlPanel::setPreviousButtonIcon(const QIcon &icon)
{
_previousButton->setText("");
_previousButton->setIcon(icon);
}
void controlPanel::togglePlayPauseState()
{
if(_currentState == controlPanel::Paused)
{
_currentState = controlPanel::Playing;
if(!_playButtonIcon.isNull())
_playPauseButton->setIcon(_pauseButtonIcon);
else
_playPauseButton->setIcon(QIcon());
}
else if(_currentState == controlPanel::Playing)
{
_currentState = controlPanel::Paused;
if(!_pauseButtonIcon.isNull())
_playPauseButton->setIcon(_playButtonIcon);
else
_playPauseButton->setIcon(QIcon());
}
}
void controlPanel::recieveNewVolumeSliderValue(int value)
{
qDebug() << "Value changed to:" << value;
emit volumeSliderValueChanged(value);
}
void controlPanel::setState(controlPanel::PlayPauseButtonState state)
{
if(state != _currentState)
togglePlayPauseState();
}
<commit_msg>Got rid debug output for revieveNewVolumeSliderValue in controlPanel.<commit_after>#include "controlpanel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
controlPanel::controlPanel(QWidget *parent) :
QWidget(parent),
_playPauseButton(new QPushButton("Play/Pause")),
_nextButton(new QPushButton("Next")),
_previousButton(new QPushButton("Previous")),
_volumeSlider(new QSlider(Qt::Horizontal)),
_currentState(controlPanel::Paused)
{
_volumeSlider->setRange(0,100);
_volumeSlider->setValue(50);
QVBoxLayout * layout = new QVBoxLayout;
QHBoxLayout * buttonLayout = new QHBoxLayout;
QHBoxLayout * optionsLayout = new QHBoxLayout;
buttonLayout->addWidget(_previousButton);
buttonLayout->addWidget(_playPauseButton);
buttonLayout->addWidget(_nextButton);
optionsLayout->addWidget(_volumeSlider);
layout->addLayout(optionsLayout);
layout->addLayout(buttonLayout);
connect(_playPauseButton, SIGNAL(clicked()), this, SLOT(togglePlayPauseState()));
connect(_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(recieveNewVolumeSliderValue(int)));
this->setLayout(layout);
}
const QObject * controlPanel::widget(Widget widget)
{
if(widget == controlPanel::PlayPauseButton)
return _playPauseButton;
else if(widget == controlPanel::NextButton)
return _nextButton;
else if(widget == controlPanel::PreviousButton)
return _previousButton;
else return new QObject;
}
void controlPanel::setPlayButtonIcon(const QIcon &icon)
{
_playButtonIcon = icon;
if(_currentState == controlPanel::Paused)
{
_playPauseButton->setText("");
_playPauseButton->setIcon(icon);
}
}
void controlPanel::setPauseButtonIcon(const QIcon &icon)
{
_pauseButtonIcon = icon;
if(_currentState == controlPanel::Playing)
{
_playPauseButton->setText("");
_playPauseButton->setIcon(icon);
}
}
void controlPanel::setNextButtonIcon(const QIcon &icon)
{
_nextButton->setText("");
_nextButton->setIcon(icon);
}
void controlPanel::setPreviousButtonIcon(const QIcon &icon)
{
_previousButton->setText("");
_previousButton->setIcon(icon);
}
void controlPanel::togglePlayPauseState()
{
if(_currentState == controlPanel::Paused)
{
_currentState = controlPanel::Playing;
if(!_playButtonIcon.isNull())
_playPauseButton->setIcon(_pauseButtonIcon);
else
_playPauseButton->setIcon(QIcon());
}
else if(_currentState == controlPanel::Playing)
{
_currentState = controlPanel::Paused;
if(!_pauseButtonIcon.isNull())
_playPauseButton->setIcon(_playButtonIcon);
else
_playPauseButton->setIcon(QIcon());
}
}
void controlPanel::recieveNewVolumeSliderValue(int value)
{
emit volumeSliderValueChanged(value);
}
void controlPanel::setState(controlPanel::PlayPauseButtonState state)
{
if(state != _currentState)
togglePlayPauseState();
}
<|endoftext|> |
<commit_before>/* @author: Fabian Wegscheider */
#include <iostream>
#include <fstream>
#include <math.h>
#include <vector>
using namespace std;
int main(int numargs, char *args[]) {
if (numargs != 2) {
cerr << "Usage: " << args[0] << " filename" << endl;
exit(EXIT_FAILURE);
}
ifstream inputFile;
inputFile.open(args[1]);
if (inputFile.fail()) {
cerr << "file could not be read" << endl;
exit(EXIT_FAILURE);
}
string line;
vector<double> values[2];
double geoMean[2] {.0, .0};
int nLoc[2] {0, 0};
long nLines = 0;
int err = 0;
while (getline(inputFile, line)) {
nLines++;
if (line.empty()) { //empty lines are ignored
continue;
}
if (line.find("#") == 0) { //comment lines are ignored
continue;
}
int pos1 = line.find(";");
int pos2 = line.find(";", pos1+1);
int seqNum = 0;
int location = 0;
double value = 0;
try {
seqNum = stoi(line.substr(0,pos1));
location = stoi(line.substr(pos1+1, pos2-pos1-1));
value = stod(line.substr(pos2+1, line.length()-pos2-1));
} catch (...) {
err++; //test format of line
continue;
}
if (location < 1 || location > 2 || isnan(value) || value <=0 ) { //location must be positive
err++;
continue;
}
values[--location].push_back(value);
geoMean[location] += log(value);
nLoc[location]++;
}
for (int i = 0; i < 2; i++) {
geoMean[i] = exp(geoMean[i] / (double)nLoc[i]);
}
// writing output
cout << "File: " << args[1] << " with " << nLines << " lines" << endl;
for (int i = 0; i < 2; i++) {
cout << "Valid values Loc " << (i+1) << ": " << nLoc[i] << " with GeoMean " << geoMean[i] << endl;
}
cout << "Number of errors in the file: " << err << endl;
exit(EXIT_SUCCESS);
}
<commit_msg>fixed some bugs<commit_after>/* @author: Fabian Wegscheider */
#include <iostream>
#include <fstream>
#include <math.h>
#include <vector>
using namespace std;
int main(int numargs, char *args[]) {
if (numargs != 2) {
cerr << "Usage: " << args[0] << " filename" << endl;
exit(EXIT_FAILURE);
}
ifstream inputFile;
inputFile.open(args[1]);
if (inputFile.fail()) {
cerr << "file could not be read" << endl;
exit(EXIT_FAILURE);
}
string line;
vector<double> values[2];
double geoMean[2] {.0, .0};
int nLoc[2] {0, 0};
long nLines = 0;
int err = 0;
while (getline(inputFile, line)) {
nLines++;
if (line.empty()) { //empty lines are ignored
continue;
}
if (line.find("#") == 0) { //comment lines are ignored
continue;
}
size_t pos1 = line.find(";");
if (pos1 == string::npos) {
err++;
continue;
}
size_t pos2 = line.find(";", pos1+1);
if (pos2 == string::npos) {
err++;
continue;
}
int seqNum = 0;
int location = 0;
double value = 0;
try {
seqNum = stoi(line.substr(0,pos1));
location = stoi(line.substr(pos1+1, pos2-pos1-1));
value = stod(line.substr(pos2+1, line.length()-pos2-1));
} catch (...) {
err++; //test format of line
continue;
}
if (location < 1 || location > 2 || !isnormal(value) || value <= 0. ) { //location must be positive
err++;
continue;
}
values[--location].push_back(value);
geoMean[location] += log(value);
nLoc[location]++;
}
for (int i = 0; i < 2; i++) {
geoMean[i] = exp(geoMean[i] / (double)nLoc[i]);
}
// writing output
cout << "File: " << args[1] << " with " << nLines << " lines" << endl;
for (int i = 0; i < 2; i++) {
cout << "Valid values Loc" << (i+1) << ": " << nLoc[i] << " with GeoMean " << geoMean[i] << endl;
}
cout << "Number of errors in the file: " << err << endl;
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
struct state
{
int resource[100];
int claim[100][100];
int alloc[100][100];
int available[100];
}intitial,temp;
void saveState()
{
}
bool isSafe()
{
return true;
}
int main(){
int t=0, p, r, Time;
cout<<"Enter number of process(p) to simulate\n";
cin>>p;
cout<<"Enter number(r) of resources\n";
cin>>r;
cout<<"Enter the resource(R) vector\n";
for(int i=0;i<r;i++)
cin >> intitial.resource[i];
cout<<"Enter the amount of time to simulate\n";
cin>>Time;
while(t<Time){
saveState();
//generateRequest();
if(!isSafe()){
// restoreState();
}
t++;
}
return 0;
}<commit_msg>savestate<commit_after>#include <iostream>
using namespace std;
struct state
{
int resource[100];
int claim[100][100];
int alloc[100][100];
int available[100];
}intitial,temp;
void saveState()
{
for(int i=0;i<100;i++)
{
temp.resource[i]=intitial.resource[i];
temp.available[i]=intitial.available[i];
}
for(int i=0;i<100;i++)
{
for(int j=0;j<100;j++)
{
temp.alloc[i][j]=intitial.alloc[i][j];
temp.claim[i][j]=intitial.claim[i][j];
}
}
}
bool isSafe()
{
return true;
}
int main(){
int t=0, p, r, Time;
cout<<"Enter number of process(p) to simulate\n";
cin>>p;
cout<<"Enter number(r) of resources\n";
cin>>r;
cout<<"Enter the resource(R) vector\n";
for(int i=0;i<r;i++)
cin >> intitial.resource[i];
cout<<"Enter the amount of time to simulate\n";
cin>>Time;
while(t<Time){
saveState();
//generateRequest();
if(!isSafe()){
// restoreState();
}
t++;
}
return 0;
}<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2012, Stuart W Baker
* 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.
*
* \file HwInit.cxx
* This file represents the hardware initialization for the TI Tiva MCU.
*
* @author Stuart W. Baker
* @date 5 January 2013
*/
#include <cstdint>
#include <new>
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "TivaDev.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** UART 0 serial driver instance */
//static TivaUart uart0("/dev/ser0", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));
/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));
extern "C" {
/** Blink LED */
uint32_t blinker_pattern = 0;
static uint32_t rest_pattern = 0;
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
void timer5a_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
// Set output LED.
MAP_GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_6,
(rest_pattern & 1) ? GPIO_PIN_6 : 0);
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
rest_pattern = blinker_pattern;
}
void diewith(uint32_t pattern)
{
vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
/** Configures a gpio pin for active-high output interfacing with the railroad
* (such as solenoids or relays). This output type is normally low and it is
* important not to keep it high or floating for too long even during boot. */
void set_gpio_output(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPinWrite(port, pin, 0);
}
/** Configures a gpio pin for input with external pullup. */
void set_gpio_extinput(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
}
/** Configures a gpio pin for a button/switch (input with pullup). */
void set_gpio_switch(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
}
/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). */
void set_gpio_led(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0xff);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0xff);
}
/** Initialize the processor hardware.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
/* We initialize the output pins to their default state before doing the
* clock switching to avoid floating pins that interface to the
* railroad. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOC);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
set_gpio_led(GPIO_PORTD_BASE, GPIO_PIN_6); // Red led
set_gpio_led(GPIO_PORTB_BASE, GPIO_PIN_0); // Yellow led
set_gpio_led(GPIO_PORTD_BASE, GPIO_PIN_5); // Green led
set_gpio_led(GPIO_PORTG_BASE, GPIO_PIN_1); // Blue led 1
set_gpio_led(GPIO_PORTB_BASE, GPIO_PIN_6); // Blue led (for sw)
set_gpio_led(GPIO_PORTB_BASE, GPIO_PIN_7); // Gold led (for sw)
set_gpio_output(GPIO_PORTC_BASE, GPIO_PIN_4); // Rel0
set_gpio_output(GPIO_PORTC_BASE, GPIO_PIN_5); // Rel1
set_gpio_output(GPIO_PORTG_BASE, GPIO_PIN_5); // Rel2
set_gpio_output(GPIO_PORTF_BASE, GPIO_PIN_3); // Rel3
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_4); // Out0
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_5); // Out1
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_0); // Out2
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_1); // Out3
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_2); // Out4
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_3); // Out5
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_2); // Out6
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_3); // Out7
set_gpio_extinput(GPIO_PORTA_BASE, 0xff); // In0..7 -- all bits.
set_gpio_switch(GPIO_PORTC_BASE, GPIO_PIN_6); // Blue button
set_gpio_switch(GPIO_PORTC_BASE, GPIO_PIN_7); // Gold button
/* Setup the system clock. */
MAP_SysCtlClockSet(SYSCTL_SYSDIV_10 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_20MHZ);
/*MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3, GPIO_PIN_3);
MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);*/
/* Blinker timer initialization. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() / 8);
MAP_IntEnable(INT_TIMER5A);
/* This interrupt should hit even during kernel operations. */
MAP_IntPrioritySet(INT_TIMER5A, 0);
MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
MAP_TimerEnable(TIMER5_BASE, TIMER_A);
/* UART0 pin initialization */
/*MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
*/
/* USB0 pin initialization */
//MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
//MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);
/* CAN pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
MAP_GPIOPinConfigure(GPIO_PB4_CAN0RX);
MAP_GPIOPinConfigure(GPIO_PB5_CAN0TX);
MAP_GPIOPinTypeCAN(GPIO_PORTB_BASE, GPIO_PIN_4 | GPIO_PIN_5);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);
MAP_GPIOPinConfigure(GPIO_PB1_U1TX);
MAP_GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_1);
}
}
<commit_msg>switches bracz-ti-acc to 80 MHz.<commit_after>/** \copyright
* Copyright (c) 2012, Stuart W Baker
* 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.
*
* \file HwInit.cxx
* This file represents the hardware initialization for the TI Tiva MCU.
*
* @author Stuart W. Baker
* @date 5 January 2013
*/
#include <cstdint>
#include <new>
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "TivaDev.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** UART 0 serial driver instance */
//static TivaUart uart0("/dev/ser0", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));
/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));
extern "C" {
/** Blink LED */
uint32_t blinker_pattern = 0;
static uint32_t rest_pattern = 0;
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
void timer5a_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
// Set output LED.
MAP_GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_6,
(rest_pattern & 1) ? GPIO_PIN_6 : 0);
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
rest_pattern = blinker_pattern;
}
void diewith(uint32_t pattern)
{
vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
/** Configures a gpio pin for active-high output interfacing with the railroad
* (such as solenoids or relays). This output type is normally low and it is
* important not to keep it high or floating for too long even during boot. */
void set_gpio_output(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPinWrite(port, pin, 0);
}
/** Configures a gpio pin for input with external pullup. */
void set_gpio_extinput(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
}
/** Configures a gpio pin for a button/switch (input with pullup). */
void set_gpio_switch(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
}
/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). */
void set_gpio_led(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0xff);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0xff);
}
/** Initialize the processor hardware.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
/* We initialize the output pins to their default state before doing the
* clock switching to avoid floating pins that interface to the
* railroad. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOC);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
set_gpio_led(GPIO_PORTD_BASE, GPIO_PIN_6); // Red led
set_gpio_led(GPIO_PORTB_BASE, GPIO_PIN_0); // Yellow led
set_gpio_led(GPIO_PORTD_BASE, GPIO_PIN_5); // Green led
set_gpio_led(GPIO_PORTG_BASE, GPIO_PIN_1); // Blue led 1
set_gpio_led(GPIO_PORTB_BASE, GPIO_PIN_6); // Blue led (for sw)
set_gpio_led(GPIO_PORTB_BASE, GPIO_PIN_7); // Gold led (for sw)
set_gpio_output(GPIO_PORTC_BASE, GPIO_PIN_4); // Rel0
set_gpio_output(GPIO_PORTC_BASE, GPIO_PIN_5); // Rel1
set_gpio_output(GPIO_PORTG_BASE, GPIO_PIN_5); // Rel2
set_gpio_output(GPIO_PORTF_BASE, GPIO_PIN_3); // Rel3
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_4); // Out0
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_5); // Out1
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_0); // Out2
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_1); // Out3
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_2); // Out4
set_gpio_output(GPIO_PORTD_BASE, GPIO_PIN_3); // Out5
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_2); // Out6
set_gpio_output(GPIO_PORTE_BASE, GPIO_PIN_3); // Out7
set_gpio_extinput(GPIO_PORTA_BASE, 0xff); // In0..7 -- all bits.
set_gpio_switch(GPIO_PORTC_BASE, GPIO_PIN_6); // Blue button
set_gpio_switch(GPIO_PORTC_BASE, GPIO_PIN_7); // Gold button
/* Setup the system clock. */
MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_20MHZ);
/*MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3, GPIO_PIN_3);
MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);*/
/* Blinker timer initialization. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() / 8);
MAP_IntEnable(INT_TIMER5A);
/* This interrupt should hit even during kernel operations. */
MAP_IntPrioritySet(INT_TIMER5A, 0);
MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
MAP_TimerEnable(TIMER5_BASE, TIMER_A);
/* UART0 pin initialization */
/*MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
*/
/* USB0 pin initialization */
//MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
//MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);
/* CAN pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
MAP_GPIOPinConfigure(GPIO_PB4_CAN0RX);
MAP_GPIOPinConfigure(GPIO_PB5_CAN0TX);
MAP_GPIOPinTypeCAN(GPIO_PORTB_BASE, GPIO_PIN_4 | GPIO_PIN_5);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);
MAP_GPIOPinConfigure(GPIO_PB1_U1TX);
MAP_GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_1);
}
}
<|endoftext|> |
<commit_before>/**
Copyright 2017 Mayank Mathur
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 ERROR_SUBMISSION_ESMP
#include "error_submission.hpp"
#endif
#ifndef LARGEINT_ESMP
#define LARGEINT_ESMP
#include <vector>
#include <functional>
namespace esmp
{
/**
* How the std::vector<bool> is used to store binary:
* binary num: 0 1 0 1 0 0 1 0 0
* vector indices: 8 7 6 5 4 3 2 1 0
* */
class largeint
{
private:
typedef std::vector<bool> binary;
binary _internal_bin;
int _size;
bool _bin_changed = false;
std::vector<short int> _base10;
void _init_binary()
{
int i;
for (i = _internal_bin.size() - 1; i >= 0; --i)
if (_internal_bin[i])
break;
_size = i + 1;
_internal_bin.resize(_size);
}
binary _operate_on_binary_vectors(const binary &a, const binary &b, std::function<bool(bool, bool)> operation)
{
int itr, size;
if (a.size() > b.size())
{
itr = b.size();
size = a.size();
}
else
{
itr = a.size();
size = b.size();
}
binary _bin_new(size, 0);
for (int i = 0; i < itr; ++i)
_bin_new[i] = operation(b[i], a[i]);
if (size == a.size())
for (int i = itr; i < size; ++i)
_bin_new[i] = operation(a[i], 0);
else
for (int i = itr; i < size; ++i)
_bin_new[i] = operation(b[i], 0);
return _bin_new;
}
public:
/**
* @brief Initializer with lValue arg
* @param binary binary representation of the number as
* std::vector<bool> lValue
* */
largeint(const binary &binary)
{
_internal_bin = binary;
_init_binary();
_bin_changed = true;
}
/**
* @brief Initializer with rValue arg
* @param binary binary representation of the number as
* std::vector<bool> rValue
* */
largeint(const binary &&binary)
{
_internal_bin = binary;
_init_binary();
_bin_changed = true;
}
/**
* @brief Operator overload for =
* */
void operator=(const largeint &n)
{
_internal_bin = n._internal_bin;
_size = n._size;
_bin_changed = true;
}
/**
* @brief Operator overload for |
* */
largeint operator|(const largeint &n)
{
largeint _largeint(
std::move(_operate_on_binary_vectors(_internal_bin, n._internal_bin, [](bool a, bool b) { return a | b; })));
return _largeint;
}
/**
* @brief Operator overload for &
* */
largeint operator&(const largeint &n)
{
largeint _largeint(
std::move(_operate_on_binary_vectors(_internal_bin, n._internal_bin, [](bool a, bool b) { return a & b; })));
return _largeint;
}
/**
* @brief Operator overload for ^
* */
largeint operator^(const largeint &n)
{
largeint _largeint(
std::move(_operate_on_binary_vectors(_internal_bin, n._internal_bin, [](bool a, bool b) { return a ^ b; })));
return _largeint;
}
/**
* @brief Operator overload for +
* */
largeint operator+(largeint &n)
{
int size, tmp;
binary *l;
if (n._size > _size)
{
size = n._size;
tmp = _size;
l = &n._internal_bin;
}
else
{
size = _size;
tmp = n._size;
l = &_internal_bin;
}
binary _bin(size + 1);
int carry = 0;
int curr = 0;
for (int i = 0; i < tmp; ++i)
{
curr = carry + n._internal_bin[i] + _internal_bin[i];
carry = 0;
switch (curr)
{
case 0:
_bin[i] = 0;
break;
case 1:
_bin[i] = 1;
break;
case 2:
_bin[i] = 0;
carry = 1;
break;
case 3:
_bin[i] = 1;
carry = 1;
break;
}
}
for (int i = tmp; i < size; ++i)
{
curr = carry + (*l)[i];
carry = 0;
switch (curr)
{
case 0:
_bin[i] = 0;
break;
case 1:
_bin[i] = 1;
break;
case 2:
_bin[i] = 0;
carry = 1;
break;
}
}
_bin[size] = carry;
return largeint(_bin);
}
};
} // namespace esmp
#endif<commit_msg>Added << overload in largeint<commit_after>/**
Copyright 2017 Mayank Mathur
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 ERROR_SUBMISSION_ESMP
#include "error_submission.hpp"
#endif
#ifndef LARGEINT_ESMP
#define LARGEINT_ESMP
#include <vector>
#include <functional>
namespace esmp
{
/**
* How the std::vector<bool> is used to store binary:
* binary num: 0 1 0 1 0 0 1 0 0
* vector indices: 8 7 6 5 4 3 2 1 0
* */
class largeint
{
private:
typedef std::vector<bool> binary;
binary _internal_bin;
int _size;
bool _bin_changed = false;
bool _print_base10 = true;
std::vector<short int> _base10;
void _init_binary()
{
int i;
for (i = _internal_bin.size() - 1; i >= 0; --i)
if (_internal_bin[i])
break;
_size = i + 1;
_internal_bin.resize(_size);
}
binary _operate_on_binary_vectors(const binary &a, const binary &b, std::function<bool(bool, bool)> operation)
{
int itr, size;
if (a.size() > b.size())
{
itr = b.size();
size = a.size();
}
else
{
itr = a.size();
size = b.size();
}
binary _bin_new(size, 0);
for (int i = 0; i < itr; ++i)
_bin_new[i] = operation(b[i], a[i]);
if (size == a.size())
for (int i = itr; i < size; ++i)
_bin_new[i] = operation(a[i], 0);
else
for (int i = itr; i < size; ++i)
_bin_new[i] = operation(b[i], 0);
return _bin_new;
}
public:
/**
* @brief Initializer with lValue arg
* @param binary binary representation of the number as
* std::vector<bool> lValue
* */
largeint(const binary &binary)
{
_internal_bin = binary;
_init_binary();
_bin_changed = true;
}
/**
* @brief Initializer with rValue arg
* @param binary binary representation of the number as
* std::vector<bool> rValue
* */
largeint(binary &&binary)
{
_internal_bin = binary;
_init_binary();
_bin_changed = true;
}
/**
* @brief Sets the base in which the number should be
* should be outputted with a << operator.
* The base would be 10 or 2.
* @param set bool value to set the base 10 if true,
* 2 if false.
* */
inline void set_output_base10(bool set)
{
_print_base10 = set;
}
/**
* @brief Operator overload for =
* */
void operator=(const largeint &n)
{
_internal_bin = n._internal_bin;
_size = n._size;
_bin_changed = true;
_print_base10 = n._print_base10;
}
/**
* @brief Operator overload for |
* */
largeint operator|(const largeint &n)
{
largeint _largeint(
std::move(_operate_on_binary_vectors(_internal_bin, n._internal_bin, [](bool a, bool b) { return a | b; })));
return _largeint;
}
/**
* @brief Operator overload for &
* */
largeint operator&(const largeint &n)
{
largeint _largeint(
std::move(_operate_on_binary_vectors(_internal_bin, n._internal_bin, [](bool a, bool b) { return a & b; })));
return _largeint;
}
/**
* @brief Operator overload for ^
* */
largeint operator^(const largeint &n)
{
largeint _largeint(
std::move(_operate_on_binary_vectors(_internal_bin, n._internal_bin, [](bool a, bool b) { return a ^ b; })));
return _largeint;
}
/**
* @brief Operator overload for +
* */
largeint operator+(largeint &n)
{
int size, tmp;
binary *l;
if (n._size > _size)
{
size = n._size;
tmp = _size;
l = &n._internal_bin;
}
else
{
size = _size;
tmp = n._size;
l = &_internal_bin;
}
binary _bin(size + 1);
int carry = 0;
int curr = 0;
for (int i = 0; i < tmp; ++i)
{
curr = carry + n._internal_bin[i] + _internal_bin[i];
carry = 0;
switch (curr)
{
case 0:
_bin[i] = 0;
break;
case 1:
_bin[i] = 1;
break;
case 2:
_bin[i] = 0;
carry = 1;
break;
case 3:
_bin[i] = 1;
carry = 1;
break;
}
}
for (int i = tmp; i < size; ++i)
{
curr = carry + (*l)[i];
carry = 0;
switch (curr)
{
case 0:
_bin[i] = 0;
break;
case 1:
_bin[i] = 1;
break;
case 2:
_bin[i] = 0;
carry = 1;
break;
}
}
_bin[size] = carry;
return largeint(_bin);
}
/// I/O overloads
/**
* @brief Operator overload for << out stream
* */
friend std::ofstream &operator<<(std::ofstream &out, const largeint &n)
{
if (!n._print_base10)
{
for (int i = n._size - 1; i >= 0; --i)
out << n._internal_bin[i];
}
}
};
} // namespace esmp
#endif<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Opposite Renderer
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
#include "Application.hxx"
#include "RunningStatus.h"
#include <QMetaType>
#include <QApplication>
#include <QThread>
#include <QMessageBox>
Application::Application(QApplication & qApplication) :
m_sequenceNumber(0),
m_runningStatus(RunningStatus::STOPPED),
m_renderMethod(RenderMethod::PROGRESSIVE_PHOTON_MAPPING),
m_rendererStatus(RendererStatus::NOT_INITIALIZED)
{
qRegisterMetaType<RunningStatus::E>("RunningStatus::E");
// Move scene manager to a thread
m_sceneManagerThread = new QThread(&qApplication);
m_sceneManager.moveToThread(m_sceneManagerThread);
m_sceneManagerThread->start();
connect(&m_sceneManager, SIGNAL(sceneUpdated()), this, SLOT(onSceneUpdated()));
connect(&m_sceneManager, SIGNAL(sceneLoadingNew()), this, SLOT(onSceneLoadingNew()));
connect(&m_sceneManager, SIGNAL(sceneLoadError(QString)), this, SLOT(onSceneLoadError(QString)));
m_outputSettingsModel.setWidth(1280);
m_outputSettingsModel.setHeight(720);
m_outputSettingsModel.setGamma(1.0f);
m_PPMSettingsModel.setPPMInitialRadius(0.20);
connect(&m_outputSettingsModel, SIGNAL(resolutionUpdated()), this, SLOT(onOutputSettingsUpdated()));
connect(&m_PPMSettingsModel, SIGNAL(updated()), this, SLOT(onPPMSettingsUpdated()));
onOutputSettingsUpdated();
onPPMSettingsUpdated();
}
void Application::onAboutToQuit()
{
setRunningStatus(RunningStatus::STOPPED);
}
void Application::waitOnApplicationFinished()
{
m_sceneManagerThread->quit();
m_sceneManagerThread->wait();
}
OutputSettingsModel & Application::getOutputSettingsModel()
{
return m_outputSettingsModel;
}
PPMSettingsModel & Application::getPPMSettingsModel()
{
return m_PPMSettingsModel;
}
Camera & Application::getCamera()
{
return m_camera;
}
SceneManager & Application::getSceneManager()
{
return m_sceneManager;
}
const SceneManager & Application::getSceneManager() const
{
return m_sceneManager;
}
RenderMethod::E Application::getRenderMethod() const
{
return m_renderMethod;
}
void Application::setRenderMethod(RenderMethod::E method)
{
incrementSequenceNumber();
m_renderMethod = method;
emit renderMethodChanged();
}
unsigned int Application::getWidth() const
{
return m_outputSettingsModel.getWidth();
}
unsigned int Application::getHeight() const
{
return m_outputSettingsModel.getHeight();
}
void Application::onCameraUpdated()
{
emit cameraUpdated();
incrementSequenceNumber();
}
unsigned long long Application::getSequenceNumber() const
{
return m_sequenceNumber;
}
void Application::incrementSequenceNumber()
{
m_sequenceNumber++;
m_renderStatisticsModel.setNumIterations(0);
m_renderStatisticsModel.setNumPreviewedIterations(0);
resetRenderTime();
emit sequenceNumberIncremented();
}
void Application::onRenderRestart()
{
incrementSequenceNumber();
setRunningStatus(RunningStatus::RUNNING);
}
void Application::onRenderStatusToggle()
{
if(m_runningStatus == RunningStatus::STOPPED)
{
onRenderRestart();
}
else if(m_runningStatus == RunningStatus::RUNNING)
{
setRunningStatus(RunningStatus::PAUSE);
pauseRenderTime();
}
else
{
setRunningStatus(RunningStatus::RUNNING);
resumeRenderTime();
}
}
void Application::setCameraToSceneDefault()
{
m_camera = m_sceneManager.getScene()->getDefaultCamera();
m_camera.setAspectRatio(m_outputSettingsModel.getAspectRatio());
onCameraUpdated();
}
void Application::onOutputSettingsUpdated()
{
m_camera.setAspectRatio(m_outputSettingsModel.getAspectRatio());
onCameraUpdated();
}
void Application::onPPMSettingsUpdated()
{
incrementSequenceNumber();
}
RenderStatisticsModel & Application::getRenderStatisticsModel()
{
return m_renderStatisticsModel;
}
const RenderStatisticsModel & Application::getRenderStatisticsModel() const
{
return m_renderStatisticsModel;
}
float Application::getRenderTimeSeconds() const
{
if(m_runningStatus == RunningStatus::RUNNING)
{
return m_renderElapsedSeconds + ((float)m_renderTime.elapsed()/1000);
}
return m_renderElapsedSeconds;
}
void Application::resetRenderTime()
{
m_renderTime.restart();
m_renderElapsedSeconds = 0;
}
void Application::pauseRenderTime()
{
m_renderElapsedSeconds += m_renderTime.elapsed()/1000.0f;
}
void Application::resumeRenderTime()
{
m_renderTime.restart();
}
void Application::onSceneLoadingNew()
{
setRunningStatus(RunningStatus::PAUSE);
}
void Application::onSceneUpdated()
{
m_camera = m_sceneManager.getScene()->getDefaultCamera();
m_camera.setAspectRatio(m_outputSettingsModel.getAspectRatio());
m_PPMSettingsModel.setPPMInitialRadius(m_sceneManager.getScene()->getSceneInitialPPMRadiusEstimate());
onCameraUpdated();
onRenderRestart();
}
void Application::onSceneLoadError(QString error)
{
emit applicationError(error);
}
void Application::onNewFrameReadyForDisplay(const float*, unsigned long long )
{
m_renderStatisticsModel.incrementNumPreviewedIterations();
}
RendererStatus::E Application::getRendererStatus() const
{
return m_rendererStatus;
}
void Application::setRendererStatus( RendererStatus::E val )
{
bool shouldEmit = m_rendererStatus != val;
m_rendererStatus = val;
if(shouldEmit)
{
emit rendererStatusChanged();
}
}
RunningStatus::E Application::getRunningStatus() const
{
return m_runningStatus;
}
void Application::setRunningStatus( RunningStatus::E val )
{
bool shouldEmit = m_runningStatus != val;
m_runningStatus = val;
if(shouldEmit)
{
emit runningStatusChanged();
}
}
<commit_msg>Gamma to 2.8f<commit_after>/*
* Copyright (c) 2013 Opposite Renderer
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
#include "Application.hxx"
#include "RunningStatus.h"
#include <QMetaType>
#include <QApplication>
#include <QThread>
#include <QMessageBox>
Application::Application(QApplication & qApplication) :
m_sequenceNumber(0),
m_runningStatus(RunningStatus::STOPPED),
m_renderMethod(RenderMethod::PROGRESSIVE_PHOTON_MAPPING),
m_rendererStatus(RendererStatus::NOT_INITIALIZED)
{
qRegisterMetaType<RunningStatus::E>("RunningStatus::E");
// Move scene manager to a thread
m_sceneManagerThread = new QThread(&qApplication);
m_sceneManager.moveToThread(m_sceneManagerThread);
m_sceneManagerThread->start();
connect(&m_sceneManager, SIGNAL(sceneUpdated()), this, SLOT(onSceneUpdated()));
connect(&m_sceneManager, SIGNAL(sceneLoadingNew()), this, SLOT(onSceneLoadingNew()));
connect(&m_sceneManager, SIGNAL(sceneLoadError(QString)), this, SLOT(onSceneLoadError(QString)));
m_outputSettingsModel.setWidth(1280);
m_outputSettingsModel.setHeight(720);
m_outputSettingsModel.setGamma(2.8f);
m_PPMSettingsModel.setPPMInitialRadius(0.20);
connect(&m_outputSettingsModel, SIGNAL(resolutionUpdated()), this, SLOT(onOutputSettingsUpdated()));
connect(&m_PPMSettingsModel, SIGNAL(updated()), this, SLOT(onPPMSettingsUpdated()));
onOutputSettingsUpdated();
onPPMSettingsUpdated();
}
void Application::onAboutToQuit()
{
setRunningStatus(RunningStatus::STOPPED);
}
void Application::waitOnApplicationFinished()
{
m_sceneManagerThread->quit();
m_sceneManagerThread->wait();
}
OutputSettingsModel & Application::getOutputSettingsModel()
{
return m_outputSettingsModel;
}
PPMSettingsModel & Application::getPPMSettingsModel()
{
return m_PPMSettingsModel;
}
Camera & Application::getCamera()
{
return m_camera;
}
SceneManager & Application::getSceneManager()
{
return m_sceneManager;
}
const SceneManager & Application::getSceneManager() const
{
return m_sceneManager;
}
RenderMethod::E Application::getRenderMethod() const
{
return m_renderMethod;
}
void Application::setRenderMethod(RenderMethod::E method)
{
incrementSequenceNumber();
m_renderMethod = method;
emit renderMethodChanged();
}
unsigned int Application::getWidth() const
{
return m_outputSettingsModel.getWidth();
}
unsigned int Application::getHeight() const
{
return m_outputSettingsModel.getHeight();
}
void Application::onCameraUpdated()
{
emit cameraUpdated();
incrementSequenceNumber();
}
unsigned long long Application::getSequenceNumber() const
{
return m_sequenceNumber;
}
void Application::incrementSequenceNumber()
{
m_sequenceNumber++;
m_renderStatisticsModel.setNumIterations(0);
m_renderStatisticsModel.setNumPreviewedIterations(0);
resetRenderTime();
emit sequenceNumberIncremented();
}
void Application::onRenderRestart()
{
incrementSequenceNumber();
setRunningStatus(RunningStatus::RUNNING);
}
void Application::onRenderStatusToggle()
{
if(m_runningStatus == RunningStatus::STOPPED)
{
onRenderRestart();
}
else if(m_runningStatus == RunningStatus::RUNNING)
{
setRunningStatus(RunningStatus::PAUSE);
pauseRenderTime();
}
else
{
setRunningStatus(RunningStatus::RUNNING);
resumeRenderTime();
}
}
void Application::setCameraToSceneDefault()
{
m_camera = m_sceneManager.getScene()->getDefaultCamera();
m_camera.setAspectRatio(m_outputSettingsModel.getAspectRatio());
onCameraUpdated();
}
void Application::onOutputSettingsUpdated()
{
m_camera.setAspectRatio(m_outputSettingsModel.getAspectRatio());
onCameraUpdated();
}
void Application::onPPMSettingsUpdated()
{
incrementSequenceNumber();
}
RenderStatisticsModel & Application::getRenderStatisticsModel()
{
return m_renderStatisticsModel;
}
const RenderStatisticsModel & Application::getRenderStatisticsModel() const
{
return m_renderStatisticsModel;
}
float Application::getRenderTimeSeconds() const
{
if(m_runningStatus == RunningStatus::RUNNING)
{
return m_renderElapsedSeconds + ((float)m_renderTime.elapsed()/1000);
}
return m_renderElapsedSeconds;
}
void Application::resetRenderTime()
{
m_renderTime.restart();
m_renderElapsedSeconds = 0;
}
void Application::pauseRenderTime()
{
m_renderElapsedSeconds += m_renderTime.elapsed()/1000.0f;
}
void Application::resumeRenderTime()
{
m_renderTime.restart();
}
void Application::onSceneLoadingNew()
{
setRunningStatus(RunningStatus::PAUSE);
}
void Application::onSceneUpdated()
{
m_camera = m_sceneManager.getScene()->getDefaultCamera();
m_camera.setAspectRatio(m_outputSettingsModel.getAspectRatio());
m_PPMSettingsModel.setPPMInitialRadius(m_sceneManager.getScene()->getSceneInitialPPMRadiusEstimate());
onCameraUpdated();
onRenderRestart();
}
void Application::onSceneLoadError(QString error)
{
emit applicationError(error);
}
void Application::onNewFrameReadyForDisplay(const float*, unsigned long long )
{
m_renderStatisticsModel.incrementNumPreviewedIterations();
}
RendererStatus::E Application::getRendererStatus() const
{
return m_rendererStatus;
}
void Application::setRendererStatus( RendererStatus::E val )
{
bool shouldEmit = m_rendererStatus != val;
m_rendererStatus = val;
if(shouldEmit)
{
emit rendererStatusChanged();
}
}
RunningStatus::E Application::getRunningStatus() const
{
return m_runningStatus;
}
void Application::setRunningStatus( RunningStatus::E val )
{
bool shouldEmit = m_runningStatus != val;
m_runningStatus = val;
if(shouldEmit)
{
emit runningStatusChanged();
}
}
<|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$ */
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <iomanip.h>
#include <TObjArray.h>
#include <TRandom.h>
#include <TMath.h>
#include "AliITSpList.h"
//______________________________________________________________________
ClassImp(AliITSpList);
//______________________________________________________________________
AliITSpList::AliITSpList(){
// Default constructor
fNi = 0;
fNj = 0;
fa = 0;
}
//______________________________________________________________________
AliITSpList::AliITSpList(Int_t imax,Int_t jmax){
// Standard constructor
fNi = imax;
fNj = jmax;
fa = new TObjArray(fNi*fNj); // elements are zeroed by
// TObjArray creator
}
//______________________________________________________________________
AliITSpList::~AliITSpList(){
// Default destructor
for(Int_t i=0;i<GetMaxIndex();i++) if(fa->At(i)!=0){
delete fa->At(i);
fa->AddAt(0,i); // zero content
} // end for i && if
fNi = 0;
fNj = 0;
delete fa;
fa = 0;
}
//______________________________________________________________________
void AliITSpList::ClearMap(){
// Delete all AliITSpListItems and zero TObjArray.
for(Int_t i=0;i<GetMaxIndex();i++) if(fa->At(i)!=0){
delete fa->At(i);
fa->AddAt(0,i); // zero content
} // end for i && if
}
//______________________________________________________________________
void AliITSpList::DeleteHit(Int_t i,Int_t j){
// Delete a particular AliITSpListItems and zero TObjArray.
Int_t k = GetIndex(i,j);
if(fa->At(k)!=0){
delete fa->At(k);
fa->AddAt(0,k); // zero content
} // end for i && if
}
//______________________________________________________________________
AliITSpList& AliITSpList::operator=(const AliITSpList &source){
// = operator
if(this == &source) return *this;
if(this->fa!=0){ // if this->fa exists delete it first.
for(Int_t i=0;i<GetMaxIndex();i++) if(fa->At(i)!=0){
delete fa->At(i);
fa->AddAt(0,i); // zero content
} // end for i && if
delete this->fa;
} // end if this->fa!=0
this->fNi = source.fNi;
this->fNj = source.fNj;
this->fa = new TObjArray(*(source.fa));
return *this;
}
//______________________________________________________________________
AliITSpList::AliITSpList(AliITSpList &source){
// Copy operator
*this = source;
}
//______________________________________________________________________
void AliITSpList::AddSignal(Int_t i,Int_t j,Int_t trk,Int_t ht,Int_t mod,
Double_t signal){
// Adds a Signal value to the TObjArray at i,j. Creates the AliITSpListItem
// if needed.
if(GetpListItem(i,j)==0){ // most create AliITSpListItem
fa->AddAt(new AliITSpListItem(trk,ht,mod,GetIndex(i,j),signal),
GetIndex(i,j));
}else{ // AliITSpListItem exists, just add signal to it.
GetpListItem(i,j)->AddSignal(trk,ht,mod,GetIndex(i,j),signal);
} // end if
}
//______________________________________________________________________
void AliITSpList::AddNoise(Int_t i,Int_t j,Int_t mod,Double_t noise){
// Adds a noise value to the TObjArray at i,j. Creates the AliITSpListItem
// if needed.
if(GetpListItem(i,j)==0){ // most create AliITSpListItem
fa->AddAt(new AliITSpListItem(mod,GetIndex(i,j),noise),
GetIndex(i,j));
}else{ // AliITSpListItem exists, just add signal to it.
GetpListItem(i,j)->AddNoise(mod,GetIndex(i,j),noise);
} // end if
}
//______________________________________________________________________
ClassImp(AliITSpListItem)
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(){
// Default constructor
fmodule = -1;
findex = -1;
for(Int_t i=0;i<this->fkSize;i++){
this->fTrack[i] = -2;
this->fHits[i] = -2;
this->fSignal[i] = 0.0;
} // end if i
fTsignal = 0.0;
fNoise = 0.0;
}
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(Int_t module,Int_t index,Double_t noise){
// Standard noise constructor
this->fmodule = module;
this->findex = index;
for(Int_t i=0;i<this->fkSize;i++){
this->fTrack[i] = -2;
this->fSignal[i] = 0.0;
this->fHits[i] = 0;
} // end if i
this->fTsignal = 0.0;
this->fNoise = noise;
}
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(Int_t track,Int_t hit,Int_t module,
Int_t index,Double_t signal){
// Standard signal constructor
this->fmodule = module;
this->findex = index;
this->fTrack[0] = track;
this->fHits[0] = hit;
this->fSignal[0] = signal;
for(Int_t i=1;i<this->fkSize;i++){
this->fTrack[i] = -2;
this->fSignal[i] = 0.0;
this->fHits[i] = 0;
} // end if i
this->fTsignal = signal;
this->fNoise = 0.0;
}
//______________________________________________________________________
AliITSpListItem::~AliITSpListItem(){
// Denstructor
this->fmodule = 0;
this->findex =0;
for(Int_t i=0;i<=this->GetNsignals();i++){
this->fTrack[i] = 0;
this->fSignal[i] = 0.0;
this->fHits[i] = 0;
} // end if i
this->fTsignal = 0.0;
this->fNoise =0.0;
}
//______________________________________________________________________
AliITSpListItem& AliITSpListItem::operator=(const AliITSpListItem &source){
// = operator
if(this == &source) return *this;
this->fmodule = source.fmodule;
this->findex = source.findex;
for(Int_t i=0;i<this->fkSize;i++){
this->fTrack[i] = source.fTrack[i];
this->fSignal[i] = source.fSignal[i];
this->fHits[i] = source.fHits[i];
} // end if i
this->fTsignal = source.fTsignal;
this->fNoise = source.fNoise;
return *this;
}
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(AliITSpListItem &source){
// Copy operator
*this = source;
}
//______________________________________________________________________
void AliITSpListItem::AddSignal(Int_t track,Int_t hit,Int_t module,
Int_t index,Double_t signal){
// Adds this track number and sinal to the pList and orders them
Int_t i,j,trk,hts;
Double_t sig;
Bool_t flg=kFALSE;
if(findex!=index || fmodule!=module)
Warning("AddSignal","index=%d != findex=%d or module=%d != fmodule=%d",
index,findex,module,fmodule);
fTsignal += signal; // Keep track of sum signal.
if(signal<=fSignal[fkSize-1]) return; // smaller than smallest
for(i=0;i<fkSize;i++)if(track==fTrack[i] && hit ==fHits[i]){
fSignal[i] += signal;
flg = kTRUE;
} // end for i & if.
if(flg){ // resort arrays. fkSize is small use Insertin sort.
for(i=1;i<fkSize;i++){
trk = fTrack[i];
hts = fHits[i];
sig = fSignal[i];
j = i-1;
while(j>=0 && fSignal[i]>signal){
fTrack[j+1] = fTrack[j];
fHits[j+1] = fHits[j];
fSignal[j+1] = fSignal[j];
j--;
} // end while
fTrack[j+1] = trk;
fHits[j+1] = hts;
fSignal[j+1] = sig;
} // end if i
return;
} // end if added to existing and resorted array
// new entry add it in order.
// if this signal is <= smallest then don't add it.
if(signal <= fSignal[fkSize-1]) return;
for(i=fkSize-2;i>=0;i--){
if(signal > fSignal[i]){
fSignal[i+1] = fSignal[i];
fTrack[i+1] = fTrack[i];
fHits[i+1] = fHits[i];
}else{;
fSignal[i] = signal;
fTrack[i] = track;
fHits[i] = hit;
return; // put it in the right place, now exit.
} // end if
} // end if; end for i
// Still haven't found the right place. Must be at top of list.
fSignal[0] = signal;
fTrack[0] = track;
fHits[0] = hit;
return;
}
//______________________________________________________________________
void AliITSpListItem::AddNoise(Int_t module,Int_t index,Double_t noise){
// Addes noise to this existing list.
if(findex!=index || fmodule!=module)
Warning("AddSignal","index=%d != findex=%d or module=%d != fmodule=%d",
index,findex,module,fmodule);
fNoise += noise; // Keep track of sum signal.
}
//______________________________________________________________________
void AliITSpListItem::AddTo(Int_t fileIndex,AliITSpListItem *pl){
// Adds the contents of pl to this with track number off set given by
// fileIndex.
Int_t i,trk;
Double_t sig=0.0;
for(i=0;i<pl->GetNsignals()&&i<this->GetNsignals();i++){
trk = pl->GetTrack(i);
trk = pl->ShiftIndex(fileIndex,trk);
this->AddSignal(trk,pl->GetHit(i),pl->GetModule(),pl->GetIndex(),pl->GetSignal(i));
sig += pl->GetSignal(i);
} // end for i
this->fNoise += pl->fNoise;
return;
}
//______________________________________________________________________
Int_t AliITSpListItem::ShiftIndex(Int_t in,Int_t trk){
// Shift an index number to occupy the upper four bits.
Int_t si = sizeof(Int_t) * 8;
UInt_t uin,utrk; // use UInt_t to avoid interger overflow-> goes negitive.
uin = in;
utrk = trk;
for(Int_t i=0;i<si-4;i++) uin *= 2;
uin += utrk;
in = uin;
return in;
}
//______________________________________________________________________
void AliITSpListItem::Print(ostream *os){
//Standard output format for this class
Int_t i;
*os << fmodule <<","<<findex<<",";
*os << fkSize <<",";
for(i=0;i<fkSize;i++) *os << fTrack[i] <<",";
for(i=0;i<fkSize;i++) *os << fHits[i] <<",";
for(i=0;i<fkSize;i++) *os << fSignal[i] <<",";
*os << fTsignal <<","<< fNoise;
}
//______________________________________________________________________
void AliITSpListItem::Read(istream *is){
// Standard output streaming function.
Int_t i,iss;
*is >> fmodule >> findex;
*is >> iss; // read in fkSize
for(i=0;i<fkSize&&i<iss;i++) *is >> fTrack[i];
for(i=0;i<fkSize&&i<iss;i++) *is >> fHits[i];
for(i=0;i<fkSize&&i<iss;i++) *is >> fSignal[i];
*is >> fTsignal >> fNoise;
}
//______________________________________________________________________
ostream &operator<<(ostream &os,AliITSpListItem &source){
// Standard output streaming function.
source.Print(&os);
return os;
}
//______________________________________________________________________
istream &operator>>(istream &os,AliITSpListItem &source){
// Standard output streaming function.
source.Read(&os);
return os;
}
<commit_msg>Fixes in AliITSpListItem::AddSignal (M.Massera)<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$ */
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <iomanip.h>
#include <TObjArray.h>
#include <TRandom.h>
#include <TMath.h>
#include "AliITSpList.h"
//______________________________________________________________________
ClassImp(AliITSpList);
//______________________________________________________________________
AliITSpList::AliITSpList(){
// Default constructor
fNi = 0;
fNj = 0;
fa = 0;
}
//______________________________________________________________________
AliITSpList::AliITSpList(Int_t imax,Int_t jmax){
// Standard constructor
fNi = imax;
fNj = jmax;
fa = new TObjArray(fNi*fNj); // elements are zeroed by
// TObjArray creator
}
//______________________________________________________________________
AliITSpList::~AliITSpList(){
// Default destructor
for(Int_t i=0;i<GetMaxIndex();i++) if(fa->At(i)!=0){
delete fa->At(i);
fa->AddAt(0,i); // zero content
} // end for i && if
fNi = 0;
fNj = 0;
delete fa;
fa = 0;
}
//______________________________________________________________________
void AliITSpList::ClearMap(){
// Delete all AliITSpListItems and zero TObjArray.
for(Int_t i=0;i<GetMaxIndex();i++) if(fa->At(i)!=0){
delete fa->At(i);
fa->AddAt(0,i); // zero content
} // end for i && if
}
//______________________________________________________________________
void AliITSpList::DeleteHit(Int_t i,Int_t j){
// Delete a particular AliITSpListItems and zero TObjArray.
Int_t k = GetIndex(i,j);
if(fa->At(k)!=0){
delete fa->At(k);
fa->AddAt(0,k); // zero content
} // end for i && if
}
//______________________________________________________________________
AliITSpList& AliITSpList::operator=(const AliITSpList &source){
// = operator
if(this == &source) return *this;
if(this->fa!=0){ // if this->fa exists delete it first.
for(Int_t i=0;i<GetMaxIndex();i++) if(fa->At(i)!=0){
delete fa->At(i);
fa->AddAt(0,i); // zero content
} // end for i && if
delete this->fa;
} // end if this->fa!=0
this->fNi = source.fNi;
this->fNj = source.fNj;
this->fa = new TObjArray(*(source.fa));
return *this;
}
//______________________________________________________________________
AliITSpList::AliITSpList(AliITSpList &source){
// Copy operator
*this = source;
}
//______________________________________________________________________
void AliITSpList::AddSignal(Int_t i,Int_t j,Int_t trk,Int_t ht,Int_t mod,
Double_t signal){
// Adds a Signal value to the TObjArray at i,j. Creates the AliITSpListItem
// if needed.
if(GetpListItem(i,j)==0){ // most create AliITSpListItem
fa->AddAt(new AliITSpListItem(trk,ht,mod,GetIndex(i,j),signal),
GetIndex(i,j));
}else{ // AliITSpListItem exists, just add signal to it.
GetpListItem(i,j)->AddSignal(trk,ht,mod,GetIndex(i,j),signal);
} // end if
}
//______________________________________________________________________
void AliITSpList::AddNoise(Int_t i,Int_t j,Int_t mod,Double_t noise){
// Adds a noise value to the TObjArray at i,j. Creates the AliITSpListItem
// if needed.
if(GetpListItem(i,j)==0){ // most create AliITSpListItem
fa->AddAt(new AliITSpListItem(mod,GetIndex(i,j),noise),
GetIndex(i,j));
}else{ // AliITSpListItem exists, just add signal to it.
GetpListItem(i,j)->AddNoise(mod,GetIndex(i,j),noise);
} // end if
}
//______________________________________________________________________
ClassImp(AliITSpListItem)
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(){
// Default constructor
fmodule = -1;
findex = -1;
for(Int_t i=0;i<this->fkSize;i++){
this->fTrack[i] = -2;
this->fHits[i] = -2;
this->fSignal[i] = 0.0;
} // end if i
fTsignal = 0.0;
fNoise = 0.0;
}
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(Int_t module,Int_t index,Double_t noise){
// Standard noise constructor
this->fmodule = module;
this->findex = index;
for(Int_t i=0;i<this->fkSize;i++){
this->fTrack[i] = -2;
this->fSignal[i] = 0.0;
this->fHits[i] = 0;
} // end if i
this->fTsignal = 0.0;
this->fNoise = noise;
}
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(Int_t track,Int_t hit,Int_t module,
Int_t index,Double_t signal){
// Standard signal constructor
this->fmodule = module;
this->findex = index;
this->fTrack[0] = track;
this->fHits[0] = hit;
this->fSignal[0] = signal;
for(Int_t i=1;i<this->fkSize;i++){
this->fTrack[i] = -2;
this->fSignal[i] = 0.0;
this->fHits[i] = 0;
} // end if i
this->fTsignal = signal;
this->fNoise = 0.0;
}
//______________________________________________________________________
AliITSpListItem::~AliITSpListItem(){
// Denstructor
this->fmodule = 0;
this->findex =0;
for(Int_t i=0;i<=this->GetNsignals();i++){
this->fTrack[i] = 0;
this->fSignal[i] = 0.0;
this->fHits[i] = 0;
} // end if i
this->fTsignal = 0.0;
this->fNoise =0.0;
}
//______________________________________________________________________
AliITSpListItem& AliITSpListItem::operator=(const AliITSpListItem &source){
// = operator
if(this == &source) return *this;
this->fmodule = source.fmodule;
this->findex = source.findex;
for(Int_t i=0;i<this->fkSize;i++){
this->fTrack[i] = source.fTrack[i];
this->fSignal[i] = source.fSignal[i];
this->fHits[i] = source.fHits[i];
} // end if i
this->fTsignal = source.fTsignal;
this->fNoise = source.fNoise;
return *this;
}
//______________________________________________________________________
AliITSpListItem::AliITSpListItem(AliITSpListItem &source){
// Copy operator
*this = source;
}
//______________________________________________________________________
void AliITSpListItem::AddSignal(Int_t track,Int_t hit,Int_t module,
Int_t index,Double_t signal){
// Adds this track number and sinal to the pList and orders them
Int_t i,j,trk,hts;
Double_t sig;
Bool_t flg=kFALSE;
if(findex!=index || fmodule!=module)
Warning("AddSignal","index=%d != findex=%d or module=%d != fmodule=%d",
index,findex,module,fmodule);
fTsignal += signal; // Keep track of sum signal.
if(signal<=fSignal[fkSize-1]) return; // smaller than smallest
for(i=0;i<fkSize;i++)if(track==fTrack[i] && hit ==fHits[i]){
fSignal[i] += signal;
flg = kTRUE;
} // end for i & if.
if(flg){ // the arrays are already sorted with the possible exception
// of one element
j=0;
for(i=0;i<fkSize-1;i++){
if(fSignal[i]<fSignal[i+1]){
j=i+1;
break;
}
}
/* debug printouts
if(j>0){
cout<<"AliITSpListItem::AddSignal - before sorting - signal="<<signal<<" mod="<<module<<endl;
for(i=0;i<fkSize-1;i++)cout<<fSignal[i]<<" ";
cout<<fSignal[fkSize-1]<<endl;
}
*/
for(i=j;i>0;i--){
if(fSignal[i]>fSignal[i-1]){
trk = fTrack[i-1];
hts = fHits[i-1];
sig = fSignal[i-1];
fTrack[i-1]=fTrack[i];
fHits[i-1]=fHits[i];
fSignal[i-1]=fSignal[i];
fTrack[i]=trk;
fHits[i]=hts;
fSignal[i]=sig;
}
}
/* debug printouts
if(j>0){
cout<<"AliITSpListItem::AddSignal - after sorting\n";
for(i=0;i<fkSize-1;i++)cout<<fSignal[i]<<" ";
cout<<fSignal[fkSize-1]<<endl;
}
*/
return;
}
// new entry add it in order.
// if this signal is <= smallest then don't add it.
if(signal <= fSignal[fkSize-1]) return;
for(i=fkSize-2;i>=0;i--){
if(signal > fSignal[i]){
fSignal[i+1] = fSignal[i];
fTrack[i+1] = fTrack[i];
fHits[i+1] = fHits[i];
}else{
fSignal[i+1] = signal; // changed m.m.
fTrack[i+1] = track; // changed m.m.
fHits[i+1] = hit; // changed m.m.
return; // put it in the right place, now exit.
} // end if
} // end if; end for i
// Still haven't found the right place. Must be at top of list.
fSignal[0] = signal;
fTrack[0] = track;
fHits[0] = hit;
return;
}
//______________________________________________________________________
void AliITSpListItem::AddNoise(Int_t module,Int_t index,Double_t noise){
// Addes noise to this existing list.
if(findex!=index || fmodule!=module)
Warning("AddSignal","index=%d != findex=%d or module=%d != fmodule=%d",
index,findex,module,fmodule);
fNoise += noise; // Keep track of sum signal.
}
//______________________________________________________________________
void AliITSpListItem::AddTo(Int_t fileIndex,AliITSpListItem *pl){
// Adds the contents of pl to this with track number off set given by
// fileIndex.
Int_t i,trk;
Double_t sig=0.0;
for(i=0;i<pl->GetNsignals()&&i<this->GetNsignals();i++){
trk = pl->GetTrack(i);
trk = pl->ShiftIndex(fileIndex,trk);
this->AddSignal(trk,pl->GetHit(i),pl->GetModule(),pl->GetIndex(),pl->GetSignal(i));
sig += pl->GetSignal(i);
} // end for i
this->fNoise += pl->fNoise;
return;
}
//______________________________________________________________________
Int_t AliITSpListItem::ShiftIndex(Int_t in,Int_t trk){
// Shift an index number to occupy the upper four bits.
Int_t si = sizeof(Int_t) * 8;
UInt_t uin,utrk; // use UInt_t to avoid interger overflow-> goes negitive.
uin = in;
utrk = trk;
for(Int_t i=0;i<si-4;i++) uin *= 2;
uin += utrk;
in = uin;
return in;
}
//______________________________________________________________________
void AliITSpListItem::Print(ostream *os){
//Standard output format for this class
Int_t i;
*os << fmodule <<","<<findex<<",";
*os << fkSize <<",";
for(i=0;i<fkSize;i++) *os << fTrack[i] <<",";
for(i=0;i<fkSize;i++) *os << fHits[i] <<",";
for(i=0;i<fkSize;i++) *os << fSignal[i] <<",";
*os << fTsignal <<","<< fNoise;
}
//______________________________________________________________________
void AliITSpListItem::Read(istream *is){
// Standard output streaming function.
Int_t i,iss;
*is >> fmodule >> findex;
*is >> iss; // read in fkSize
for(i=0;i<fkSize&&i<iss;i++) *is >> fTrack[i];
for(i=0;i<fkSize&&i<iss;i++) *is >> fHits[i];
for(i=0;i<fkSize&&i<iss;i++) *is >> fSignal[i];
*is >> fTsignal >> fNoise;
}
//______________________________________________________________________
ostream &operator<<(ostream &os,AliITSpListItem &source){
// Standard output streaming function.
source.Print(&os);
return os;
}
//______________________________________________________________________
istream &operator>>(istream &os,AliITSpListItem &source){
// Standard output streaming function.
source.Read(&os);
return os;
}
<|endoftext|> |
<commit_before>// Copyright 2016 Duc Hoang Bui, KAIST. All rights reserved.
// Licensed under MIT ($LICENSE_URL)
#include "browser_profiler_impl_state.h"
#include <sstream>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/string_split.h"
namespace {
bool ReadExperimentCommandLines(
const base::FilePath& experiment_command_lines_file,
std::vector<std::string> *experiment_command_lines) {
if (!base::PathExists(experiment_command_lines_file)) {
LOG(ERROR) << "Experiment command line file not exist at: " << experiment_command_lines_file.value();
return false;
}
// More memory consumption, O(n), but reduce disk I/O by reading once
std::string lines;
if (!base::ReadFileToString(experiment_command_lines_file, &lines)) {
LOG(FATAL) << "Failed to read experiment command line file";
return false;
}
std::istringstream all_cmdlines(lines);
std::string cmdline;
while (getline(all_cmdlines, cmdline)) {
// Only get the command line with prefix "chrome"
if (StartsWithASCII(cmdline, "chrome ", /*case-sensitive*/ true)) {
experiment_command_lines->push_back(cmdline);
}
}
return true;
}
bool ReadExperimentUrlList(const base::FilePath& url_list_file,
std::vector<std::string> *url_list) {
std::string lines;
if (!base::ReadFileToString(url_list_file, &lines)) {
LOG(FATAL) << "Cannot read url list at " << url_list_file.value();
return false;
}
std::vector<std::string> list;
base::SplitString(lines, '\n', &list);
url_list->clear();
for (size_t i = 0; i < list.size(); ++i) {
std::string url = list[i];
if (!url.empty()) {
VLOG(1) << "Read url: " << url;
// Add http by default, if the url is just a host name
if (!StartsWithASCII(url, "http", true))
url = "http://" + url;
url_list->push_back(url);
}
}
return true;
}
} // namespace
namespace browser_profiler {
BrowserProfilerImplState::BrowserProfilerImplState() {
Reset();
}
void BrowserProfilerImplState::Reset() {
experiment_command_line_index = 0;
current_url_index = 0;
current_url_try_done = 0;
experiment_command_lines.clear();
experiment_urls.clear();
started = false;
all_experiments_finished = false;
start_new_experiments = false;
last_experiment_id = "last_experiment_id";
}
void BrowserProfilerImplState::Initialize(const base::FilePath& experiment_command_lines_file,
const base::FilePath& url_list_file) {
// Reset values after loading from file
Reset();
if (!ReadExperimentCommandLines(experiment_command_lines_file,
&experiment_command_lines)) {
LOG(ERROR) << "Fail to read experiment command lines";
}
if (!ReadExperimentUrlList(url_list_file, &experiment_urls)) {
LOG(FATAL) << "Fail to read experiment url list";
}
}
// No exception allowed in Chromium so we need to check each write
#define STREAM_WRITELN(stream, variable) \
do { \
stream << variable << std::endl; \
if (!stream.good()) { \
LOG(FATAL) << "Error writing string to stream"; \
return false; \
} \
} while (0);
// To save development time, use the simplest way: hardcode a format
// In the future, may use json Chromium's pickle (with crc32 check)
bool BrowserProfilerImplState::SaveToFile(const base::FilePath& file_name) {
std::ostringstream output;
STREAM_WRITELN(output, experiment_command_line_index);
STREAM_WRITELN(output, current_url_index);
STREAM_WRITELN(output, current_url_try_done);
STREAM_WRITELN(output, experiment_command_lines.size());
for (size_t i = 0; i < experiment_command_lines.size(); ++i) {
STREAM_WRITELN(output, experiment_command_lines[i]);
}
STREAM_WRITELN(output, experiment_urls.size());
for (size_t i = 0; i < experiment_urls.size(); ++i) {
STREAM_WRITELN(output, experiment_urls[i]);
}
STREAM_WRITELN(output, started);
STREAM_WRITELN(output, all_experiments_finished);
STREAM_WRITELN(output, start_new_experiments);
STREAM_WRITELN(output, last_experiment_id);
std::string output_str = output.str();
return WriteFile(file_name, output_str.c_str(), output_str.length());
}
// No exception allowed in Chromium so we need to check each read
// file_name and stream_str must match ones in LoadFromFile
#define STREAM_READ(stream, variable) \
do { \
stream >> variable; \
if (!stream.good()) { \
LOG(FATAL) << "Error parsing string from state file (" << file_name.value() \
<< "): " << state_str; \
return false; \
} \
} while (0);
// Load in the inverse order of saving
bool BrowserProfilerImplState::LoadFromFile(const base::FilePath& file_name) {
if (!base::PathExists(file_name)) {
LOG(ERROR) << "State file not exist at: " << file_name.value();
return false;
}
std::string state_str;
if (!base::ReadFileToString(file_name, &state_str)) {
LOG(FATAL) << "Cannot read state file: " << file_name.value();
return false;
}
std::istringstream input(state_str);
STREAM_READ(input, experiment_command_line_index);
STREAM_READ(input, current_url_index);
STREAM_READ(input, current_url_try_done);
size_t experiment_command_lines_size;
STREAM_READ(input, experiment_command_lines_size);
LOG(INFO) << "Experiment command lines size: " << experiment_command_lines_size;
experiment_command_lines.resize(experiment_command_lines_size);
// Skip all new lines, otherwise getline will have unexpected behavior
input.ignore(1000, '\n');
for (size_t i = 0; i < experiment_command_lines_size; ++i) {
std::string cmdline;
if (!std::getline(input, cmdline)) {
LOG(FATAL) << "Cannot read experiment command line";
}
LOG(INFO) << "Read command line: " << cmdline;
experiment_command_lines[i] = cmdline;
}
size_t experiment_urls_size;
STREAM_READ(input, experiment_urls_size);
experiment_urls.resize(experiment_urls_size);
for (size_t i = 0; i < experiment_urls_size; ++i) {
STREAM_READ(input, experiment_urls[i]);
}
STREAM_READ(input, started);
STREAM_READ(input, all_experiments_finished);
STREAM_READ(input, start_new_experiments);
STREAM_READ(input, last_experiment_id);
return true;
}
} // namespace browser_profiler
<commit_msg>read only url without beginning by #<commit_after>// Copyright 2016 Duc Hoang Bui, KAIST. All rights reserved.
// Licensed under MIT ($LICENSE_URL)
#include "browser_profiler_impl_state.h"
#include <sstream>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/string_split.h"
namespace {
bool ReadExperimentCommandLines(
const base::FilePath& experiment_command_lines_file,
std::vector<std::string> *experiment_command_lines) {
if (!base::PathExists(experiment_command_lines_file)) {
LOG(ERROR) << "Experiment command line file not exist at: " << experiment_command_lines_file.value();
return false;
}
// More memory consumption, O(n), but reduce disk I/O by reading once
std::string lines;
if (!base::ReadFileToString(experiment_command_lines_file, &lines)) {
LOG(FATAL) << "Failed to read experiment command line file";
return false;
}
std::istringstream all_cmdlines(lines);
std::string cmdline;
while (getline(all_cmdlines, cmdline)) {
// Only get the command line with prefix "chrome"
if (StartsWithASCII(cmdline, "chrome ", /*case-sensitive*/ true)) {
experiment_command_lines->push_back(cmdline);
}
}
return true;
}
bool ReadExperimentUrlList(const base::FilePath& url_list_file,
std::vector<std::string> *url_list) {
std::string lines;
if (!base::ReadFileToString(url_list_file, &lines)) {
LOG(FATAL) << "Cannot read url list at " << url_list_file.value();
return false;
}
std::vector<std::string> list;
base::SplitString(lines, '\n', &list);
url_list->clear();
for (size_t i = 0; i < list.size(); ++i) {
std::string url = list[i];
// Skip url starting with #
if (!url.empty() && !StartsWithASCII(url, "#", true)) {
VLOG(1) << "Read url: " << url;
// Add http by default, if the url is just a host name
if (!StartsWithASCII(url, "http", true))
url = "http://" + url;
url_list->push_back(url);
}
}
return true;
}
} // namespace
namespace browser_profiler {
BrowserProfilerImplState::BrowserProfilerImplState() {
Reset();
}
void BrowserProfilerImplState::Reset() {
experiment_command_line_index = 0;
current_url_index = 0;
current_url_try_done = 0;
experiment_command_lines.clear();
experiment_urls.clear();
started = false;
all_experiments_finished = false;
start_new_experiments = false;
last_experiment_id = "last_experiment_id";
}
void BrowserProfilerImplState::Initialize(const base::FilePath& experiment_command_lines_file,
const base::FilePath& url_list_file) {
// Reset values after loading from file
Reset();
if (!ReadExperimentCommandLines(experiment_command_lines_file,
&experiment_command_lines)) {
LOG(ERROR) << "Fail to read experiment command lines";
}
if (!ReadExperimentUrlList(url_list_file, &experiment_urls)) {
LOG(FATAL) << "Fail to read experiment url list";
}
}
// No exception allowed in Chromium so we need to check each write
#define STREAM_WRITELN(stream, variable) \
do { \
stream << variable << std::endl; \
if (!stream.good()) { \
LOG(FATAL) << "Error writing string to stream"; \
return false; \
} \
} while (0);
// To save development time, use the simplest way: hardcode a format
// In the future, may use json Chromium's pickle (with crc32 check)
bool BrowserProfilerImplState::SaveToFile(const base::FilePath& file_name) {
std::ostringstream output;
STREAM_WRITELN(output, experiment_command_line_index);
STREAM_WRITELN(output, current_url_index);
STREAM_WRITELN(output, current_url_try_done);
STREAM_WRITELN(output, experiment_command_lines.size());
for (size_t i = 0; i < experiment_command_lines.size(); ++i) {
STREAM_WRITELN(output, experiment_command_lines[i]);
}
STREAM_WRITELN(output, experiment_urls.size());
for (size_t i = 0; i < experiment_urls.size(); ++i) {
STREAM_WRITELN(output, experiment_urls[i]);
}
STREAM_WRITELN(output, started);
STREAM_WRITELN(output, all_experiments_finished);
STREAM_WRITELN(output, start_new_experiments);
STREAM_WRITELN(output, last_experiment_id);
std::string output_str = output.str();
return WriteFile(file_name, output_str.c_str(), output_str.length());
}
// No exception allowed in Chromium so we need to check each read
// file_name and stream_str must match ones in LoadFromFile
#define STREAM_READ(stream, variable) \
do { \
stream >> variable; \
if (!stream.good()) { \
LOG(FATAL) << "Error parsing string from state file (" << file_name.value() \
<< "): " << state_str; \
return false; \
} \
} while (0);
// Load in the inverse order of saving
bool BrowserProfilerImplState::LoadFromFile(const base::FilePath& file_name) {
if (!base::PathExists(file_name)) {
LOG(ERROR) << "State file not exist at: " << file_name.value();
return false;
}
std::string state_str;
if (!base::ReadFileToString(file_name, &state_str)) {
LOG(FATAL) << "Cannot read state file: " << file_name.value();
return false;
}
std::istringstream input(state_str);
STREAM_READ(input, experiment_command_line_index);
STREAM_READ(input, current_url_index);
STREAM_READ(input, current_url_try_done);
size_t experiment_command_lines_size;
STREAM_READ(input, experiment_command_lines_size);
LOG(INFO) << "Experiment command lines size: " << experiment_command_lines_size;
experiment_command_lines.resize(experiment_command_lines_size);
// Skip all new lines, otherwise getline will have unexpected behavior
input.ignore(1000, '\n');
for (size_t i = 0; i < experiment_command_lines_size; ++i) {
std::string cmdline;
if (!std::getline(input, cmdline)) {
LOG(FATAL) << "Cannot read experiment command line";
}
LOG(INFO) << "Read command line: " << cmdline;
experiment_command_lines[i] = cmdline;
}
size_t experiment_urls_size;
STREAM_READ(input, experiment_urls_size);
experiment_urls.resize(experiment_urls_size);
for (size_t i = 0; i < experiment_urls_size; ++i) {
STREAM_READ(input, experiment_urls[i]);
}
STREAM_READ(input, started);
STREAM_READ(input, all_experiments_finished);
STREAM_READ(input, start_new_experiments);
STREAM_READ(input, last_experiment_id);
return true;
}
} // namespace browser_profiler
<|endoftext|> |
<commit_before>/*==============================================================================
Library: MSVTK
Copyright (c) The University of Auckland.
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.
==============================================================================*/
#include "msvVTKEmbeddedProbeFilter.h"
#include "vtkCellData.h"
#include "vtkCell.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include <vector>
vtkStandardNewMacro(msvVTKEmbeddedProbeFilter);
class msvVTKEmbeddedProbeFilter::vtkVectorOfArrays :
public std::vector<vtkDataArray*>
{
};
//----------------------------------------------------------------------------
msvVTKEmbeddedProbeFilter::msvVTKEmbeddedProbeFilter()
{
this->SetNumberOfInputPorts(2);
this->CellIdArrayName = 0;
this->ParametricCoordinateArrayName = 0;
this->CellArrays = new vtkVectorOfArrays();
this->PointList = 0;
this->CellList = 0;
}
//----------------------------------------------------------------------------
msvVTKEmbeddedProbeFilter::~msvVTKEmbeddedProbeFilter()
{
delete this->CellArrays;
delete this->PointList;
delete this->CellList;
}
//----------------------------------------------------------------------------
void msvVTKEmbeddedProbeFilter::SetSourceConnection(
vtkAlgorithmOutput* algOutput)
{
this->SetInputConnection(1, algOutput);
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *source = vtkDataSet::SafeDownCast(
sourceInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
return this->Probe(input, source, output);
}
//----------------------------------------------------------------------------
void msvVTKEmbeddedProbeFilter::BuildFieldList(vtkDataSet* source)
{
delete this->PointList;
delete this->CellList;
this->PointList = new vtkDataSetAttributes::FieldList(1);
this->PointList->InitializeFieldList(source->GetPointData());
this->CellList = new vtkDataSetAttributes::FieldList(1);
this->CellList->InitializeFieldList(source->GetCellData());
}
//----------------------------------------------------------------------------
// * input -- dataset probed with
// * source -- dataset probed into
// * output - output.
void msvVTKEmbeddedProbeFilter::InitializeForProbing(vtkDataSet* input,
vtkDataSet* output)
{
if (!this->PointList || !this->CellList)
{
vtkErrorMacro("BuildFieldList() must be called before calling this method.");
return;
}
vtkIdType numPts = input->GetNumberOfPoints();
// First, copy the input to the output as a starting point
output->CopyStructure(input);
// Pass here so that the attributes/fields can be over-written later
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
output->GetFieldData()->PassData(input->GetFieldData());
// vtkPointSet-derived outputs have points coordinates probed,
// so allocate and replace the referenced ones set by CopyStructure()
vtkPointSet *pointSet = vtkPointSet::SafeDownCast(output);
if (pointSet)
{
vtkPoints *points = vtkPoints::New();
points->DeepCopy(pointSet->GetPoints());
pointSet->SetPoints(points);
points->Delete();
}
vtkPointData* outPD = output->GetPointData();
// Allocate storage for output PointData
// All source PD is sampled to output as PD. Those arrays in source CD that
// are not present in output PD will be passed as output PD.
outPD = output->GetPointData();
outPD->InterpolateAllocate((*this->PointList), numPts, numPts);
vtkCellData* tempCellData = vtkCellData::New();
tempCellData->InterpolateAllocate( (*this->CellList), numPts, numPts);
this->CellArrays->clear();
int numCellArrays = tempCellData->GetNumberOfArrays();
for (int cc=0; cc < numCellArrays; cc++)
{
vtkDataArray* inArray = tempCellData->GetArray(cc);
if (inArray && inArray->GetName() && !outPD->GetArray(inArray->GetName()))
{
outPD->AddArray(inArray);
this->CellArrays->push_back(inArray);
}
}
tempCellData->Delete();
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::Probe(vtkDataSet *input, vtkDataSet *source,
vtkDataSet *output)
{
if ((!input) || (!source) || (!output))
{
return 0;
}
this->BuildFieldList(source);
this->InitializeForProbing(input, output);
return this->PerformProbe(input, 0, source, output);
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::PerformProbe(vtkDataSet *input,
int srcIdx, vtkDataSet *source, vtkDataSet *output)
{
vtkDebugMacro(<<"Probing data");
int numPts = input->GetNumberOfPoints();
vtkPointData *inputPD = input->GetPointData();
vtkPointData *sourcePD = source->GetPointData();
vtkCellData *sourceCD = source->GetCellData();
vtkPointData *outputPD = output->GetPointData();
vtkIdTypeArray *cellIdArray = 0;
int cellIdArrayNumberOfTuples = 0;
if (this->CellIdArrayName)
{
vtkDataArray *cellIdDataArray = inputPD->GetArray(this->CellIdArrayName);
if (!cellIdDataArray)
{
vtkErrorMacro(<<"Cell Id array not found or non-numeric.");
return 0;
}
const int cellIdArrayNumberOfComponents =
cellIdDataArray->GetNumberOfComponents();
cellIdArray = vtkIdTypeArray::SafeDownCast(cellIdDataArray);
if ((cellIdArrayNumberOfComponents != 1) || (!cellIdArray))
{
vtkErrorMacro(<<"Cell Id array is not scalar vtkIdType.");
return 0;
}
cellIdArrayNumberOfTuples = cellIdArray->GetNumberOfTuples();
if (cellIdArrayNumberOfTuples < 1)
{
vtkErrorMacro(<<"Cell Id array must have at least 1 value.");
return 0;
}
}
if (!this->ParametricCoordinateArrayName)
{
vtkErrorMacro(<<"Parametric coordinate array not set.");
return 0;
}
vtkDataArray *pcoordArray =
inputPD->GetArray(this->ParametricCoordinateArrayName);
if (!pcoordArray)
{
vtkErrorMacro(<<"Parametric coordinate array not found or non-numeric.");
return 0;
}
const int pcoordArrayNumberOfComponents =
pcoordArray->GetNumberOfComponents();
if (pcoordArrayNumberOfComponents > 3)
{
vtkErrorMacro(<<"Parametric coordinate array has more than 3 components.");
return 0;
}
const int pcoordArrayNumberOfTuples = pcoordArray->GetNumberOfTuples();
if (pcoordArrayNumberOfTuples < numPts)
{
vtkErrorMacro(<<"Parametric coordinate array has fewer tuples than number"
" of points in dataset.");
return 0;
}
std::vector<double> basisWeights(source->GetMaxCellSize());
double *weights = basisWeights.data();
double pcoords[3] = { 0.0, 0.0, 0.0 };
vtkIdType cellId = 0;
vtkCell *cell = 0;
// vtkPointSet-derived outputs have point coordinates probed
vtkPointSet *pointSet = vtkPointSet::SafeDownCast(output);
int subId = 0;
double coords[3];
vtkPoints *points = 0;
if (pointSet)
{
points = pointSet->GetPoints();
}
for (vtkIdType ptId = 0; ptId < numPts; ++ptId)
{
if (ptId < cellIdArrayNumberOfTuples)
{
cellId = cellIdArray->GetValue(ptId);
}
if (cellId >= 0)
{
cell = source->GetCell(cellId);
}
else
{
cell = 0;
}
if (!cell)
{
vtkErrorMacro(<<"No cell found with ID "<<cellId);
return 0;
}
pcoordArray->GetTuple(ptId, pcoords);
if (points)
{
cell->EvaluateLocation(subId, pcoords, coords, weights);
points->SetPoint(ptId, coords);
}
else
{
cell->InterpolateFunctions(pcoords, weights);
}
// Interpolate the point data
outputPD->InterpolatePoint((*this->PointList), sourcePD, srcIdx, ptId,
cell->PointIds, weights);
vtkVectorOfArrays::iterator iter;
for (iter = this->CellArrays->begin(); iter != this->CellArrays->end();
++iter)
{
vtkDataArray* inArray = sourceCD->GetArray((*iter)->GetName());
if (inArray)
{
outputPD->CopyTuple(inArray, *iter, cellId, ptId);
}
}
}
return 1;
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->CopyEntry(sourceInfo,
vtkStreamingDemandDrivenPipeline::TIME_STEPS());
outInfo->CopyEntry(sourceInfo,
vtkStreamingDemandDrivenPipeline::TIME_RANGE());
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()),
6);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
inInfo->Get(
vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES()));
return 1;
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(), 0);
inInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()), 6);
return 1;
}
//----------------------------------------------------------------------------
void msvVTKEmbeddedProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
vtkDataObject *source = 0;
if (this->GetNumberOfInputConnections(1) > 0)
{
source = this->GetExecutive()->GetInputData(1, 0);
}
os << indent << "Source: " << source << "\n";
os << indent << "CellIdArrayName: " << (this->CellIdArrayName ?
this->CellIdArrayName : "<none>") << "\n";
os << indent << "ParametricCoordinateArrayName: " <<
(this->ParametricCoordinateArrayName ?
this->ParametricCoordinateArrayName : "<none>") << "\n";
}
<commit_msg>Remove use of non-standard vector method data(). (Closes #34)<commit_after>/*==============================================================================
Library: MSVTK
Copyright (c) The University of Auckland.
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.
==============================================================================*/
#include "msvVTKEmbeddedProbeFilter.h"
#include "vtkCellData.h"
#include "vtkCell.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include <vector>
vtkStandardNewMacro(msvVTKEmbeddedProbeFilter);
class msvVTKEmbeddedProbeFilter::vtkVectorOfArrays :
public std::vector<vtkDataArray*>
{
};
//----------------------------------------------------------------------------
msvVTKEmbeddedProbeFilter::msvVTKEmbeddedProbeFilter()
{
this->SetNumberOfInputPorts(2);
this->CellIdArrayName = 0;
this->ParametricCoordinateArrayName = 0;
this->CellArrays = new vtkVectorOfArrays();
this->PointList = 0;
this->CellList = 0;
}
//----------------------------------------------------------------------------
msvVTKEmbeddedProbeFilter::~msvVTKEmbeddedProbeFilter()
{
delete this->CellArrays;
delete this->PointList;
delete this->CellList;
}
//----------------------------------------------------------------------------
void msvVTKEmbeddedProbeFilter::SetSourceConnection(
vtkAlgorithmOutput* algOutput)
{
this->SetInputConnection(1, algOutput);
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *source = vtkDataSet::SafeDownCast(
sourceInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
return this->Probe(input, source, output);
}
//----------------------------------------------------------------------------
void msvVTKEmbeddedProbeFilter::BuildFieldList(vtkDataSet* source)
{
delete this->PointList;
delete this->CellList;
this->PointList = new vtkDataSetAttributes::FieldList(1);
this->PointList->InitializeFieldList(source->GetPointData());
this->CellList = new vtkDataSetAttributes::FieldList(1);
this->CellList->InitializeFieldList(source->GetCellData());
}
//----------------------------------------------------------------------------
// * input -- dataset probed with
// * source -- dataset probed into
// * output - output.
void msvVTKEmbeddedProbeFilter::InitializeForProbing(vtkDataSet* input,
vtkDataSet* output)
{
if (!this->PointList || !this->CellList)
{
vtkErrorMacro("BuildFieldList() must be called before calling this method.");
return;
}
vtkIdType numPts = input->GetNumberOfPoints();
// First, copy the input to the output as a starting point
output->CopyStructure(input);
// Pass here so that the attributes/fields can be over-written later
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
output->GetFieldData()->PassData(input->GetFieldData());
// vtkPointSet-derived outputs have points coordinates probed,
// so allocate and replace the referenced ones set by CopyStructure()
vtkPointSet *pointSet = vtkPointSet::SafeDownCast(output);
if (pointSet)
{
vtkPoints *points = vtkPoints::New();
points->DeepCopy(pointSet->GetPoints());
pointSet->SetPoints(points);
points->Delete();
}
vtkPointData* outPD = output->GetPointData();
// Allocate storage for output PointData
// All source PD is sampled to output as PD. Those arrays in source CD that
// are not present in output PD will be passed as output PD.
outPD = output->GetPointData();
outPD->InterpolateAllocate((*this->PointList), numPts, numPts);
vtkCellData* tempCellData = vtkCellData::New();
tempCellData->InterpolateAllocate( (*this->CellList), numPts, numPts);
this->CellArrays->clear();
int numCellArrays = tempCellData->GetNumberOfArrays();
for (int cc=0; cc < numCellArrays; cc++)
{
vtkDataArray* inArray = tempCellData->GetArray(cc);
if (inArray && inArray->GetName() && !outPD->GetArray(inArray->GetName()))
{
outPD->AddArray(inArray);
this->CellArrays->push_back(inArray);
}
}
tempCellData->Delete();
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::Probe(vtkDataSet *input, vtkDataSet *source,
vtkDataSet *output)
{
if ((!input) || (!source) || (!output))
{
return 0;
}
this->BuildFieldList(source);
this->InitializeForProbing(input, output);
return this->PerformProbe(input, 0, source, output);
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::PerformProbe(vtkDataSet *input,
int srcIdx, vtkDataSet *source, vtkDataSet *output)
{
vtkDebugMacro(<<"Probing data");
int numPts = input->GetNumberOfPoints();
vtkPointData *inputPD = input->GetPointData();
vtkPointData *sourcePD = source->GetPointData();
vtkCellData *sourceCD = source->GetCellData();
vtkPointData *outputPD = output->GetPointData();
vtkIdTypeArray *cellIdArray = 0;
int cellIdArrayNumberOfTuples = 0;
if (this->CellIdArrayName)
{
vtkDataArray *cellIdDataArray = inputPD->GetArray(this->CellIdArrayName);
if (!cellIdDataArray)
{
vtkErrorMacro(<<"Cell Id array not found or non-numeric.");
return 0;
}
const int cellIdArrayNumberOfComponents =
cellIdDataArray->GetNumberOfComponents();
cellIdArray = vtkIdTypeArray::SafeDownCast(cellIdDataArray);
if ((cellIdArrayNumberOfComponents != 1) || (!cellIdArray))
{
vtkErrorMacro(<<"Cell Id array is not scalar vtkIdType.");
return 0;
}
cellIdArrayNumberOfTuples = cellIdArray->GetNumberOfTuples();
if (cellIdArrayNumberOfTuples < 1)
{
vtkErrorMacro(<<"Cell Id array must have at least 1 value.");
return 0;
}
}
if (!this->ParametricCoordinateArrayName)
{
vtkErrorMacro(<<"Parametric coordinate array not set.");
return 0;
}
vtkDataArray *pcoordArray =
inputPD->GetArray(this->ParametricCoordinateArrayName);
if (!pcoordArray)
{
vtkErrorMacro(<<"Parametric coordinate array not found or non-numeric.");
return 0;
}
const int pcoordArrayNumberOfComponents =
pcoordArray->GetNumberOfComponents();
if (pcoordArrayNumberOfComponents > 3)
{
vtkErrorMacro(<<"Parametric coordinate array has more than 3 components.");
return 0;
}
const int pcoordArrayNumberOfTuples = pcoordArray->GetNumberOfTuples();
if (pcoordArrayNumberOfTuples < numPts)
{
vtkErrorMacro(<<"Parametric coordinate array has fewer tuples than number"
" of points in dataset.");
return 0;
}
double *weights = new double[source->GetMaxCellSize()];
double pcoords[3] = { 0.0, 0.0, 0.0 };
vtkIdType cellId = 0;
vtkCell *cell = 0;
// vtkPointSet-derived outputs have point coordinates probed
vtkPointSet *pointSet = vtkPointSet::SafeDownCast(output);
int subId = 0;
double coords[3];
vtkPoints *points = 0;
if (pointSet)
{
points = pointSet->GetPoints();
}
int result = 1;
for (vtkIdType ptId = 0; ptId < numPts; ++ptId)
{
if (ptId < cellIdArrayNumberOfTuples)
{
cellId = cellIdArray->GetValue(ptId);
}
if (cellId >= 0)
{
cell = source->GetCell(cellId);
}
else
{
cell = 0;
}
if (!cell)
{
vtkErrorMacro(<<"No cell found with ID "<<cellId);
result = 0;
break;
}
pcoordArray->GetTuple(ptId, pcoords);
if (points)
{
cell->EvaluateLocation(subId, pcoords, coords, weights);
points->SetPoint(ptId, coords);
}
else
{
cell->InterpolateFunctions(pcoords, weights);
}
// Interpolate the point data
outputPD->InterpolatePoint((*this->PointList), sourcePD, srcIdx, ptId,
cell->PointIds, weights);
vtkVectorOfArrays::iterator iter;
for (iter = this->CellArrays->begin(); iter != this->CellArrays->end();
++iter)
{
vtkDataArray* inArray = sourceCD->GetArray((*iter)->GetName());
if (inArray)
{
outputPD->CopyTuple(inArray, *iter, cellId, ptId);
}
}
}
delete[] weights;
return result;
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->CopyEntry(sourceInfo,
vtkStreamingDemandDrivenPipeline::TIME_STEPS());
outInfo->CopyEntry(sourceInfo,
vtkStreamingDemandDrivenPipeline::TIME_RANGE());
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()),
6);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
inInfo->Get(
vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES()));
return 1;
}
//----------------------------------------------------------------------------
int msvVTKEmbeddedProbeFilter::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(), 0);
inInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()), 6);
return 1;
}
//----------------------------------------------------------------------------
void msvVTKEmbeddedProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
vtkDataObject *source = 0;
if (this->GetNumberOfInputConnections(1) > 0)
{
source = this->GetExecutive()->GetInputData(1, 0);
}
os << indent << "Source: " << source << "\n";
os << indent << "CellIdArrayName: " << (this->CellIdArrayName ?
this->CellIdArrayName : "<none>") << "\n";
os << indent << "ParametricCoordinateArrayName: " <<
(this->ParametricCoordinateArrayName ?
this->ParametricCoordinateArrayName : "<none>") << "\n";
}
<|endoftext|> |
<commit_before>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#ifdef N_USE_SDL_IMAGE
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <n/concurrent/Mutex.h>
#include <n/utils.h>
#include <n/defines.h>
#include "ImageLoader.h"
#include <iostream>
namespace n {
namespace graphics {
class SDLImageDecoder : public graphics::ImageLoader::ImageDecoder<SDLImageDecoder, core::String>
{
public:
SDLImageDecoder() : graphics::ImageLoader::ImageDecoder<SDLImageDecoder, core::String>() {
}
graphics::internal::Image *operator()(core::String name) override {
static concurrent::Mutex lock;
lock.lock();
SDL_Surface *surf = IMG_Load(name.toChar());
if(!surf) {
std::cerr<<"Failed to load \""<<name<<"\" : "<<IMG_GetError()<<std::endl;
lock.unlock();
return 0;
}
SDL_LockSurface(surf);
math::Vec2ui size(surf->w, surf->h);
SDL_PixelFormat frm;
frm.format = SDL_PIXELFORMAT_RGBA8888;
frm.BitsPerPixel = 32;
frm.BytesPerPixel = 4;
frm.Rmask = 0x000000FF;
frm.Gmask = 0x0000FF00;
frm.Bmask = 0x00FF0000;
frm.Amask = 0xFF000000;
if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
std::swap(frm.Amask, frm.Rmask);
std::swap(frm.Bmask, frm.Gmask);
}
SDL_Surface* cs = SDL_ConvertSurface(surf, &frm, SDL_SWSURFACE);
SDL_LockSurface(cs);
void *dat = cs->pixels;
cs->pixels = 0;
SDL_LockSurface(surf);
SDL_LockSurface(cs);
lock.unlock();
return new internal::Image(size, ImageFormat::RGBA8, dat);
}
};
}
}
#endif
<commit_msg>Fixed sdl lock problems<commit_after>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#ifdef N_USE_SDL_IMAGE
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <n/concurrent/Mutex.h>
#include <n/utils.h>
#include <n/defines.h>
#include "ImageLoader.h"
#include <iostream>
namespace n {
namespace graphics {
class SDLImageDecoder : public graphics::ImageLoader::ImageDecoder<SDLImageDecoder, core::String>
{
public:
SDLImageDecoder() : graphics::ImageLoader::ImageDecoder<SDLImageDecoder, core::String>() {
}
graphics::internal::Image *operator()(core::String name) override {
static concurrent::Mutex lock;
lock.lock();
SDL_Surface *surf = IMG_Load(name.toChar());
if(!surf) {
std::cerr<<"Failed to load \""<<name<<"\" : "<<IMG_GetError()<<std::endl;
lock.unlock();
return 0;
}
SDL_LockSurface(surf);
math::Vec2ui size(surf->w, surf->h);
SDL_PixelFormat frm;
frm.format = SDL_PIXELFORMAT_RGBA8888;
frm.BitsPerPixel = 32;
frm.BytesPerPixel = 4;
frm.Rmask = 0x000000FF;
frm.Gmask = 0x0000FF00;
frm.Bmask = 0x00FF0000;
frm.Amask = 0xFF000000;
if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
std::swap(frm.Amask, frm.Rmask);
std::swap(frm.Bmask, frm.Gmask);
}
SDL_Surface* cs = SDL_ConvertSurface(surf, &frm, SDL_SWSURFACE);
SDL_LockSurface(cs);
void *dat = cs->pixels;
cs->pixels = 0;
SDL_UnlockSurface(surf);
SDL_UnlockSurface(cs);
lock.unlock();
return new internal::Image(size, ImageFormat::RGBA8, dat);
}
};
}
}
#endif
<|endoftext|> |
<commit_before>/** \brief Tool for generating reasonable input for the FulltextImporter if only a PDF fulltext is available
* \author Johannes Riedl
*
* \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "FileUtil.h"
#include "FullTextImport.h"
#include "PdfUtil.h"
#include "RegexMatcher.h"
#include "Solr.h"
#include "SolrJSON.h"
#include "StringUtil.h"
#include "util.h"
// Try to derive relevant information to guess the PPN
// Strategy 1: Try to find an ISBN string
// Strategy 2: Extract pages at the beginning and try to identify information at
// the bottom of the first page and try to guess author and title
namespace {
const std::string solr_host_and_port("localhost:8080");
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--min-log-level=min_verbosity] pdf_input full_text_output\n"
<< ::progname << " [--min-log-level=min_verbosity] --output_dir output_dir pdf_input1 pdf_input2 ...\n\n";
std::exit(EXIT_FAILURE);
}
std::string GuessISSN(const std::string &first_page_text, std::string * const issn) {
std::string first_page_text_trimmed(first_page_text);
StringUtil::Trim(&first_page_text_trimmed, '\n');
const std::size_t last_paragraph_start(first_page_text_trimmed.rfind("\n\n"));
std::string last_paragraph(last_paragraph_start != std::string::npos ?
first_page_text_trimmed.substr(last_paragraph_start) : "");
StringUtil::Map(&last_paragraph, '\n', ' ');
static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*ISSN\\s*([\\d\\-X]+).*"));
if (matcher->matched(last_paragraph))
*issn = (*matcher)[1];
return last_paragraph;
}
void GuessISBN(const std::string &extracted_text, std::string * const isbn) {
static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*ISBN\\s*([\\d\\-‑X]+).*"));
if (matcher->matched(extracted_text)) {
*isbn = (*matcher)[1];
StringUtil::ReplaceString("‑", "-", isbn); // Normalize strange dash
}
}
void GuessAuthorAndTitle(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) {
std::string pdfinfo_output;
PdfUtil::ExtractPDFInfo(pdf_document, &pdfinfo_output);
static RegexMatcher * const authors_matcher(RegexMatcher::RegexMatcherFactory("Author:\\s*(.*)", nullptr, RegexMatcher::CASE_INSENSITIVE));
if (authors_matcher->matched(pdfinfo_output))
StringUtil::Split((*authors_matcher)[1], std::set<char>({ ';', '|' }), &(fulltext_data->authors_));
static RegexMatcher * const title_matcher(RegexMatcher::RegexMatcherFactory("^Title:?\\s*(.*)", nullptr, RegexMatcher::CASE_INSENSITIVE));
if (title_matcher->matched(pdfinfo_output))
fulltext_data->title_ = (*title_matcher)[1];
}
void GetFulltextMetadataFromSolr(const std::string control_number, FullTextImport::FullTextData * const fulltext_data) {
std::string json_result;
std::string err_msg;
const std::string query(std::string("id:") + control_number);
if (unlikely(not Solr::Query(query, "id,title,author,author2,publishDate", &json_result, &err_msg,
solr_host_and_port,/* timeout */ 5, Solr::JSON)))
LOG_ERROR("Solr query failed or timed-out: \"" + query + "\". (" + err_msg + ")");
const std::shared_ptr<const JSON::ArrayNode> docs(SolrJSON::ParseTreeAndGetDocs(json_result));
if (docs->size() != 1)
LOG_ERROR("Invalid size " + std::to_string(docs->size()) + " for SOLR results (Expected only one)");
const std::shared_ptr<const JSON::ObjectNode> doc_obj(JSON::JSONNode::CastToObjectNodeOrDie("document object", *(docs->begin())));
fulltext_data->title_ = SolrJSON::GetTitle(doc_obj);
const auto authors(SolrJSON::GetAuthors(doc_obj));
fulltext_data->authors_.insert(std::begin(authors), std::end(authors));
fulltext_data->year_ = SolrJSON::GetFirstPublishDate(doc_obj);
}
bool GuessPDFMetadata(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) {
ControlNumberGuesser control_number_guesser;
std::set<std::string> control_numbers;
// Try to find an ISBN in the first pages
std::string first_pages_text;
PdfUtil::ExtractText(pdf_document, &first_pages_text, "1", "10" );
std::string isbn;
GuessISBN(first_pages_text, &isbn);
if (not isbn.empty()) {
LOG_INFO("Extracted ISBN: " + isbn);
control_number_guesser.lookupISBN(isbn, &control_numbers);
if (control_numbers.size() != 1) {
LOG_WARNING("We got more than one control number for ISBN \"" + isbn + "\" - falling back to title and author");
GuessAuthorAndTitle(pdf_document, fulltext_data);
fulltext_data->isbn_ = isbn;
if (unlikely(not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_numbers)))
return false;
if (control_numbers.size() != 1)
LOG_ERROR("Unable to determine unique control number fo ISBN \"" + isbn + "\"");
}
const std::string control_number(*(control_numbers.begin()));
LOG_INFO("Determined control number \"" + control_number + "\" for ISBN \"" + isbn + "\"\n");
GetFulltextMetadataFromSolr(control_number, fulltext_data);
return true;
}
// Guess control number by author, title and and possibly issn
std::string first_page_text;
PdfUtil::ExtractText(pdf_document, &first_page_text, "1", "1" ); // Get only first page
std::string issn;
const std::string last_paragraph(GuessISSN(first_page_text, &issn));
fulltext_data->issn_ = issn;
GuessAuthorAndTitle(pdf_document, fulltext_data);
std::string control_number;
if (unlikely(not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number)))
return false;
return true;
}
bool ExtractFulltext(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) {
return PdfUtil::ExtractText(pdf_document, &(fulltext_data->full_text_));
}
void CreateFulltextImportFile(const std::string &fulltext_pdf, const std::string &fulltext_txt) {
std::cout << "Processing \"" << fulltext_pdf << "\"\n";
FullTextImport::FullTextData fulltext_data;
std::string pdf_document;
if (not FileUtil::ReadString(fulltext_pdf, &pdf_document))
LOG_ERROR("Could not read \"" + fulltext_pdf + "\"");
if (PdfUtil::PdfDocContainsNoText(pdf_document))
LOG_ERROR("Apparently no text in \"" + fulltext_pdf + "\"");
if (unlikely(not GuessPDFMetadata(pdf_document, &fulltext_data)))
LOG_ERROR("Unable to determine metadata for \"" + fulltext_pdf + "\"");
if (unlikely(not ExtractFulltext(pdf_document, &fulltext_data)))
LOG_ERROR("Unable to extract fulltext from \"" + fulltext_pdf + "\"");
auto plain_text_output(FileUtil::OpenOutputFileOrDie(fulltext_txt));
FullTextImport::WriteExtractedTextToDisk(fulltext_data.full_text_, fulltext_data.title_, fulltext_data.authors_, fulltext_data.doi_,
fulltext_data.year_, fulltext_data.issn_, fulltext_data.isbn_, plain_text_output.get());
}
std::string DeriveOutputFilename(const std::string &pdf_filename) {
return (std::strcmp(StringUtil::ASCIIToLower(FileUtil::GetExtension(pdf_filename)).c_str(), "pdf") == 0) ?
FileUtil::GetFilenameWithoutExtensionOrDie(pdf_filename) + ".txt" : pdf_filename + ".txt";
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 3)
Usage();
bool use_output_dir(false);
std::string output_dir(".");
if (argc > 2 and StringUtil::StartsWith(argv[1], "--output-dir=")) {
use_output_dir = true;
output_dir = argv[1] + __builtin_strlen("--output-dir=");
--argc;
++argv;
}
if (argc < 2)
Usage();
if (not use_output_dir and argc < 3)
Usage();
if (not use_output_dir) {
const std::string fulltext_pdf(argv[1]);
CreateFulltextImportFile(fulltext_pdf, argv[2]);
return EXIT_SUCCESS;
}
for (int arg_no(1); arg_no < argc; ++arg_no)
CreateFulltextImportFile(argv[arg_no], output_dir + '/' + DeriveOutputFilename(argv[arg_no]));
return EXIT_SUCCESS;
}
<commit_msg>Use default constant<commit_after>/** \brief Tool for generating reasonable input for the FulltextImporter if only a PDF fulltext is available
* \author Johannes Riedl
*
* \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "FileUtil.h"
#include "FullTextImport.h"
#include "PdfUtil.h"
#include "RegexMatcher.h"
#include "Solr.h"
#include "SolrJSON.h"
#include "StringUtil.h"
#include "util.h"
// Try to derive relevant information to guess the PPN
// Strategy 1: Try to find an ISBN string
// Strategy 2: Extract pages at the beginning and try to identify information at
// the bottom of the first page and try to guess author and title
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--min-log-level=min_verbosity] pdf_input full_text_output\n"
<< ::progname << " [--min-log-level=min_verbosity] --output_dir output_dir pdf_input1 pdf_input2 ...\n\n";
std::exit(EXIT_FAILURE);
}
std::string GuessISSN(const std::string &first_page_text, std::string * const issn) {
std::string first_page_text_trimmed(first_page_text);
StringUtil::Trim(&first_page_text_trimmed, '\n');
const std::size_t last_paragraph_start(first_page_text_trimmed.rfind("\n\n"));
std::string last_paragraph(last_paragraph_start != std::string::npos ?
first_page_text_trimmed.substr(last_paragraph_start) : "");
StringUtil::Map(&last_paragraph, '\n', ' ');
static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*ISSN\\s*([\\d\\-X]+).*"));
if (matcher->matched(last_paragraph))
*issn = (*matcher)[1];
return last_paragraph;
}
void GuessISBN(const std::string &extracted_text, std::string * const isbn) {
static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*ISBN\\s*([\\d\\-‑X]+).*"));
if (matcher->matched(extracted_text)) {
*isbn = (*matcher)[1];
StringUtil::ReplaceString("‑", "-", isbn); // Normalize strange dash
}
}
void GuessAuthorAndTitle(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) {
std::string pdfinfo_output;
PdfUtil::ExtractPDFInfo(pdf_document, &pdfinfo_output);
static RegexMatcher * const authors_matcher(RegexMatcher::RegexMatcherFactory("Author:\\s*(.*)", nullptr, RegexMatcher::CASE_INSENSITIVE));
if (authors_matcher->matched(pdfinfo_output))
StringUtil::Split((*authors_matcher)[1], std::set<char>({ ';', '|' }), &(fulltext_data->authors_));
static RegexMatcher * const title_matcher(RegexMatcher::RegexMatcherFactory("^Title:?\\s*(.*)", nullptr, RegexMatcher::CASE_INSENSITIVE));
if (title_matcher->matched(pdfinfo_output))
fulltext_data->title_ = (*title_matcher)[1];
}
void GetFulltextMetadataFromSolr(const std::string control_number, FullTextImport::FullTextData * const fulltext_data) {
std::string json_result;
std::string err_msg;
const std::string query(std::string("id:") + control_number);
if (unlikely(not Solr::Query(query, "id,title,author,author2,publishDate", &json_result, &err_msg,
Solr::DEFAULT_HOST_AND_PORT,/* timeout */ 5, Solr::JSON)))
LOG_ERROR("Solr query failed or timed-out: \"" + query + "\". (" + err_msg + ")");
const std::shared_ptr<const JSON::ArrayNode> docs(SolrJSON::ParseTreeAndGetDocs(json_result));
if (docs->size() != 1)
LOG_ERROR("Invalid size " + std::to_string(docs->size()) + " for SOLR results (Expected only one)");
const std::shared_ptr<const JSON::ObjectNode> doc_obj(JSON::JSONNode::CastToObjectNodeOrDie("document object", *(docs->begin())));
fulltext_data->title_ = SolrJSON::GetTitle(doc_obj);
const auto authors(SolrJSON::GetAuthors(doc_obj));
fulltext_data->authors_.insert(std::begin(authors), std::end(authors));
fulltext_data->year_ = SolrJSON::GetFirstPublishDate(doc_obj);
}
bool GuessPDFMetadata(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) {
ControlNumberGuesser control_number_guesser;
std::set<std::string> control_numbers;
// Try to find an ISBN in the first pages
std::string first_pages_text;
PdfUtil::ExtractText(pdf_document, &first_pages_text, "1", "10" );
std::string isbn;
GuessISBN(first_pages_text, &isbn);
if (not isbn.empty()) {
LOG_INFO("Extracted ISBN: " + isbn);
control_number_guesser.lookupISBN(isbn, &control_numbers);
if (control_numbers.size() != 1) {
LOG_WARNING("We got more than one control number for ISBN \"" + isbn + "\" - falling back to title and author");
GuessAuthorAndTitle(pdf_document, fulltext_data);
fulltext_data->isbn_ = isbn;
if (unlikely(not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_numbers)))
return false;
if (control_numbers.size() != 1)
LOG_ERROR("Unable to determine unique control number fo ISBN \"" + isbn + "\"");
}
const std::string control_number(*(control_numbers.begin()));
LOG_INFO("Determined control number \"" + control_number + "\" for ISBN \"" + isbn + "\"\n");
GetFulltextMetadataFromSolr(control_number, fulltext_data);
return true;
}
// Guess control number by author, title and and possibly issn
std::string first_page_text;
PdfUtil::ExtractText(pdf_document, &first_page_text, "1", "1" ); // Get only first page
std::string issn;
const std::string last_paragraph(GuessISSN(first_page_text, &issn));
fulltext_data->issn_ = issn;
GuessAuthorAndTitle(pdf_document, fulltext_data);
std::string control_number;
if (unlikely(not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number)))
return false;
return true;
}
bool ExtractFulltext(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) {
return PdfUtil::ExtractText(pdf_document, &(fulltext_data->full_text_));
}
void CreateFulltextImportFile(const std::string &fulltext_pdf, const std::string &fulltext_txt) {
std::cout << "Processing \"" << fulltext_pdf << "\"\n";
FullTextImport::FullTextData fulltext_data;
std::string pdf_document;
if (not FileUtil::ReadString(fulltext_pdf, &pdf_document))
LOG_ERROR("Could not read \"" + fulltext_pdf + "\"");
if (PdfUtil::PdfDocContainsNoText(pdf_document))
LOG_ERROR("Apparently no text in \"" + fulltext_pdf + "\"");
if (unlikely(not GuessPDFMetadata(pdf_document, &fulltext_data)))
LOG_ERROR("Unable to determine metadata for \"" + fulltext_pdf + "\"");
if (unlikely(not ExtractFulltext(pdf_document, &fulltext_data)))
LOG_ERROR("Unable to extract fulltext from \"" + fulltext_pdf + "\"");
auto plain_text_output(FileUtil::OpenOutputFileOrDie(fulltext_txt));
FullTextImport::WriteExtractedTextToDisk(fulltext_data.full_text_, fulltext_data.title_, fulltext_data.authors_, fulltext_data.doi_,
fulltext_data.year_, fulltext_data.issn_, fulltext_data.isbn_, plain_text_output.get());
}
std::string DeriveOutputFilename(const std::string &pdf_filename) {
return (std::strcmp(StringUtil::ASCIIToLower(FileUtil::GetExtension(pdf_filename)).c_str(), "pdf") == 0) ?
FileUtil::GetFilenameWithoutExtensionOrDie(pdf_filename) + ".txt" : pdf_filename + ".txt";
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 3)
Usage();
bool use_output_dir(false);
std::string output_dir(".");
if (argc > 2 and StringUtil::StartsWith(argv[1], "--output-dir=")) {
use_output_dir = true;
output_dir = argv[1] + __builtin_strlen("--output-dir=");
--argc;
++argv;
}
if (argc < 2)
Usage();
if (not use_output_dir and argc < 3)
Usage();
if (not use_output_dir) {
const std::string fulltext_pdf(argv[1]);
CreateFulltextImportFile(fulltext_pdf, argv[2]);
return EXIT_SUCCESS;
}
for (int arg_no(1); arg_no < argc; ++arg_no)
CreateFulltextImportFile(argv[arg_no], output_dir + '/' + DeriveOutputFilename(argv[arg_no]));
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/** \brief Updates Zeder (via Ingo's SQL database) w/ the last N issues of harvested articles for each journal.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DnsUtil.h"
#include "IniFile.h"
#include "MARC.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"
namespace {
// Please note that Zeder PPN entries are separated by spaces and, unlike what the column names "print_ppn" and
// "online_ppn" imply may in rare cases contain space-separated lists of PPN's.
inline auto SplitZederPPNs(const std::string &ppns) {
std::vector<std::string> individual_ppns;
StringUtil::Split(ppns, ' ', &individual_ppns);
return individual_ppns;
}
struct ZederIdAndType {
unsigned zeder_id_;
char type_; // 'p' or 'e' for "print" or "electronic"
public:
ZederIdAndType(const unsigned zeder_id, const char type)
: zeder_id_(zeder_id), type_(type) { }
};
std::unordered_map<std::string, ZederIdAndType> GetPPNsToZederIdsAndTypesMap(const std::string &system_type) {
const Zeder::SimpleZeder zeder(system_type == "ixtheo" ? Zeder::IXTHEO : Zeder::KRIMDOK, { "eppn", "pppn" });
if (unlikely(zeder.empty()))
LOG_ERROR("found no Zeder entries matching any of our requested columns!"
" (This *should* not happen as we included the column ID!)");
std::unordered_map<std::string, ZederIdAndType> ppns_to_zeder_ids_and_types_map;
unsigned included_journal_count(0);
std::set<std::string> bundle_ppns; // We use a std::set because it is automatically being sorted for us.
for (const auto &journal : zeder) {
if (journal.empty())
continue;
++included_journal_count;
const auto print_ppns(SplitZederPPNs(journal.lookup("pppn")));
const auto online_ppns(SplitZederPPNs(journal.lookup("eppn")));
if (print_ppns.empty() and online_ppns.empty()) {
--included_journal_count;
LOG_WARNING("Zeder entry #" + std::to_string(journal.getId()) + " is missing print and online PPN's!");
continue;
}
for (const auto &print_ppn : print_ppns)
ppns_to_zeder_ids_and_types_map.emplace(print_ppn, ZederIdAndType(journal.getId(), 'p'));
for (const auto &online_ppn : online_ppns)
ppns_to_zeder_ids_and_types_map.emplace(online_ppn, ZederIdAndType(journal.getId(), 'e'));
}
LOG_INFO("downloaded information for " + std::to_string(included_journal_count) + " journal(s) from Zeder.");
return ppns_to_zeder_ids_and_types_map;
}
bool SplitPageNumbers(const std::string &possibly_combined_pages, unsigned * const start_page, unsigned * const end_page) {
if (StringUtil::ToUnsigned(possibly_combined_pages, start_page)) {
*end_page = *start_page;
return true;
} else if (possibly_combined_pages.length() >= 2
and possibly_combined_pages[possibly_combined_pages.length() - 1] == 'f')
{
if (not StringUtil::ToUnsigned(possibly_combined_pages.substr(0, possibly_combined_pages.length() - 1), start_page))
return false;
*end_page = *start_page + 1;
return true;
}
// Common case, page range with a hypen.
const auto first_hyphen_pos(possibly_combined_pages.find('-'));
if (first_hyphen_pos == std::string::npos)
return false;
return StringUtil::ToUnsigned(possibly_combined_pages.substr(0, first_hyphen_pos), start_page)
and StringUtil::ToUnsigned(possibly_combined_pages.substr(first_hyphen_pos + 1), end_page);
}
// \return the year as a small integer or 0 if we could not parse it.
unsigned short YearStringToShort(const std::string &year_as_string) {
unsigned short year_as_unsigned_short;
if (not StringUtil::ToUnsignedShort(year_as_string, &year_as_unsigned_short))
return 0;
return year_as_unsigned_short;
}
struct DbEntry {
std::string jahr_;
std::string band_;
std::string heft_;
std::string seitenbereich_;
public:
DbEntry(const std::string &jahr, const std::string &band, const std::string &heft, const std::string &seitenbereich)
: jahr_(jahr), band_(band), heft_(heft), seitenbereich_(seitenbereich) { }
DbEntry() = default;
DbEntry(const DbEntry &other) = default;
bool operator==(const DbEntry &rhs) const;
};
bool DbEntry::operator==(const DbEntry &rhs) const {
return jahr_ == rhs.jahr_ and band_ == rhs.band_ and heft_ == rhs.heft_ and seitenbereich_ == rhs.seitenbereich_;
}
size_t GetExistingDbEntries(const IniFile &ini_file, const std::string &hostname, const std::string &system_type,
std::unordered_map<std::string, DbEntry> * const existing_entries)
{
DbConnection db_connection(ini_file, "DatabaseSelect");
db_connection.queryOrDie("SELECT MAX(timestamp),Zeder_ID,PPN,Jahr,Band,Heft,Seitenbereich"
" FROM zeder.erschliessung WHERE Quellrechner='" + hostname + "' AND Systemtyp='"
+ system_type + "' GROUP BY Zeder_ID,PPN");
auto result_set(db_connection.getLastResultSet());
while (const auto row = result_set.getNextRow())
(*existing_entries)[row["Zeder_ID"] + "+" + row["PPN"]] =
DbEntry(row["Jahr"], row["Band"], row["Heft"], row["Seitenbereich"]);
return existing_entries->size();
}
bool AlreadyPresentInDB(const std::unordered_map<std::string, DbEntry> &existing_entries,
const std::string &zeder_id, const std::string &ppn, const DbEntry &test_entry)
{
const auto key_and_entry(existing_entries.find(zeder_id + "+" + ppn));
if (key_and_entry == existing_entries.cend())
return false;
return key_and_entry->second == test_entry;
}
void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::string &system_type,
const std::unordered_map<std::string, ZederIdAndType> &ppns_to_zeder_ids_and_types_map,
const IniFile &ini_file, DbConnection * const db_connection)
{
const auto zeder_flavour(system_type == "krimdok" ? Zeder::KRIMDOK : Zeder::IXTHEO);
const auto JOB_START_TIME(std::to_string(std::time(nullptr)));
const auto HOSTNAME(DnsUtil::GetHostname());
const std::string ZEDER_URL_PREFIX(Zeder::GetFullDumpEndpointPath(zeder_flavour) + "#suche=Z%3D");
std::unordered_map<std::string, DbEntry> existing_entries;
LOG_INFO("Found " + std::to_string(GetExistingDbEntries(ini_file, HOSTNAME, system_type, &existing_entries))
+ " existing database entries.");
const std::vector<std::string> COLUMN_NAMES{ "timestamp", "Quellrechner", "Systemtyp", "Zeder_ID", "Zeder_URL", "PPN_Typ",
"PPN", "Jahr", "Band", "Heft", "Seitenbereich", "Startseite", "Endseite" };
std::vector<std::vector<std::optional<std::string>>> column_values;
const unsigned SQL_INSERT_BATCH_SIZE(20);
unsigned total_count(0), inserted_count(0);
while (const auto record = reader->read()) {
++total_count;
writer->write(record); // For the next pipeline phase.
const std::string superior_control_number(record.getSuperiorControlNumber());
if (superior_control_number.empty())
continue;
const auto ppn_and_zeder_id_and_ppn_type(ppns_to_zeder_ids_and_types_map.find(superior_control_number));
if (ppn_and_zeder_id_and_ppn_type == ppns_to_zeder_ids_and_types_map.cend())
continue;
const auto _936_field(record.findTag("936"));
if (_936_field == record.end())
continue;
const std::string pages(_936_field->getFirstSubfieldWithCode('h'));
std::string volume;
std::string issue(_936_field->getFirstSubfieldWithCode('e'));
if (issue.empty())
issue = _936_field->getFirstSubfieldWithCode('d');
else
volume = _936_field->getFirstSubfieldWithCode('d');
const std::string year(_936_field->getFirstSubfieldWithCode('j'));
const std::string zeder_id(std::to_string(ppn_and_zeder_id_and_ppn_type->second.zeder_id_));
const std::string ppn_type(1, ppn_and_zeder_id_and_ppn_type->second.type_);
const std::string year_as_string(std::to_string(YearStringToShort(year)));
if (AlreadyPresentInDB(existing_entries, zeder_id, superior_control_number,
DbEntry(year_as_string, volume, issue, pages)))
continue;
std::vector<std::optional<std::string>> new_column_values{
{ /* timestamp */ JOB_START_TIME },
{ /* Quellrechner */ HOSTNAME },
{ /* Systemtyp */ system_type, },
{ /* Zeder_ID */ zeder_id },
{ /* Zeder_URL */ ZEDER_URL_PREFIX + std::to_string(ppn_and_zeder_id_and_ppn_type->second.zeder_id_) },
{ /* PPN_Typ */ ppn_type },
{ /* PPN */ superior_control_number },
{ /* Jahr */ year_as_string },
{ /* Band */ volume },
{ /* Heft */ issue },
{ /* Seitenbereich */ pages },
};
unsigned start_page, end_page;
if (SplitPageNumbers(pages, &start_page, &end_page)) {
new_column_values.emplace_back(StringUtil::ToString(start_page));
new_column_values.emplace_back(StringUtil::ToString(end_page));
} else {
new_column_values.emplace_back(std::optional<std::string>());
new_column_values.emplace_back(std::optional<std::string>());
}
column_values.emplace_back(new_column_values);
if (column_values.size() == SQL_INSERT_BATCH_SIZE) {
db_connection->insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
column_values.clear();
}
++inserted_count;
}
if (not column_values.empty())
db_connection->insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
LOG_INFO("Processed " + std::to_string(total_count) + " records and inserted " + std::to_string(inserted_count)
+ " into Ingo's database.");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
::Usage("[--min-log-level=log_level] system_type marc_input marc_output\n"
"\twhere \"system_type\" must be one of ixtheo|krimdok");
std::string system_type;
if (__builtin_strcmp("ixtheo", argv[1]) == 0)
system_type = "ixtheo";
else if (__builtin_strcmp("krimdok", argv[1]) == 0)
system_type = "krimdok";
else
LOG_ERROR("system_type must be one of ixtheo|krimdok!");
const auto ppns_to_zeder_ids_and_types_map(GetPPNsToZederIdsAndTypesMap(system_type));
IniFile ini_file;
DbConnection db_connection(ini_file, "DatabaseInsert");
const auto marc_reader(MARC::Reader::Factory(argv[2]));
const auto marc_writer(MARC::Writer::Factory(argv[3]));
ProcessRecords(marc_reader.get(), marc_writer.get(), system_type, ppns_to_zeder_ids_and_types_map,
ini_file, &db_connection);
return EXIT_SUCCESS;
}
<commit_msg>Removed three columns as they appear to have disappeared from the database.<commit_after>/** \brief Updates Zeder (via Ingo's SQL database) w/ the last N issues of harvested articles for each journal.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DnsUtil.h"
#include "IniFile.h"
#include "MARC.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"
namespace {
// Please note that Zeder PPN entries are separated by spaces and, unlike what the column names "print_ppn" and
// "online_ppn" imply may in rare cases contain space-separated lists of PPN's.
inline auto SplitZederPPNs(const std::string &ppns) {
std::vector<std::string> individual_ppns;
StringUtil::Split(ppns, ' ', &individual_ppns);
return individual_ppns;
}
struct ZederIdAndType {
unsigned zeder_id_;
char type_; // 'p' or 'e' for "print" or "electronic"
public:
ZederIdAndType(const unsigned zeder_id, const char type)
: zeder_id_(zeder_id), type_(type) { }
};
std::unordered_map<std::string, ZederIdAndType> GetPPNsToZederIdsAndTypesMap(const std::string &system_type) {
const Zeder::SimpleZeder zeder(system_type == "ixtheo" ? Zeder::IXTHEO : Zeder::KRIMDOK, { "eppn", "pppn" });
if (unlikely(zeder.empty()))
LOG_ERROR("found no Zeder entries matching any of our requested columns!"
" (This *should* not happen as we included the column ID!)");
std::unordered_map<std::string, ZederIdAndType> ppns_to_zeder_ids_and_types_map;
unsigned included_journal_count(0);
std::set<std::string> bundle_ppns; // We use a std::set because it is automatically being sorted for us.
for (const auto &journal : zeder) {
if (journal.empty())
continue;
++included_journal_count;
const auto print_ppns(SplitZederPPNs(journal.lookup("pppn")));
const auto online_ppns(SplitZederPPNs(journal.lookup("eppn")));
if (print_ppns.empty() and online_ppns.empty()) {
--included_journal_count;
LOG_WARNING("Zeder entry #" + std::to_string(journal.getId()) + " is missing print and online PPN's!");
continue;
}
for (const auto &print_ppn : print_ppns)
ppns_to_zeder_ids_and_types_map.emplace(print_ppn, ZederIdAndType(journal.getId(), 'p'));
for (const auto &online_ppn : online_ppns)
ppns_to_zeder_ids_and_types_map.emplace(online_ppn, ZederIdAndType(journal.getId(), 'e'));
}
LOG_INFO("downloaded information for " + std::to_string(included_journal_count) + " journal(s) from Zeder.");
return ppns_to_zeder_ids_and_types_map;
}
// \return the year as a small integer or 0 if we could not parse it.
unsigned short YearStringToShort(const std::string &year_as_string) {
unsigned short year_as_unsigned_short;
if (not StringUtil::ToUnsignedShort(year_as_string, &year_as_unsigned_short))
return 0;
return year_as_unsigned_short;
}
struct DbEntry {
std::string jahr_;
std::string band_;
std::string heft_;
std::string seitenbereich_;
public:
DbEntry(const std::string &jahr, const std::string &band, const std::string &heft, const std::string &seitenbereich)
: jahr_(jahr), band_(band), heft_(heft), seitenbereich_(seitenbereich) { }
DbEntry() = default;
DbEntry(const DbEntry &other) = default;
bool operator==(const DbEntry &rhs) const;
};
bool DbEntry::operator==(const DbEntry &rhs) const {
return jahr_ == rhs.jahr_ and band_ == rhs.band_ and heft_ == rhs.heft_ and seitenbereich_ == rhs.seitenbereich_;
}
size_t GetExistingDbEntries(const IniFile &ini_file, const std::string &hostname, const std::string &system_type,
std::unordered_map<std::string, DbEntry> * const existing_entries)
{
DbConnection db_connection(ini_file, "DatabaseSelect");
db_connection.queryOrDie("SELECT MAX(timestamp),Zeder_ID,PPN,Jahr,Band,Heft,Seitenbereich"
" FROM zeder.erschliessung WHERE Quellrechner='" + hostname + "' AND Systemtyp='"
+ system_type + "' GROUP BY Zeder_ID,PPN");
auto result_set(db_connection.getLastResultSet());
while (const auto row = result_set.getNextRow())
(*existing_entries)[row["Zeder_ID"] + "+" + row["PPN"]] =
DbEntry(row["Jahr"], row["Band"], row["Heft"], row["Seitenbereich"]);
return existing_entries->size();
}
bool AlreadyPresentInDB(const std::unordered_map<std::string, DbEntry> &existing_entries,
const std::string &zeder_id, const std::string &ppn, const DbEntry &test_entry)
{
const auto key_and_entry(existing_entries.find(zeder_id + "+" + ppn));
if (key_and_entry == existing_entries.cend())
return false;
return key_and_entry->second == test_entry;
}
void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::string &system_type,
const std::unordered_map<std::string, ZederIdAndType> &ppns_to_zeder_ids_and_types_map,
const IniFile &ini_file, DbConnection * const db_connection)
{
const auto JOB_START_TIME(std::to_string(std::time(nullptr)));
const auto HOSTNAME(DnsUtil::GetHostname());
std::unordered_map<std::string, DbEntry> existing_entries;
LOG_INFO("Found " + std::to_string(GetExistingDbEntries(ini_file, HOSTNAME, system_type, &existing_entries))
+ " existing database entries.");
const std::vector<std::string> COLUMN_NAMES{ "timestamp", "Quellrechner", "Systemtyp", "Zeder_ID", "PPN_Typ",
"PPN", "Jahr", "Band", "Heft", "Seitenbereich" };
std::vector<std::vector<std::optional<std::string>>> column_values;
const unsigned SQL_INSERT_BATCH_SIZE(20);
unsigned total_count(0), inserted_count(0);
while (const auto record = reader->read()) {
++total_count;
writer->write(record); // For the next pipeline phase.
const std::string superior_control_number(record.getSuperiorControlNumber());
if (superior_control_number.empty())
continue;
const auto ppn_and_zeder_id_and_ppn_type(ppns_to_zeder_ids_and_types_map.find(superior_control_number));
if (ppn_and_zeder_id_and_ppn_type == ppns_to_zeder_ids_and_types_map.cend())
continue;
const auto _936_field(record.findTag("936"));
if (_936_field == record.end())
continue;
const std::string pages(_936_field->getFirstSubfieldWithCode('h'));
std::string volume;
std::string issue(_936_field->getFirstSubfieldWithCode('e'));
if (issue.empty())
issue = _936_field->getFirstSubfieldWithCode('d');
else
volume = _936_field->getFirstSubfieldWithCode('d');
const std::string year(_936_field->getFirstSubfieldWithCode('j'));
const std::string zeder_id(std::to_string(ppn_and_zeder_id_and_ppn_type->second.zeder_id_));
const std::string ppn_type(1, ppn_and_zeder_id_and_ppn_type->second.type_);
const std::string year_as_string(std::to_string(YearStringToShort(year)));
if (AlreadyPresentInDB(existing_entries, zeder_id, superior_control_number,
DbEntry(year_as_string, volume, issue, pages)))
continue;
const std::vector<std::optional<std::string>> new_column_values{
{ /* timestamp */ JOB_START_TIME },
{ /* Quellrechner */ HOSTNAME },
{ /* Systemtyp */ system_type, },
{ /* Zeder_ID */ zeder_id },
{ /* PPN_Typ */ ppn_type },
{ /* PPN */ superior_control_number },
{ /* Jahr */ year_as_string },
{ /* Band */ volume },
{ /* Heft */ issue },
{ /* Seitenbereich */ pages },
};
column_values.emplace_back(new_column_values);
if (column_values.size() == SQL_INSERT_BATCH_SIZE) {
db_connection->insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
column_values.clear();
}
++inserted_count;
}
if (not column_values.empty())
db_connection->insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
LOG_INFO("Processed " + std::to_string(total_count) + " records and inserted " + std::to_string(inserted_count)
+ " into Ingo's database.");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
::Usage("[--min-log-level=log_level] system_type marc_input marc_output\n"
"\twhere \"system_type\" must be one of ixtheo|krimdok");
std::string system_type;
if (__builtin_strcmp("ixtheo", argv[1]) == 0)
system_type = "ixtheo";
else if (__builtin_strcmp("krimdok", argv[1]) == 0)
system_type = "krimdok";
else
LOG_ERROR("system_type must be one of ixtheo|krimdok!");
const auto ppns_to_zeder_ids_and_types_map(GetPPNsToZederIdsAndTypesMap(system_type));
IniFile ini_file;
DbConnection db_connection(ini_file, "DatabaseInsert");
const auto marc_reader(MARC::Reader::Factory(argv[2]));
const auto marc_writer(MARC::Writer::Factory(argv[3]));
ProcessRecords(marc_reader.get(), marc_writer.get(), system_type, ppns_to_zeder_ids_and_types_map,
ini_file, &db_connection);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "httpserver.h"
#include "../logger.h"
#include "../config.h"
#include <microhttpd.h>
namespace shanghai {
namespace system {
namespace {
using mtx_guard = std::lock_guard<std::mutex>;
// libmicrohttpd の内部アサートっぽいので諦めて死ぬ
void AtPanic(void *cls, const char *file, unsigned int line, const char *reason)
{
logger.Log(LogLevel::Fatal, "libmicrohttpd panic");
logger.Log(LogLevel::Fatal, "%s:%u %s", file, line, reason);
std::terminate();
}
// イテレートコールバックを map<string, string> に変換する
int IterateToMap(void *cls, enum MHD_ValueKind kind,
const char *key, const char *value) noexcept
{
auto &map = *static_cast<KeyValueSet *>(cls);
value = (value == nullptr) ? "" : value;
map.emplace(key, value);
return MHD_YES;
}
} // namespace
HttpServer::HttpServer() : m_daemon(nullptr)
{
logger.Log(LogLevel::Info, "Initialize HttpServer...");
// 設定の読み出し
int port = config.GetInt({"HttpServer", "Port"});
if (port < 0 || port > 0xffff) {
throw ConfigError("Invalid HttpServer port");
}
// サーバスタート (失敗時はコンストラクト失敗、デストラクトなし)
::MHD_set_panic_func(AtPanic, nullptr);
m_daemon = ::MHD_start_daemon(
MHD_USE_SELECT_INTERNALLY, port, nullptr, nullptr,
OnRequest, this,
MHD_OPTION_CONNECTION_MEMORY_LIMIT, MemoryLimit,
MHD_OPTION_CONNECTION_LIMIT, MaxConn,
MHD_OPTION_CONNECTION_TIMEOUT, TimeoutSec,
MHD_OPTION_PER_IP_CONNECTION_LIMIT, IpConnLimit,
MHD_OPTION_THREAD_POOL_SIZE, ThreadPoolSize,
MHD_OPTION_LISTENING_ADDRESS_REUSE,
MHD_OPTION_END);
if (m_daemon == nullptr) {
throw std::runtime_error("Starting HTTP server failed");
}
logger.Log(LogLevel::Info, "Initialize HttpServer OK (port=%d)", port);
}
HttpServer::~HttpServer()
{
// デストラクタでサーバ停止
::MHD_stop_daemon(m_daemon);
m_daemon = nullptr;
}
void HttpServer::AddPage(const std::regex &method, const std::regex &url,
std::shared_ptr<WebPage> page)
{
mtx_guard lock(m_mtx);
m_routes.emplace_back(method, url, page);
// unlock
}
HttpResponse HttpServer::ProcessRequest(struct MHD_Connection *connection,
const std::string &url, const std::string &method,
const std::string &version, const char *upload_data,
size_t *upload_data_size, void **con_cls) noexcept
{
logger.Log(LogLevel::Info, "[HTTP] %s %s %s",
version.c_str(), method.c_str(), url.c_str());
// version: HTTP/1.1 以外は "505 HTTP Version Not Supported"
if (version != "HTTP/1.1") {
return HttpResponse(505);
}
// HEAD は libmicrohttpd が自動で Response body をカットしてくれるので
// GET と同じ処理をしてあとは任せる
const std::string &vmethod = (method == "HEAD") ? "GET"s : method;
// HTTP request header と query を map に変換する
KeyValueSet request_header;
KeyValueSet get_args;
::MHD_get_connection_values(connection, MHD_HEADER_KIND,
IterateToMap, &request_header);
::MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND,
IterateToMap, &get_args);
std::shared_ptr<WebPage> page = nullptr;
{
mtx_guard lock(m_mtx);
for (const auto &elem : m_routes) {
const std::regex method_re = std::get<0>(elem);
const std::regex url_re = std::get<1>(elem);
if (!std::regex_match(vmethod, method_re)) {
continue;
}
if (!std::regex_match(url, url_re)) {
continue;
}
page = std::get<2>(elem);
break;
}
}
if (page != nullptr) {
return page->Do(vmethod, url, request_header, get_args);
}
// マッチするものがなかった場合は 404 とする
return HttpResponse(404);
}
int HttpServer::OnRequest(void *cls, struct MHD_Connection *connection,
const char *url, const char *method,
const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls) noexcept
{
auto self = static_cast<HttpServer *>(cls);
// non-static に移行
// HttpResponse オブジェクトを返してもらう
HttpResponse resp = self->ProcessRequest(
connection, url, method, version,
upload_data, upload_data_size, con_cls);
// エラー (4xx, 5xx) で body がない場合はここで自動生成する
if (resp.Status / 100 == 4 || resp.Status / 100 == 5) {
if (resp.Body.size() == 0) {
const std::string status_str = std::to_string(resp.Status);
resp.Header["Content-Type"] = "text/html; charset=utf-8";
resp.Body = R"(<!DOCTYPE html>
<html lang="en">
<head>
<title>Error: )" + status_str + R"(</title>
</head>
<body>
<h1>Error: )" + status_str + R"(</h1>
Sorry.
</body>
</html>
)";
}
}
// HttpResponse を変換処理してクライアントに返す
// ソースを確認したが malloc してそこに memcpy しているだけなので
// const を外しても問題ない
auto resp_del = [](MHD_Response *r) {
::MHD_destroy_response(r);
};
MHD_Response *tmp = MHD_create_response_from_buffer(
resp.Body.size(), const_cast<char *>(resp.Body.c_str()),
MHD_RESPMEM_MUST_COPY);
std::unique_ptr<MHD_Response, decltype(resp_del)> mhd_resp(tmp, resp_del);
if (mhd_resp == nullptr) {
logger.Log(LogLevel::Error, "MHD_create_response_from_buffer failed");
return MHD_NO;
}
int ret = MHD_queue_response(connection, resp.Status, mhd_resp.get());
if (ret != MHD_YES) {
logger.Log(LogLevel::Error, "MHD_queue_response failed");
return MHD_NO;
}
return MHD_YES;
}
} // namespace system
} // namespace shanghai
<commit_msg>REUSE オプションの設定方法が間違っていたのを修正<commit_after>#include "httpserver.h"
#include "../logger.h"
#include "../config.h"
#include <microhttpd.h>
namespace shanghai {
namespace system {
namespace {
using mtx_guard = std::lock_guard<std::mutex>;
// libmicrohttpd の内部アサートっぽいので諦めて死ぬ
void AtPanic(void *cls, const char *file, unsigned int line, const char *reason)
{
logger.Log(LogLevel::Fatal, "libmicrohttpd panic");
logger.Log(LogLevel::Fatal, "%s:%u %s", file, line, reason);
std::terminate();
}
// イテレートコールバックを map<string, string> に変換する
int IterateToMap(void *cls, enum MHD_ValueKind kind,
const char *key, const char *value) noexcept
{
auto &map = *static_cast<KeyValueSet *>(cls);
value = (value == nullptr) ? "" : value;
map.emplace(key, value);
return MHD_YES;
}
} // namespace
HttpServer::HttpServer() : m_daemon(nullptr)
{
logger.Log(LogLevel::Info, "Initialize HttpServer...");
// 設定の読み出し
int port = config.GetInt({"HttpServer", "Port"});
if (port < 0 || port > 0xffff) {
throw ConfigError("Invalid HttpServer port");
}
// サーバスタート (失敗時はコンストラクト失敗、デストラクトなし)
::MHD_set_panic_func(AtPanic, nullptr);
m_daemon = ::MHD_start_daemon(
MHD_USE_SELECT_INTERNALLY, port, nullptr, nullptr,
OnRequest, this,
MHD_OPTION_CONNECTION_MEMORY_LIMIT, MemoryLimit,
MHD_OPTION_CONNECTION_LIMIT, MaxConn,
MHD_OPTION_CONNECTION_TIMEOUT, TimeoutSec,
MHD_OPTION_PER_IP_CONNECTION_LIMIT, IpConnLimit,
MHD_OPTION_THREAD_POOL_SIZE, ThreadPoolSize,
MHD_OPTION_LISTENING_ADDRESS_REUSE, 1U,
MHD_OPTION_END);
if (m_daemon == nullptr) {
throw std::runtime_error("Starting HTTP server failed");
}
logger.Log(LogLevel::Info, "Initialize HttpServer OK (port=%d)", port);
}
HttpServer::~HttpServer()
{
// デストラクタでサーバ停止
::MHD_stop_daemon(m_daemon);
m_daemon = nullptr;
}
void HttpServer::AddPage(const std::regex &method, const std::regex &url,
std::shared_ptr<WebPage> page)
{
mtx_guard lock(m_mtx);
m_routes.emplace_back(method, url, page);
// unlock
}
HttpResponse HttpServer::ProcessRequest(struct MHD_Connection *connection,
const std::string &url, const std::string &method,
const std::string &version, const char *upload_data,
size_t *upload_data_size, void **con_cls) noexcept
{
logger.Log(LogLevel::Info, "[HTTP] %s %s %s",
version.c_str(), method.c_str(), url.c_str());
// version: HTTP/1.1 以外は "505 HTTP Version Not Supported"
if (version != "HTTP/1.1") {
return HttpResponse(505);
}
// HEAD は libmicrohttpd が自動で Response body をカットしてくれるので
// GET と同じ処理をしてあとは任せる
const std::string &vmethod = (method == "HEAD") ? "GET"s : method;
// HTTP request header と query を map に変換する
KeyValueSet request_header;
KeyValueSet get_args;
::MHD_get_connection_values(connection, MHD_HEADER_KIND,
IterateToMap, &request_header);
::MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND,
IterateToMap, &get_args);
std::shared_ptr<WebPage> page = nullptr;
{
mtx_guard lock(m_mtx);
for (const auto &elem : m_routes) {
const std::regex method_re = std::get<0>(elem);
const std::regex url_re = std::get<1>(elem);
if (!std::regex_match(vmethod, method_re)) {
continue;
}
if (!std::regex_match(url, url_re)) {
continue;
}
page = std::get<2>(elem);
break;
}
}
if (page != nullptr) {
return page->Do(vmethod, url, request_header, get_args);
}
// マッチするものがなかった場合は 404 とする
return HttpResponse(404);
}
int HttpServer::OnRequest(void *cls, struct MHD_Connection *connection,
const char *url, const char *method,
const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls) noexcept
{
auto self = static_cast<HttpServer *>(cls);
// non-static に移行
// HttpResponse オブジェクトを返してもらう
HttpResponse resp = self->ProcessRequest(
connection, url, method, version,
upload_data, upload_data_size, con_cls);
// エラー (4xx, 5xx) で body がない場合はここで自動生成する
if (resp.Status / 100 == 4 || resp.Status / 100 == 5) {
if (resp.Body.size() == 0) {
const std::string status_str = std::to_string(resp.Status);
resp.Header["Content-Type"] = "text/html; charset=utf-8";
resp.Body = R"(<!DOCTYPE html>
<html lang="en">
<head>
<title>Error: )" + status_str + R"(</title>
</head>
<body>
<h1>Error: )" + status_str + R"(</h1>
Sorry.
</body>
</html>
)";
}
}
// HttpResponse を変換処理してクライアントに返す
// ソースを確認したが malloc してそこに memcpy しているだけなので
// const を外しても問題ない
auto resp_del = [](MHD_Response *r) {
::MHD_destroy_response(r);
};
MHD_Response *tmp = MHD_create_response_from_buffer(
resp.Body.size(), const_cast<char *>(resp.Body.c_str()),
MHD_RESPMEM_MUST_COPY);
std::unique_ptr<MHD_Response, decltype(resp_del)> mhd_resp(tmp, resp_del);
if (mhd_resp == nullptr) {
logger.Log(LogLevel::Error, "MHD_create_response_from_buffer failed");
return MHD_NO;
}
int ret = MHD_queue_response(connection, resp.Status, mhd_resp.get());
if (ret != MHD_YES) {
logger.Log(LogLevel::Error, "MHD_queue_response failed");
return MHD_NO;
}
return MHD_YES;
}
} // namespace system
} // namespace shanghai
<|endoftext|> |
<commit_before>//Consul Admin Tests
#include "logging.h"
#include "consul_admin.h"
#include <string>
#include <string.h>
#include <assert.h>
int main()
{
//Construction tests
ConsulAdmin ca ("http://localhost:8500/");
Service s ("1", "CLyman", "tcp://*", "5555");
s.add_tag("Testing");
Service s2 ("2", "CLyman", "tcp://*", "5557");
s2.add_tag("Test");
Service s3 ("3", "OtherService", "tcp://*", "5559");
s3.add_tag("Test");
s3.clear_tags();
s3.add_tag("Test2");
s3.add_tag("Test3");
assert(s3.num_tags() == 2);
//Test Service Registration
ca.register_service(s);
logging->debug(ca.services_dc(""));
//Test Service Deregistration
ca.deregister_service(s);
logging->debug(ca.services_dc(""));
//Test Queries
logging->debug(ca.datacenters());
logging->debug(ca.nodes_dc(""));
logging->debug(ca.nodes_service("CLyman"));
logging->debug(ca.services_node(""));
//Test Key-Value Store
bool success = ca.set_config_value("Test", "123");
assert(success);
std::string test_val = ca.get_config_value("Test");
assert(test_val == "123");
success = ca.del_config_value("Test");
assert(success);
}
<commit_msg>Consul Admin Fixes<commit_after>//Consul Admin Tests
#include "include/logging.h"
#include "include/consul_admin.h"
#include <string>
#include <string.h>
#include <assert.h>
int main()
{
//Construction tests
ConsulAdmin ca ("http://localhost:8500/");
Service s ("1", "CLyman", "tcp://*", "5555");
s.add_tag("Testing");
Service s2 ("2", "CLyman", "tcp://*", "5557");
s2.add_tag("Test");
Service s3 ("3", "OtherService", "tcp://*", "5559");
s3.add_tag("Test");
s3.clear_tags();
s3.add_tag("Test2");
s3.add_tag("Test3");
assert(s3.num_tags() == 2);
//Test Service Registration
ca.register_service(s);
logging->debug(ca.services_dc(""));
//Test Service Deregistration
ca.deregister_service(s);
logging->debug(ca.services_dc(""));
//Test Queries
logging->debug(ca.datacenters());
logging->debug(ca.nodes_dc(""));
logging->debug(ca.nodes_service("CLyman"));
logging->debug(ca.services_node(""));
//Test Key-Value Store
bool success = ca.set_config_value("Test", "123");
assert(success);
std::string test_val = ca.get_config_value("Test");
assert(test_val == "123");
success = ca.del_config_value("Test");
assert(success);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a simple application that stress-tests the crash recovery of the disk
// cache. The main application starts a copy of itself on a loop, checking the
// exit code of the child process. When the child dies in an unexpected way,
// the main application quits.
// The child application has two threads: one to exercise the cache in an
// infinite loop, and another one to asynchronously kill the process.
// A regular build should never crash.
// To test that the disk cache doesn't generate critical errors with regular
// application level crashes, edit stress_support.h.
#include <string>
#include <vector>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/base/io_buffer.h"
#include "net/disk_cache/backend_impl.h"
#include "net/disk_cache/disk_cache.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/disk_cache/stress_support.h"
#include "net/disk_cache/trace.h"
#if defined(OS_WIN)
#include "base/logging_win.h"
#endif
using base::Time;
const int kError = -1;
const int kExpectedCrash = 100;
// Starts a new process.
int RunSlave(int iteration) {
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
CommandLine cmdline(exe);
cmdline.AppendArg(base::IntToString(iteration));
base::ProcessHandle handle;
if (!base::LaunchProcess(cmdline, base::LaunchOptions(), &handle)) {
printf("Unable to run test\n");
return kError;
}
int exit_code;
if (!base::WaitForExitCode(handle, &exit_code)) {
printf("Unable to get return code\n");
return kError;
}
return exit_code;
}
// Main loop for the master process.
int MasterCode() {
for (int i = 0; i < 100000; i++) {
int ret = RunSlave(i);
if (kExpectedCrash != ret)
return ret;
}
printf("More than enough...\n");
return 0;
}
// -----------------------------------------------------------------------
std::string GenerateStressKey() {
char key[20 * 1024];
size_t size = 50 + rand() % 20000;
CacheTestFillBuffer(key, size, true);
key[size - 1] = '\0';
return std::string(key);
}
// This thread will loop forever, adding and removing entries from the cache.
// iteration is the current crash cycle, so the entries on the cache are marked
// to know which instance of the application wrote them.
void StressTheCache(int iteration) {
int cache_size = 0x2000000; // 32MB.
uint32 mask = 0xfff; // 4096 entries.
FilePath path = GetCacheFilePath().InsertBeforeExtensionASCII("_stress");
base::Thread cache_thread("CacheThread");
if (!cache_thread.StartWithOptions(
base::Thread::Options(MessageLoop::TYPE_IO, 0)))
return;
disk_cache::BackendImpl* cache =
new disk_cache::BackendImpl(path, mask, cache_thread.message_loop_proxy(),
NULL);
cache->SetMaxSize(cache_size);
cache->SetFlags(disk_cache::kNoLoadProtection);
net::TestCompletionCallback cb;
int rv = cache->Init(cb.callback());
if (cb.GetResult(rv) != net::OK) {
printf("Unable to initialize cache.\n");
return;
}
printf("Iteration %d, initial entries: %d\n", iteration,
cache->GetEntryCount());
int seed = static_cast<int>(Time::Now().ToInternalValue());
srand(seed);
// kNumKeys is meant to be enough to have about 3x or 4x iterations before
// the process crashes.
#ifdef NDEBUG
const int kNumKeys = 4000;
#else
const int kNumKeys = 1200;
#endif
const int kNumEntries = 30;
std::string keys[kNumKeys];
disk_cache::Entry* entries[kNumEntries] = {0};
for (int i = 0; i < kNumKeys; i++) {
keys[i] = GenerateStressKey();
}
const int kSize = 20000;
scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(kSize));
memset(buffer->data(), 'k', kSize);
for (int i = 0;; i++) {
int slot = rand() % kNumEntries;
int key = rand() % kNumKeys;
bool truncate = rand() % 2 ? false : true;
int size = kSize - (rand() % 20) * kSize / 20;
if (entries[slot])
entries[slot]->Close();
net::TestCompletionCallback cb;
rv = cache->OpenEntry(keys[key], &entries[slot], cb.callback());
if (cb.GetResult(rv) != net::OK) {
rv = cache->CreateEntry(keys[key], &entries[slot], cb.callback());
CHECK_EQ(net::OK, cb.GetResult(rv));
}
base::snprintf(buffer->data(), kSize,
"i: %d iter: %d, size: %d, truncate: %d ", i, iteration,
size, truncate ? 1 : 0);
rv = entries[slot]->WriteData(0, 0, buffer, size, cb.callback(), truncate);
CHECK_EQ(size, cb.GetResult(rv));
if (rand() % 100 > 80) {
key = rand() % kNumKeys;
net::TestCompletionCallback cb2;
rv = cache->DoomEntry(keys[key], cb2.callback());
cb2.GetResult(rv);
}
if (!(i % 100))
printf("Entries: %d \r", i);
}
}
// We want to prevent the timer thread from killing the process while we are
// waiting for the debugger to attach.
bool g_crashing = false;
class CrashTask : public Task {
public:
CrashTask() {}
~CrashTask() {}
virtual void Run() {
// Keep trying to run.
RunSoon(MessageLoop::current());
if (g_crashing)
return;
if (rand() % 100 > 30) {
printf("sweet death...\n");
#if defined(OS_WIN)
// Windows does more work on _exit() that we would like, so we use Kill.
base::KillProcessById(base::GetCurrentProcId(), kExpectedCrash, false);
#elif defined(OS_POSIX)
// On POSIX, _exit() will terminate the process with minimal cleanup,
// and it is cleaner than killing.
_exit(kExpectedCrash);
#endif
}
}
static void RunSoon(MessageLoop* target_loop) {
int task_delay = 10000; // 10 seconds
CrashTask* task = new CrashTask();
target_loop->PostDelayedTask(FROM_HERE, task, task_delay);
}
};
// We leak everything here :)
bool StartCrashThread() {
base::Thread* thread = new base::Thread("party_crasher");
if (!thread->Start())
return false;
CrashTask::RunSoon(thread->message_loop());
return true;
}
void CrashHandler(const std::string& str) {
g_crashing = true;
base::debug::BreakDebugger();
}
bool MessageHandler(int severity, const char* file, int line,
size_t message_start, const std::string& str) {
const size_t kMaxMessageLen = 48;
char message[kMaxMessageLen];
size_t len = std::min(str.length() - message_start, kMaxMessageLen - 1);
memcpy(message, str.c_str() + message_start, len);
message[len] = '\0';
#if !defined(DISK_CACHE_TRACE_TO_LOG)
disk_cache::Trace("%s", message);
#endif
return false;
}
// -----------------------------------------------------------------------
#if defined(OS_WIN)
// {B9A153D4-31C3-48e4-9ABF-D54383F14A0D}
const GUID kStressCacheTraceProviderName = {
0xb9a153d4, 0x31c3, 0x48e4,
{ 0x9a, 0xbf, 0xd5, 0x43, 0x83, 0xf1, 0x4a, 0xd } };
#endif
int main(int argc, const char* argv[]) {
// Setup an AtExitManager so Singleton objects will be destructed.
base::AtExitManager at_exit_manager;
if (argc < 2)
return MasterCode();
logging::SetLogAssertHandler(CrashHandler);
logging::SetLogMessageHandler(MessageHandler);
#if defined(OS_WIN)
logging::LogEventProvider::Initialize(kStressCacheTraceProviderName);
#else
CommandLine::Init(argc, argv);
logging::InitLogging(NULL, logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE, logging::DELETE_OLD_LOG_FILE,
logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
#endif
// Some time for the memory manager to flush stuff.
base::PlatformThread::Sleep(3000);
MessageLoop message_loop(MessageLoop::TYPE_IO);
char* end;
long int iteration = strtol(argv[1], &end, 0);
if (!StartCrashThread()) {
printf("failed to start thread\n");
return kError;
}
StressTheCache(iteration);
return 0;
}
<commit_msg>base::Bind(): stress_cache.cc<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a simple application that stress-tests the crash recovery of the disk
// cache. The main application starts a copy of itself on a loop, checking the
// exit code of the child process. When the child dies in an unexpected way,
// the main application quits.
// The child application has two threads: one to exercise the cache in an
// infinite loop, and another one to asynchronously kill the process.
// A regular build should never crash.
// To test that the disk cache doesn't generate critical errors with regular
// application level crashes, edit stress_support.h.
#include <string>
#include <vector>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/base/io_buffer.h"
#include "net/disk_cache/backend_impl.h"
#include "net/disk_cache/disk_cache.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/disk_cache/stress_support.h"
#include "net/disk_cache/trace.h"
#if defined(OS_WIN)
#include "base/logging_win.h"
#endif
using base::Time;
const int kError = -1;
const int kExpectedCrash = 100;
// Starts a new process.
int RunSlave(int iteration) {
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
CommandLine cmdline(exe);
cmdline.AppendArg(base::IntToString(iteration));
base::ProcessHandle handle;
if (!base::LaunchProcess(cmdline, base::LaunchOptions(), &handle)) {
printf("Unable to run test\n");
return kError;
}
int exit_code;
if (!base::WaitForExitCode(handle, &exit_code)) {
printf("Unable to get return code\n");
return kError;
}
return exit_code;
}
// Main loop for the master process.
int MasterCode() {
for (int i = 0; i < 100000; i++) {
int ret = RunSlave(i);
if (kExpectedCrash != ret)
return ret;
}
printf("More than enough...\n");
return 0;
}
// -----------------------------------------------------------------------
std::string GenerateStressKey() {
char key[20 * 1024];
size_t size = 50 + rand() % 20000;
CacheTestFillBuffer(key, size, true);
key[size - 1] = '\0';
return std::string(key);
}
// This thread will loop forever, adding and removing entries from the cache.
// iteration is the current crash cycle, so the entries on the cache are marked
// to know which instance of the application wrote them.
void StressTheCache(int iteration) {
int cache_size = 0x2000000; // 32MB.
uint32 mask = 0xfff; // 4096 entries.
FilePath path = GetCacheFilePath().InsertBeforeExtensionASCII("_stress");
base::Thread cache_thread("CacheThread");
if (!cache_thread.StartWithOptions(
base::Thread::Options(MessageLoop::TYPE_IO, 0)))
return;
disk_cache::BackendImpl* cache =
new disk_cache::BackendImpl(path, mask, cache_thread.message_loop_proxy(),
NULL);
cache->SetMaxSize(cache_size);
cache->SetFlags(disk_cache::kNoLoadProtection);
net::TestCompletionCallback cb;
int rv = cache->Init(cb.callback());
if (cb.GetResult(rv) != net::OK) {
printf("Unable to initialize cache.\n");
return;
}
printf("Iteration %d, initial entries: %d\n", iteration,
cache->GetEntryCount());
int seed = static_cast<int>(Time::Now().ToInternalValue());
srand(seed);
// kNumKeys is meant to be enough to have about 3x or 4x iterations before
// the process crashes.
#ifdef NDEBUG
const int kNumKeys = 4000;
#else
const int kNumKeys = 1200;
#endif
const int kNumEntries = 30;
std::string keys[kNumKeys];
disk_cache::Entry* entries[kNumEntries] = {0};
for (int i = 0; i < kNumKeys; i++) {
keys[i] = GenerateStressKey();
}
const int kSize = 20000;
scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(kSize));
memset(buffer->data(), 'k', kSize);
for (int i = 0;; i++) {
int slot = rand() % kNumEntries;
int key = rand() % kNumKeys;
bool truncate = rand() % 2 ? false : true;
int size = kSize - (rand() % 20) * kSize / 20;
if (entries[slot])
entries[slot]->Close();
net::TestCompletionCallback cb;
rv = cache->OpenEntry(keys[key], &entries[slot], cb.callback());
if (cb.GetResult(rv) != net::OK) {
rv = cache->CreateEntry(keys[key], &entries[slot], cb.callback());
CHECK_EQ(net::OK, cb.GetResult(rv));
}
base::snprintf(buffer->data(), kSize,
"i: %d iter: %d, size: %d, truncate: %d ", i, iteration,
size, truncate ? 1 : 0);
rv = entries[slot]->WriteData(0, 0, buffer, size, cb.callback(), truncate);
CHECK_EQ(size, cb.GetResult(rv));
if (rand() % 100 > 80) {
key = rand() % kNumKeys;
net::TestCompletionCallback cb2;
rv = cache->DoomEntry(keys[key], cb2.callback());
cb2.GetResult(rv);
}
if (!(i % 100))
printf("Entries: %d \r", i);
}
}
// We want to prevent the timer thread from killing the process while we are
// waiting for the debugger to attach.
bool g_crashing = false;
void RunSoon(MessageLoop* target_loop);
void Crash() {
// Keep trying to run.
RunSoon(MessageLoop::current());
if (g_crashing)
return;
if (rand() % 100 > 30) {
printf("sweet death...\n");
#if defined(OS_WIN)
// Windows does more work on _exit() that we would like, so we use Kill.
base::KillProcessById(base::GetCurrentProcId(), kExpectedCrash, false);
#elif defined(OS_POSIX)
// On POSIX, _exit() will terminate the process with minimal cleanup,
// and it is cleaner than killing.
_exit(kExpectedCrash);
#endif
}
}
void RunSoon(MessageLoop* target_loop) {
int task_delay = 10000; // 10 seconds
target_loop->PostDelayedTask(FROM_HERE, base::Bind(&Crash), task_delay);
}
// We leak everything here :)
bool StartCrashThread() {
base::Thread* thread = new base::Thread("party_crasher");
if (!thread->Start())
return false;
RunSoon(thread->message_loop());
return true;
}
void CrashHandler(const std::string& str) {
g_crashing = true;
base::debug::BreakDebugger();
}
bool MessageHandler(int severity, const char* file, int line,
size_t message_start, const std::string& str) {
const size_t kMaxMessageLen = 48;
char message[kMaxMessageLen];
size_t len = std::min(str.length() - message_start, kMaxMessageLen - 1);
memcpy(message, str.c_str() + message_start, len);
message[len] = '\0';
#if !defined(DISK_CACHE_TRACE_TO_LOG)
disk_cache::Trace("%s", message);
#endif
return false;
}
// -----------------------------------------------------------------------
#if defined(OS_WIN)
// {B9A153D4-31C3-48e4-9ABF-D54383F14A0D}
const GUID kStressCacheTraceProviderName = {
0xb9a153d4, 0x31c3, 0x48e4,
{ 0x9a, 0xbf, 0xd5, 0x43, 0x83, 0xf1, 0x4a, 0xd } };
#endif
int main(int argc, const char* argv[]) {
// Setup an AtExitManager so Singleton objects will be destructed.
base::AtExitManager at_exit_manager;
if (argc < 2)
return MasterCode();
logging::SetLogAssertHandler(CrashHandler);
logging::SetLogMessageHandler(MessageHandler);
#if defined(OS_WIN)
logging::LogEventProvider::Initialize(kStressCacheTraceProviderName);
#else
CommandLine::Init(argc, argv);
logging::InitLogging(NULL, logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE, logging::DELETE_OLD_LOG_FILE,
logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
#endif
// Some time for the memory manager to flush stuff.
base::PlatformThread::Sleep(3000);
MessageLoop message_loop(MessageLoop::TYPE_IO);
char* end;
long int iteration = strtol(argv[1], &end, 0);
if (!StartCrashThread()) {
printf("failed to start thread\n");
return kError;
}
StressTheCache(iteration);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grdocsh.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: kz $ $Date: 2006-12-12 17:13:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#define ITEMID_SEARCH SID_SEARCH_ITEM
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_SRCHITEM_HXX
#include <sfx2/srchitem.hxx>
#endif
#ifndef _GLOBNAME_HXX //autogen
#include <tools/globname.hxx>
#endif
#ifndef _SO_CLSIDS_HXX //autogen
#include <sot/clsids.hxx>
#endif
#include <sfx2/objface.hxx>
#include "app.hrc"
#include "strings.hrc"
#include "glob.hrc"
#ifndef SD_GRAPHIC_DOC_SHELL_HXX
#include "GraphicDocShell.hxx"
#endif
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#include "drawdoc.hxx"
#include "sdresid.hxx"
using namespace sd;
#define GraphicDocShell
#include "sdgslots.hxx"
namespace sd
{
TYPEINIT1(GraphicDocShell, DrawDocShell);
SFX_IMPL_INTERFACE(GraphicDocShell, SfxObjectShell, SdResId(0))
{
SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG);
SFX_CHILDWINDOW_REGISTRATION( SID_HYPERLINK_INSERT );
}
SFX_IMPL_OBJECTFACTORY( GraphicDocShell, SvGlobalName(SO3_SDRAW_CLASSID_60), SFXOBJECTSHELL_STD_NORMAL, "sdraw" )
GraphicDocShell::GraphicDocShell(SfxObjectCreateMode eMode,
BOOL bDataObject,
DocumentType eDocType) :
DrawDocShell(eMode, bDataObject, eDocType)
{
SetStyleFamily( 2 ); // SFX_STYLE_FAMILY_PARA
}
GraphicDocShell::~GraphicDocShell()
{
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS pchfix04 (1.11.6); FILE MERGED 2007/02/05 08:38:57 os 1.11.6.2: #i73604# usage of ITEMID_* removed 2007/01/19 10:49:56 hjs 1.11.6.1: #i73650# warning free with pch<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grdocsh.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2007-05-10 15:28:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_SRCHITEM_HXX
#include <sfx2/srchitem.hxx>
#endif
#ifndef _GLOBNAME_HXX //autogen
#include <tools/globname.hxx>
#endif
#ifndef _SO_CLSIDS_HXX //autogen
#include <sot/clsids.hxx>
#endif
#include <sfx2/objface.hxx>
#include "app.hrc"
#include "strings.hrc"
#include "glob.hrc"
#ifndef SD_GRAPHIC_DOC_SHELL_HXX
#include "GraphicDocShell.hxx"
#endif
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#include "drawdoc.hxx"
#include "sdresid.hxx"
using namespace sd;
#define GraphicDocShell
#include "sdgslots.hxx"
namespace sd
{
TYPEINIT1(GraphicDocShell, DrawDocShell);
SFX_IMPL_INTERFACE(GraphicDocShell, SfxObjectShell, SdResId(0))
{
SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG);
SFX_CHILDWINDOW_REGISTRATION( SID_HYPERLINK_INSERT );
}
SFX_IMPL_OBJECTFACTORY( GraphicDocShell, SvGlobalName(SO3_SDRAW_CLASSID_60), SFXOBJECTSHELL_STD_NORMAL, "sdraw" )
GraphicDocShell::GraphicDocShell(SfxObjectCreateMode eMode,
BOOL bDataObject,
DocumentType eDocType) :
DrawDocShell(eMode, bDataObject, eDocType)
{
SetStyleFamily( 2 ); // SFX_STYLE_FAMILY_PARA
}
GraphicDocShell::~GraphicDocShell()
{
}
} // end of namespace sd
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2010, 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 libuobject/uvar.cc
#include <libport/format.hh>
#include <libport/escape.hh>
#include <urbi/uabstractclient.hh>
#include <urbi/ublend-type.hh>
#include <urbi/uexternal.hh>
#include <urbi/umessage.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
#include <liburbi/compatibility.hh>
#include <libuobject/remote-ucontext-impl.hh>
namespace urbi
{
namespace impl
{
//! UVar initialization
void
RemoteUVarImpl::initialize(UVar* owner)
{
owner_ = owner;
RemoteUContextImpl* ctx = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_);
client_ = ctx->client_;
std::string name = owner_->get_name();
ctx->varmap()[name].push_back(owner_);
URBI_SEND_PIPED_COMMAND_C((*client_), "if (!isdef(" << name << ")) var "
<< name);
UObject* dummyUObject = ctx->getDummyUObject();
createUCallback(*dummyUObject, owner,
"var",
dummyUObject, &UObject::voidfun, name);
}
bool RemoteUVarImpl::setBypass(bool enable)
{
return !enable;
}
//! UVar out value (read mode)
ufloat&
RemoteUVarImpl::out()
{
return const_cast<ufloat&>(get().val);
}
//! UVar in value (write mode)
ufloat&
RemoteUVarImpl::in()
{
return const_cast<ufloat&>(get().val);
}
void
RemoteUVarImpl::setProp(UProperty p, const UValue& v)
{
URBI_SEND_PIPED_COMMAND_C((*client_), owner_->get_name() << "->"
<< urbi::name(p) << " = " << v);
}
void
RemoteUVarImpl::keepSynchronized()
{
//FIXME: do something?
}
UValue
RemoteUVarImpl::getProp(UProperty p)
{
UMessage* m = client_->syncGet("%s->%s", owner_->get_name().c_str(),
urbi::name(p));
aver(m->value);
UValue res = *m->value;
delete m;
return res;
}
/*
UBlendType
UVar::blend()
{
echo("Properties not implemented in remote mode yet.\n");
return UNORMAL;
}
*/
//! UVar destructor.
void
RemoteUVarImpl::clean()
{
RemoteUContextImpl* ctx = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_);
ctx->varmap().clean(*owner_);
}
void
RemoteUVarImpl::set(const UValue& v)
{
if (v.type == DATA_BINARY)
{
UBinary& b = *(v.binary);
client_->startPack();
// K1 only supports a binary at top level within ';' and no
// other separator.
if (client_->kernelMajor() < 2)
URBI_SEND_COMMAND_C((*client_),"");
(*client_) << owner_->get_name() << "=";
client_->sendBinary(b.common.data, b.common.size,
b.getMessage());
(*client_) << "|;";
client_->endPack();
}
else if (v.type == DATA_STRING)
URBI_SEND_PIPED_COMMAND_C((*client_), owner_->get_name() << "=\""
<< libport::escape(*v.stringValue, '"') << '"');
else
URBI_SEND_PIPED_COMMAND_C((*client_), owner_->get_name() << "=" << v);
}
const UValue& RemoteUVarImpl::get() const
{
return value_;
};
//! set own mode
void
RemoteUVarImpl::setOwned()
{
owner_->owned = true;
}
//! Get Uvalue type
UDataType
RemoteUVarImpl::type() const
{
return get().type;
}
void
RemoteUVarImpl::request()
{
std::string name = owner_->get_name();
//build a getvalue message that will be parsed and returned by the server
URBI_SEND_PIPED_COMMAND_C((*client_), externalModuleTag << "<<"
<<'[' << UEM_ASSIGNVALUE << ","
<< '"' << name << '"' << ',' << name << ']');
}
void
RemoteUVarImpl::sync()
{
std::string tag(client_->fresh());
std::string repeatChannel;
if (client_->kernelMajor() < 2)
repeatChannel = tag + " << ";
static boost::format
fmt("{\n"
" if (isdef (%s) && !(%s))\n"
" {\n"
" %s %s\n"
" }\n"
" else\n"
" {\n"
" %s 1/0\n"
" }\n"
"};\n");
std::string name = owner_->get_name();
std::string cmd = str(fmt
% name
% compatibility::isvoid(name.c_str(),
client_->kernelMajor())
% repeatChannel
% name
% repeatChannel);
UMessage* m = client_->syncGetTag("%s", tag.c_str(), 0, cmd.c_str());
if (m->type == MESSAGE_DATA)
value_ = *m->value;
}
void
RemoteUVarImpl::update(const UValue& v)
{
value_ = v;
}
void RemoteUVarImpl::unnotify()
{
std::string name = owner_->get_name();
size_t p = name.find_first_of(".");
if (p == name.npos)
throw std::runtime_error("Invalid argument to unnotify: "+name);
send(libport::format(
"UObject.unnotify(\"%s\", \"%s\", %s),",
name.substr(0, p), name.substr(p+1, name.npos),
callbacks_.size()));
foreach(RemoteUGenericCallbackImpl* c, callbacks_)
{
UTable& t =
dynamic_cast<RemoteUContextImpl*>(c->owner_->ctx_)
->tableByName(c->owner_->type);
UTable::callbacks_type& ct = t[c->owner_->name];
UTable::callbacks_type::iterator i =
std::find(ct.begin(), ct.end(), c->owner_);
if (i != ct.end())
ct.erase(i);
owner_->ctx_->addCleanup(c->owner_);
owner_->ctx_->addCleanup(c);
}
callbacks_.clear();
};
}
} //namespace urbi
<commit_msg>Factor RemoteUVarImpl::set.<commit_after>/*
* Copyright (C) 2005-2010, 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 libuobject/uvar.cc
#include <libport/format.hh>
#include <libport/escape.hh>
#include <urbi/uabstractclient.hh>
#include <urbi/ublend-type.hh>
#include <urbi/uexternal.hh>
#include <urbi/umessage.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
#include <liburbi/compatibility.hh>
#include <libuobject/remote-ucontext-impl.hh>
namespace urbi
{
namespace impl
{
//! UVar initialization
void
RemoteUVarImpl::initialize(UVar* owner)
{
owner_ = owner;
RemoteUContextImpl* ctx = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_);
client_ = ctx->client_;
std::string name = owner_->get_name();
ctx->varmap()[name].push_back(owner_);
URBI_SEND_PIPED_COMMAND_C((*client_), "if (!isdef(" << name << ")) var "
<< name);
UObject* dummyUObject = ctx->getDummyUObject();
createUCallback(*dummyUObject, owner,
"var",
dummyUObject, &UObject::voidfun, name);
}
bool RemoteUVarImpl::setBypass(bool enable)
{
return !enable;
}
//! UVar out value (read mode)
ufloat&
RemoteUVarImpl::out()
{
return const_cast<ufloat&>(get().val);
}
//! UVar in value (write mode)
ufloat&
RemoteUVarImpl::in()
{
return const_cast<ufloat&>(get().val);
}
void
RemoteUVarImpl::setProp(UProperty p, const UValue& v)
{
URBI_SEND_PIPED_COMMAND_C((*client_), owner_->get_name() << "->"
<< urbi::name(p) << " = " << v);
}
void
RemoteUVarImpl::keepSynchronized()
{
//FIXME: do something?
}
UValue
RemoteUVarImpl::getProp(UProperty p)
{
UMessage* m = client_->syncGet("%s->%s", owner_->get_name().c_str(),
urbi::name(p));
aver(m->value);
UValue res = *m->value;
delete m;
return res;
}
/*
UBlendType
UVar::blend()
{
echo("Properties not implemented in remote mode yet.\n");
return UNORMAL;
}
*/
//! UVar destructor.
void
RemoteUVarImpl::clean()
{
RemoteUContextImpl* ctx = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_);
ctx->varmap().clean(*owner_);
}
void
RemoteUVarImpl::set(const UValue& v)
{
client_->startPack();
(*client_) << owner_->get_name() << "=";
if (v.type == DATA_BINARY)
{
UBinary& b = *(v.binary);
client_->sendBinary(b.common.data, b.common.size,
b.getMessage());
(*client_) << "|;";
}
else if (v.type == DATA_STRING)
(*client_) << "\"" << libport::escape(*v.stringValue, '"') << "\"|";
else
*client_ << v << "|";
client_->endPack();
}
const UValue& RemoteUVarImpl::get() const
{
return value_;
};
//! set own mode
void
RemoteUVarImpl::setOwned()
{
owner_->owned = true;
}
//! Get Uvalue type
UDataType
RemoteUVarImpl::type() const
{
return get().type;
}
void
RemoteUVarImpl::request()
{
std::string name = owner_->get_name();
//build a getvalue message that will be parsed and returned by the server
URBI_SEND_PIPED_COMMAND_C((*client_), externalModuleTag << "<<"
<<'[' << UEM_ASSIGNVALUE << ","
<< '"' << name << '"' << ',' << name << ']');
}
void
RemoteUVarImpl::sync()
{
std::string tag(client_->fresh());
std::string repeatChannel;
if (client_->kernelMajor() < 2)
repeatChannel = tag + " << ";
static boost::format
fmt("{\n"
" if (isdef (%s) && !(%s))\n"
" {\n"
" %s %s\n"
" }\n"
" else\n"
" {\n"
" %s 1/0\n"
" }\n"
"};\n");
std::string name = owner_->get_name();
std::string cmd = str(fmt
% name
% compatibility::isvoid(name.c_str(),
client_->kernelMajor())
% repeatChannel
% name
% repeatChannel);
UMessage* m = client_->syncGetTag("%s", tag.c_str(), 0, cmd.c_str());
if (m->type == MESSAGE_DATA)
value_ = *m->value;
}
void
RemoteUVarImpl::update(const UValue& v)
{
value_ = v;
}
void RemoteUVarImpl::unnotify()
{
std::string name = owner_->get_name();
size_t p = name.find_first_of(".");
if (p == name.npos)
throw std::runtime_error("Invalid argument to unnotify: "+name);
send(libport::format(
"UObject.unnotify(\"%s\", \"%s\", %s),",
name.substr(0, p), name.substr(p+1, name.npos),
callbacks_.size()));
foreach(RemoteUGenericCallbackImpl* c, callbacks_)
{
UTable& t =
dynamic_cast<RemoteUContextImpl*>(c->owner_->ctx_)
->tableByName(c->owner_->type);
UTable::callbacks_type& ct = t[c->owner_->name];
UTable::callbacks_type::iterator i =
std::find(ct.begin(), ct.end(), c->owner_);
if (i != ct.end())
ct.erase(i);
owner_->ctx_->addCleanup(c->owner_);
owner_->ctx_->addCleanup(c);
}
callbacks_.clear();
};
}
} //namespace urbi
<|endoftext|> |
<commit_before>/// \file libuobject/uvar.cc
#include <libport/escape.hh>
#include <urbi/uabstractclient.hh>
#include <urbi/ublend-type.hh>
#include <urbi/uexternal.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
namespace urbi
{
class UVardata
{
public:
UVardata()
{
}
~UVardata()
{
}
};
//! UVar initialization
void
UVar::__init()
{
varmap()[name].push_back(this);
URBI_SEND_PIPED_COMMAND("if (!isdef(" << name << ")) var " << name);
vardata = 0; // unused. For internal softdevices only
this->owned = false;
assert (dummyUObject);
createUCallback(dummyUObject->__name,
"var",
dummyUObject, &UObject::voidfun, name, monitormap(), false);
}
//! UVar out value (read mode)
ufloat&
UVar::out()
{
return value.val;
}
//! UVar in value (write mode)
ufloat&
UVar::in()
{
return value.val;
}
void
UVar::setProp(UProperty p, const UValue& v)
{
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = " << v);
}
void
UVar::setProp(UProperty p, const char* v)
{
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = " << v);
}
void
UVar::setProp(UProperty p, double v)
{
// FIXME: This is not the right way to do it. Generalize
// conversions between enums and strings.
int i = static_cast<int>(v);
if (p == PROP_BLEND && is_blendtype(i))
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = "
<< '"'
<< urbi::name(static_cast<UBlendType>(i))
<< '"');
else
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = " << v);
}
UValue
UVar::getProp(UProperty p)
{
USyncClient& uc = dynamic_cast<USyncClient&>(get_default_client());
UMessage* m = uc.syncGet("%s->%s", name.c_str(), urbi::name(p));
UValue v = *m->value;
delete m;
return v;
}
/*
UBlendType
UVar::blend()
{
echo("Properties not implemented in remote mode yet.\n");
return UNORMAL;
}
*/
//! UVar destructor.
UVar::~UVar()
{
varmap().clean(*this);
}
// This is a stub for something that might be existing in k1. k2 no
// longer uses it, but SDK-Remote tries to stay compatible with it.
class UVariable
{};
//! Set the UVar in "zombie" mode (the attached UVariable is dead)
void
UVar::setZombie()
{
// no effect in remote mode.
}
//! Return the internal variable.
UVariable*
UVar::variable()
{
return 0;
}
//! UVar reset (deep assignement)
void
UVar::reset(ufloat n)
{
*this = n;
}
//! UVar float assignment
void
UVar::operator = (ufloat n)
{
URBI_SEND_PIPED_COMMAND(name << "=" << n);
}
//! UVar string assignment
void
UVar::operator= (const std::string& s)
{
URBI_SEND_PIPED_COMMAND(name << "=\"" << libport::escape(s, '"') << '"');
}
//! UVar binary assignment
void
UVar::operator = (const UBinary& b)
{
getDefaultClient()->startPack();
// K1 only supports a binary at top level within ';' and no other separator.
if (getDefaultClient()->kernelMajor() < 2)
URBI_SEND_COMMAND("");
(*getDefaultClient()) << name << "=";
getDefaultClient()->sendBinary(b.common.data, b.common.size,
b.getMessage());
(*getDefaultClient()) << ";";
getDefaultClient()->endPack();
}
void
UVar::operator= (const UImage& i)
{
//we don't use UBinary Image ctor because it copies data
UBinary b;
b.type = BINARY_IMAGE;
b.image = i;
(*this) = b;
b.common.data = 0; //required, dtor frees data
}
void
UVar::operator= (const USound& i)
{
//we don't use UBinary Image ctor because it copies data
UBinary b;
b.type = BINARY_SOUND;
b.sound = i;
(*this) = b;
b.common.data = 0; //required, dtor frees data
}
void
UVar::operator= (const UList& l)
{
UValue v;
v.type = DATA_LIST;
v.list = &const_cast<UList&>(l);
URBI_SEND_PIPED_COMMAND(name << "=" << v);
v.type = DATA_VOID;
v.list = 0;
}
UVar::operator int() const
{
return (int) value;
};
UVar::operator ufloat() const
{
return (ufloat) value;
};
UVar::operator std::string() const
{
return (std::string) value;
};
UVar::operator UBinary() const
{
return value;
};
UVar::operator UBinary*() const
{
return new UBinary(value.operator UBinary());
};
UVar::operator UImage() const
{
return (UImage) value;
};
UVar::operator USound() const
{
return (USound) value;
};
UVar::operator UList() const
{
return (UList) value;
};
//! UVar update
void
UVar::__update(UValue& v)
{
# ifdef LIBURBIDEBUG
std::cout << " Variable " << name << " updated to : ";
switch (v.type)
{
case DATA_DOUBLE:
std::cout << (double)v << std::endl;
break;
case DATA_STRING:
std::cout << (std::string)v << std::endl;
break;
case DATA_BINARY:
case DATA_LIST:
case DATA_OBJECT:
case DATA_VOID:
break;
}
# endif
value = v;
}
//! set own mode
void
UVar::setOwned()
{
owned = true;
}
//! Get Uvalue type
UDataType
UVar::type() const
{
return value.type;
}
void
UVar::requestValue()
{
//build a getvalue message that will be parsed and returned by the server
URBI_SEND_PIPED_COMMAND(externalModuleTag << "<<"
<<'[' << UEM_ASSIGNVALUE << ","
<< '"' << name << '"' << ',' << name << ']');
}
void
UVar::syncValue()
{
USyncClient& client = dynamic_cast<USyncClient&> (URBI(()));
char tag[32];
client.makeUniqueTag(tag);
UMessage* m =
client.syncGetTag("{"
" if (isdef (%s) && !isvoid (%s))"
" {"
" %s<<%s"
" }"
" else"
" {"
" %s<<1/0"
" }"
"};",
tag, 0, name.c_str(), name.c_str(),
tag, name.c_str(), tag);
if (m->type == MESSAGE_DATA)
__update(*m->value);
}
} //namespace urbi
<commit_msg>Simplify/documentation UVardata.<commit_after>/// \file libuobject/uvar.cc
#include <libport/escape.hh>
#include <urbi/uabstractclient.hh>
#include <urbi/ublend-type.hh>
#include <urbi/uexternal.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
namespace urbi
{
/// This class is useless in SDK-Remote, and it is not used by Urbi
/// 2 either. But Urbi 1 uses this field to store private data, and
/// since SDK-Remote is to be compatible with both Urbi, keep it,
/// although useless.
class UVardata
{};
//! UVar initialization
void
UVar::__init()
{
varmap()[name].push_back(this);
URBI_SEND_PIPED_COMMAND("if (!isdef(" << name << ")) var " << name);
vardata = 0; // unused. For internal softdevices only
this->owned = false;
assert (dummyUObject);
createUCallback(dummyUObject->__name,
"var",
dummyUObject, &UObject::voidfun, name, monitormap(), false);
}
//! UVar out value (read mode)
ufloat&
UVar::out()
{
return value.val;
}
//! UVar in value (write mode)
ufloat&
UVar::in()
{
return value.val;
}
void
UVar::setProp(UProperty p, const UValue& v)
{
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = " << v);
}
void
UVar::setProp(UProperty p, const char* v)
{
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = " << v);
}
void
UVar::setProp(UProperty p, double v)
{
// FIXME: This is not the right way to do it. Generalize
// conversions between enums and strings.
int i = static_cast<int>(v);
if (p == PROP_BLEND && is_blendtype(i))
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = "
<< '"'
<< urbi::name(static_cast<UBlendType>(i))
<< '"');
else
URBI_SEND_PIPED_COMMAND(name << "->" << urbi::name(p) << " = " << v);
}
UValue
UVar::getProp(UProperty p)
{
USyncClient& uc = dynamic_cast<USyncClient&>(get_default_client());
UMessage* m = uc.syncGet("%s->%s", name.c_str(), urbi::name(p));
UValue v = *m->value;
delete m;
return v;
}
/*
UBlendType
UVar::blend()
{
echo("Properties not implemented in remote mode yet.\n");
return UNORMAL;
}
*/
//! UVar destructor.
UVar::~UVar()
{
varmap().clean(*this);
}
// This is a stub for something that might be existing in k1. k2 no
// longer uses it, but SDK-Remote tries to stay compatible with it.
class UVariable
{};
//! Set the UVar in "zombie" mode (the attached UVariable is dead)
void
UVar::setZombie()
{
// no effect in remote mode.
}
//! Return the internal variable.
UVariable*
UVar::variable()
{
return 0;
}
//! UVar reset (deep assignement)
void
UVar::reset(ufloat n)
{
*this = n;
}
//! UVar float assignment
void
UVar::operator = (ufloat n)
{
URBI_SEND_PIPED_COMMAND(name << "=" << n);
}
//! UVar string assignment
void
UVar::operator= (const std::string& s)
{
URBI_SEND_PIPED_COMMAND(name << "=\"" << libport::escape(s, '"') << '"');
}
//! UVar binary assignment
void
UVar::operator = (const UBinary& b)
{
getDefaultClient()->startPack();
// K1 only supports a binary at top level within ';' and no other separator.
if (getDefaultClient()->kernelMajor() < 2)
URBI_SEND_COMMAND("");
(*getDefaultClient()) << name << "=";
getDefaultClient()->sendBinary(b.common.data, b.common.size,
b.getMessage());
(*getDefaultClient()) << ";";
getDefaultClient()->endPack();
}
void
UVar::operator= (const UImage& i)
{
//we don't use UBinary Image ctor because it copies data
UBinary b;
b.type = BINARY_IMAGE;
b.image = i;
(*this) = b;
b.common.data = 0; //required, dtor frees data
}
void
UVar::operator= (const USound& i)
{
//we don't use UBinary Image ctor because it copies data
UBinary b;
b.type = BINARY_SOUND;
b.sound = i;
(*this) = b;
b.common.data = 0; //required, dtor frees data
}
void
UVar::operator= (const UList& l)
{
UValue v;
v.type = DATA_LIST;
v.list = &const_cast<UList&>(l);
URBI_SEND_PIPED_COMMAND(name << "=" << v);
v.type = DATA_VOID;
v.list = 0;
}
UVar::operator int() const
{
return (int) value;
};
UVar::operator ufloat() const
{
return (ufloat) value;
};
UVar::operator std::string() const
{
return (std::string) value;
};
UVar::operator UBinary() const
{
return value;
};
UVar::operator UBinary*() const
{
return new UBinary(value.operator UBinary());
};
UVar::operator UImage() const
{
return (UImage) value;
};
UVar::operator USound() const
{
return (USound) value;
};
UVar::operator UList() const
{
return (UList) value;
};
//! UVar update
void
UVar::__update(UValue& v)
{
# ifdef LIBURBIDEBUG
std::cout << " Variable " << name << " updated to : ";
switch (v.type)
{
case DATA_DOUBLE:
std::cout << (double)v << std::endl;
break;
case DATA_STRING:
std::cout << (std::string)v << std::endl;
break;
case DATA_BINARY:
case DATA_LIST:
case DATA_OBJECT:
case DATA_VOID:
break;
}
# endif
value = v;
}
//! set own mode
void
UVar::setOwned()
{
owned = true;
}
//! Get Uvalue type
UDataType
UVar::type() const
{
return value.type;
}
void
UVar::requestValue()
{
//build a getvalue message that will be parsed and returned by the server
URBI_SEND_PIPED_COMMAND(externalModuleTag << "<<"
<<'[' << UEM_ASSIGNVALUE << ","
<< '"' << name << '"' << ',' << name << ']');
}
void
UVar::syncValue()
{
USyncClient& client = dynamic_cast<USyncClient&> (URBI(()));
char tag[32];
client.makeUniqueTag(tag);
UMessage* m =
client.syncGetTag("{"
" if (isdef (%s) && !isvoid (%s))"
" {"
" %s<<%s"
" }"
" else"
" {"
" %s<<1/0"
" }"
"};",
tag, 0, name.c_str(), name.c_str(),
tag, name.c_str(), tag);
if (m->type == MESSAGE_DATA)
__update(*m->value);
}
} //namespace urbi
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007-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.
*/
#ifndef SDK_REMOTE_TESTS_TESTS_HH
# define SDK_REMOTE_TESTS_TESTS_HH
# include <iostream>
# include <libport/debug.hh>
# include <libport/semaphore.hh>
# include <libport/program-name.hh>
# include <libport/unistd.h>
# include <urbi/uclient.hh>
# include <urbi/usyncclient.hh>
using libport::program_name;
/* Liburbi test suite
= Architecture =
Each file corresponds to an 'atomic' test.
Test file layout
- #includes "tests.hh"
- write callbacks, ensure global unique names
- a call to BEGIN_TEST(testname, clientname, syncclientname),
testname must be filename-without-extension
- code of the test:
- setup callbacks, the callback function dump is provided: it displays the
message and increments dumpSem semaphore. Setting a Wildcard or at least
an error callback is recommended.
- c++ code using UClient & client, USyncClient &syncClient made available
- expected output in comments:
//= <expected output>
- a call to END_TEST
<expected output>
<type> <tag> <value>
<type>
D|E|S for data, error, system
*/
/// Register the message category for each file including this header.
GD_CATEGORY(Test);
/// Send S to the Client.
/// Letter: S for synchronous, A for asynchronous.
#define SEND_(Letter, Client, S) \
do { \
if (Client.isConnected()) \
{ \
GD_SINFO(Letter "Snd: " << S); \
Client.send("%s\n", (S)); \
} \
else \
GD_SINFO(#Client " not connected, cannot send: " << S); \
} while (0)
/// Send S to client/syncclient.
#define SEND(S) SEND_("A", client, S)
#define SSEND(S) SEND_("S", syncClient, S)
/*----------.
| SyncGet. |
`----------*/
template <typename T>
inline
T
sget(urbi::USyncClient& c, const std::string& msg)
{
pabort("Do not call me");
}
template <>
inline
std::string
sget<std::string>(urbi::USyncClient& c, const std::string& msg)
{
GD_SINFO("syncGet: Asking " << msg);
std::string res;
urbi::getValue(c.syncGet(msg), res);
return res;
}
template <>
inline
int
sget<int>(urbi::USyncClient& c, const std::string& msg)
{
GD_SINFO("syncGet: Asking " << msg);
int res = 0;
urbi::getValue(c.syncGet(msg), res);
return res;
}
#define SGET(Type, E) \
sget<Type>(syncClient, E)
std::string sget_error(urbi::USyncClient& c, const std::string& msg);
/// Send a computation, expect an error.
#define SGET_ERROR(E) \
sget_error(syncClient, E)
extern libport::Semaphore dumpSem;
/// Display the value.
urbi::UCallbackAction log(const urbi::UMessage& msg);
/// Display the value, increment dumpSem.
urbi::UCallbackAction dump(const urbi::UMessage& msg);
/// Display the value, increment dumpSem remove callback if 0.
urbi::UCallbackAction removeOnZero(const urbi::UMessage& msg);
#define BEGIN_TEST \
void \
test(urbi::UClient& client, \
urbi::USyncClient& syncClient) \
{ \
LIBPORT_USE(client, syncClient);
#define END_TEST \
}
void test(urbi::UClient& client, urbi::USyncClient& syncClient);
#endif // SDK_REMOTE_TESTS_TESTS_HH
<commit_msg>clang: remove warnings.<commit_after>/*
* Copyright (C) 2007-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.
*/
#ifndef SDK_REMOTE_TESTS_TESTS_HH
# define SDK_REMOTE_TESTS_TESTS_HH
# include <iostream>
# include <libport/debug.hh>
# include <libport/semaphore.hh>
# include <libport/program-name.hh>
# include <libport/unistd.h>
# include <urbi/uclient.hh>
# include <urbi/usyncclient.hh>
using libport::program_name;
/* Liburbi test suite
= Architecture =
Each file corresponds to an 'atomic' test.
Test file layout
- #includes "tests.hh"
- write callbacks, ensure global unique names
- a call to BEGIN_TEST(testname, clientname, syncclientname),
testname must be filename-without-extension
- code of the test:
- setup callbacks, the callback function dump is provided: it displays the
message and increments dumpSem semaphore. Setting a Wildcard or at least
an error callback is recommended.
- c++ code using UClient & client, USyncClient &syncClient made available
- expected output in comments:
//= <expected output>
- a call to END_TEST
<expected output>
<type> <tag> <value>
<type>
D|E|S for data, error, system
*/
/// Register the message category for each file including this header.
GD_CATEGORY(Test);
/// Send S to the Client.
/// Letter: S for synchronous, A for asynchronous.
#define SEND_(Letter, Client, S) \
do { \
if (Client.isConnected()) \
{ \
GD_SINFO(Letter "Snd: " << S); \
Client.send("%s\n", (S)); \
} \
else \
GD_SINFO(#Client " not connected, cannot send: " << S); \
} while (0)
/// Send S to client/syncclient.
#define SEND(S) SEND_("A", client, S)
#define SSEND(S) SEND_("S", syncClient, S)
/*----------.
| SyncGet. |
`----------*/
template <typename T>
inline
T
sget(urbi::USyncClient&, const std::string&)
{
pabort("Do not call me");
}
template <>
inline
std::string
sget<std::string>(urbi::USyncClient& c, const std::string& msg)
{
GD_SINFO("syncGet: Asking " << msg);
std::string res;
urbi::getValue(c.syncGet(msg), res);
return res;
}
template <>
inline
int
sget<int>(urbi::USyncClient& c, const std::string& msg)
{
GD_SINFO("syncGet: Asking " << msg);
int res = 0;
urbi::getValue(c.syncGet(msg), res);
return res;
}
#define SGET(Type, E) \
sget<Type>(syncClient, E)
std::string sget_error(urbi::USyncClient& c, const std::string& msg);
/// Send a computation, expect an error.
#define SGET_ERROR(E) \
sget_error(syncClient, E)
extern libport::Semaphore dumpSem;
/// Display the value.
urbi::UCallbackAction log(const urbi::UMessage& msg);
/// Display the value, increment dumpSem.
urbi::UCallbackAction dump(const urbi::UMessage& msg);
/// Display the value, increment dumpSem remove callback if 0.
urbi::UCallbackAction removeOnZero(const urbi::UMessage& msg);
#define BEGIN_TEST \
void \
test(urbi::UClient& client, \
urbi::USyncClient& syncClient) \
{ \
LIBPORT_USE(client, syncClient);
#define END_TEST \
}
void test(urbi::UClient& client, urbi::USyncClient& syncClient);
#endif // SDK_REMOTE_TESTS_TESTS_HH
<|endoftext|> |
<commit_before>#include "pacman_vision/kinect2_processor.h"
#include <array>
Kinect2Processor::Kinect2Processor () : device(0), packetPipeline(0), registration(0),
listener(0), started(false), initialized(false)
{
undistorted = new libfreenect2::Frame(512, 424, 4);
registered = new libfreenect2::Frame(512, 424, 4);
}
bool
Kinect2Processor::initDevice ()
{
if (freenect2.enumerateDevices() <= 0)
{
ROS_ERROR("[Kinect2] No Kinect2 devices found");
return (false);
}
//no support for multiple kinects as of now... just get default one.
std::string serial = freenect2.getDefaultDeviceSerialNumber();
//Use OpenCL Packet pipeline processor
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
if (!packetPipeline)
packetPipeline = new libfreenect2::OpenCLPacketPipeline();
#else
ROS_ERROR("[Kinect2] LibFreenect2 does not have OpenCL support. Please recompile it with OpenCL support");
return (false);
#endif
//Open kinect2
device = freenect2.openDevice(serial, packetPipeline);
if (device == 0)
{
ROS_ERROR("[Kinect2] Failed to open Kinect2 with serial %s", serial.c_str());
return (false);
}
//create the listener
listener = new libfreenect2::SyncMultiFrameListener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth);
//and set them
device->setColorFrameListener(listener);
device->setIrAndDepthFrameListener(listener);
//listen to camera parameters
device->start();
colorParams = device->getColorCameraParams();
irParams = device->getIrCameraParams();
device->stop();
//init registration
registration = new libfreenect2::Registration(irParams, colorParams);
initialized = true;
return (true);
}
void
Kinect2Processor::processData()
{
//assume kinect2 is started and initialized
listener->waitForNewFrame(frames);
colorFrame = frames[libfreenect2::Frame::Color];
// irFrame = frames[libfreenect2::Frame::Ir];
depthFrame = frames[libfreenect2::Frame::Depth];
registration->apply(colorFrame, depthFrame, undistorted, registered);
listener->release(frames);
}
void
Kinect2Processor::computePointCloud(PC::Ptr& out_cloud)
{
std::array<float, 512*424> X,Y,Z,RGB;
//assume registration was performed
out_cloud.reset(new PC);
out_cloud->width = 512;
out_cloud->height = 424;
out_cloud->is_dense = false;
out_cloud->sensor_origin_.setZero();
out_cloud->sensor_orientation_.setIdentity();
out_cloud->points.resize(out_cloud->width * out_cloud->height);
registration->computeCoordinatesAndColor(undistorted, registered, X,Y,Z,RGB);
//todo fill pointcloud
}
<commit_msg>to test process point cloud<commit_after>#include "pacman_vision/kinect2_processor.h"
#include <array>
Kinect2Processor::Kinect2Processor () : device(0), packetPipeline(0), registration(0),
listener(0), started(false), initialized(false)
{
undistorted = new libfreenect2::Frame(512, 424, 4);
registered = new libfreenect2::Frame(512, 424, 4);
}
bool
Kinect2Processor::initDevice ()
{
if (freenect2.enumerateDevices() <= 0)
{
ROS_ERROR("[Kinect2] No Kinect2 devices found");
return (false);
}
//no support for multiple kinects as of now... just get default one.
std::string serial = freenect2.getDefaultDeviceSerialNumber();
//Use OpenCL Packet pipeline processor
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
if (!packetPipeline)
packetPipeline = new libfreenect2::OpenCLPacketPipeline();
#else
ROS_ERROR("[Kinect2] LibFreenect2 does not have OpenCL support. Please recompile it with OpenCL support");
return (false);
#endif
//Open kinect2
device = freenect2.openDevice(serial, packetPipeline);
if (device == 0)
{
ROS_ERROR("[Kinect2] Failed to open Kinect2 with serial %s", serial.c_str());
return (false);
}
//create the listener
listener = new libfreenect2::SyncMultiFrameListener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth);
//and set them
device->setColorFrameListener(listener);
device->setIrAndDepthFrameListener(listener);
//listen to camera parameters
device->start();
colorParams = device->getColorCameraParams();
irParams = device->getIrCameraParams();
device->stop();
//init registration
registration = new libfreenect2::Registration(irParams, colorParams);
initialized = true;
return (true);
}
void
Kinect2Processor::processData()
{
//assume kinect2 is started and initialized
listener->waitForNewFrame(frames);
colorFrame = frames[libfreenect2::Frame::Color];
// irFrame = frames[libfreenect2::Frame::Ir];
depthFrame = frames[libfreenect2::Frame::Depth];
registration->apply(colorFrame, depthFrame, undistorted, registered);
listener->release(frames);
}
void
Kinect2Processor::computePointCloud(PC::Ptr& out_cloud)
{
std::array<float, 512*424> X,Y,Z,RGB;
//assume registration was performed
out_cloud.reset(new PC);
out_cloud->width = 512;
out_cloud->height = 424;
out_cloud->is_dense = false;
out_cloud->sensor_origin_.setZero();
out_cloud->sensor_orientation_.setIdentity();
out_cloud->points.resize(out_cloud->width * out_cloud->height);
registration->computeCoordinatesAndColor(undistorted, registered, X,Y,Z,RGB);
for (size_t i=0; i<out_cloud->points.size(); ++i)
{
out_cloud->points[i].x = X[i];
out_cloud->points[i].y = Y[i];
out_cloud->points[i].z = Z[i];
out_cloud->points[i].rgb = RGB[i];
}
}
<|endoftext|> |
<commit_before>#include "libbbn-ni-r.h"
//global to hold on to session handle
NiFpga_Session session;
bool isOpen = false;
//Initialize FPGA on loading the library -- constructor hook in header
void init() {
NiFpga_Status status = NiFpga_Initialize();
}
//Cleanup NI library -- destructor hook in header
void cleanup(){
if (isOpen) {NiFpga_Close(session, 0);};
NiFpga_Finalize();
}
BBN_NI_R_STATUS open_load_run(){
NiFpga_Status status = NiFpga_Open(NiFpga_SimpleDigitizer_VI_Bitfile,
NiFpga_SimpleDigitizer_VI_Signature,
"RIO0", 0, &session);
if (status == NiFpga_Status_Success){
isOpen = true;
}
return status;
}
BBN_NI_R_STATUS set_numSamples(unsigned numSamples){
return 0;
};
BBN_NI_R_STATUS get_numSamples(unsigned* numSamples){
return 0;
};
BBN_NI_R_STATUS set_sampleInterval(unsigned sampleInterval){
return 0;
};
BBN_NI_R_STATUS get_sampleInterval(unsigned* sampleInterval){
return 0;
};
<commit_msg>Fix relative location of bitfile<commit_after>#include "libbbn-ni-r.h"
//global to hold on to session handle
NiFpga_Session session;
bool isOpen = false;
//Initialize FPGA on loading the library -- constructor hook in header
void init() {
NiFpga_Status status = NiFpga_Initialize();
}
//Cleanup NI library -- destructor hook in header
void cleanup(){
if (isOpen) {NiFpga_Close(session, 0);};
NiFpga_Finalize();
}
BBN_NI_R_STATUS open_load_run(){
NiFpga_Status status = NiFpga_Open("../" NiFpga_SimpleDigitizer_VI_Bitfile,
NiFpga_SimpleDigitizer_VI_Signature,
"RIO0", 0, &session);
if (status == NiFpga_Status_Success){
isOpen = true;
}
return status;
}
BBN_NI_R_STATUS set_numSamples(unsigned numSamples){
return 0;
};
BBN_NI_R_STATUS get_numSamples(unsigned* numSamples){
return 0;
};
BBN_NI_R_STATUS set_sampleInterval(unsigned sampleInterval){
return 0;
};
BBN_NI_R_STATUS get_sampleInterval(unsigned* sampleInterval){
return 0;
};
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009, 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.
*/
#include <libport/asio.hh>
namespace libport
{
void
runIoService(boost::asio::io_service* io)
{
while (true)
{
// Used so that io->run() never returns.
boost::asio::io_service::work work(*io);
io->run();
std::cerr << "The impossible happened" << std::endl;
io->reset();
}
}
static pthread_t asio_worker_thread;
boost::asio::io_service&
get_io_service(bool startWorkerThread)
{
static boost::asio::io_service* io = 0;
static bool hasWorkerThread = false;
if (!startWorkerThread && hasWorkerThread)
{
std::cerr <<"fatal, worker thread allready running" << std::endl;
abort();
}
if (!io)
{
io = new boost::asio::io_service;
if (startWorkerThread)
{
hasWorkerThread = true;
asio_worker_thread =
libport::startThread(boost::bind(&runIoService, io));
}
else
asio_worker_thread = pthread_self();
}
return *io;
}
#if ! defined WIN32
int
Socket::stealFD()
{
if (base_)
return base_->stealFD();
else
return -1;
}
int
Socket::getFD()
{
if (base_)
return base_->getFD();
else
return -1;
}
#endif
void
Socket::destroy()
{
// Lock in case the user calls destroy() in its error handler.
Destructible::DestructionLock l = getDestructionLock();
// It is safe to reach that point with an open socket.
close();
AsioDestructible::destroy();
}
Socket::~Socket()
{
/* FIXME: ensure no false positive before activating
if (!checkDestructionPermission())
std::cerr <<"WARNING, attempting to delete a Socket that is still in use."
<< "\n\tThis is likely a bug if you overrided onRead or onError"
<< "\n\tSee Socket documentation for more informations."
<< std::endl;
*/
wasDestroyed();
if (base_)
{
Destructible::DestructionLock l = base_->getDestructionLock();
base_->close();
base_->destroy();
BlockLock bl(base_->callbackLock);
base_->onReadFunc = 0;
base_->onErrorFunc = 0;
base_ = 0;
}
// FIXME: optimize
while (!checkDestructionPermission())
{
sleep(100);
}
//waitForDestructionPermission();
}
Socket::Handle
Socket::listenUDP(const std::string& host,
const std::string& port,
netdetail::UDPSocket::onread_type onRead,
boost::system::error_code& erc)
{
using namespace boost::asio::ip;
netdetail::UDPSocket* s = new netdetail::UDPSocket();
s->onRead = onRead;
/* On some configurations, the resolver will resolve an ipv6 address even
* if this protocol is not supported by the system. So try to bind using all
* the endopints until one succeeds, and not just the first. */
udp::resolver::query query(host, port);
udp::resolver resolver(libport::get_io_service());
udp::resolver::iterator iter = resolver.resolve(query, erc);
if (erc)
return Handle();
// Careful to use the protocol reported by the endpoint.
while (iter != udp::resolver::iterator())
{
s->socket_.open(iter->endpoint().protocol(), erc);
if (!erc)
s->socket_.bind(iter->endpoint(), erc);
if (!erc)
goto ok;
iter++;
}
if (!erc)
erc =
netdetail::errorcodes::make_error_code(
netdetail::errorcodes::bad_address);
return Handle();
ok:
s->start_receive();
return Handle();
}
void
Socket::setBase(BaseSocket* b)
{
base_ = b;
BlockLock bl(base_->callbackLock);
base_-> onReadFunc = boost::bind(&Socket::onRead_, this, _1);
base_->onErrorFunc = boost::bind(&Socket::onError, this, _1);
}
bool
Socket::onRead_(boost::asio::streambuf& buf)
{
DestructionLock lock = getDestructionLock();
// Dump the stream in our linear buffer
std::istream is(&buf);
static const int blockSize = 1024;
while (is.good())
{
size_t oldBufferLength = buffer.length();
buffer.resize(oldBufferLength + blockSize);
is.read(&buffer[0] + oldBufferLength, blockSize);
long len = is.gcount();
buffer.resize(oldBufferLength + len);
}
// Call onRead until it eats 0 characters.
size_t r;
do
{
r = onRead(buffer.c_str(), buffer.length());
if (r)
buffer = buffer.substr(r, buffer.npos);
}
while(r && !buffer.empty());
return true;
}
void
Socket::sleep(useconds_t duration)
{
//FIXME: implement for real
if (isPollThread())
pollFor(duration);
else
usleep(duration);
}
static void stop_io_service(boost::asio::io_service& io)
{
io.stop();
}
void pollFor(useconds_t duration, bool once, boost::asio::io_service& io)
{
boost::asio::io_service::work work(io);
io.reset();
AsyncCallHandler asc =
asyncCall(boost::bind(&stop_io_service, boost::ref(io)), duration, io);
if (once)
io.run_one();
else
io.run();
}
bool isPollThread()
{
return pthread_self() == asio_worker_thread;
}
# if BOOST_VERSION >= 103600
boost::system::error_code
Socket::open_serial(const std::string& device,
unsigned int rate)
{
boost::system::error_code erc;
Rs232& sp = *new Rs232(get_io_service());
sp.open(device, erc);
sp.set_option(boost::asio::serial_port::baud_rate(rate), erc);
typedef libport::netdetail::SocketImpl<Rs232> SerBase;
SerBase* sb = (SerBase*)SerBase::create(&sp);
this->setBase(sb);
sb->startReader();
return erc;
}
# endif
}
<commit_msg>asio: Correct two bugs in open_serial.<commit_after>/*
* Copyright (C) 2009, 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.
*/
#include <libport/asio.hh>
namespace libport
{
void
runIoService(boost::asio::io_service* io)
{
while (true)
{
// Used so that io->run() never returns.
boost::asio::io_service::work work(*io);
io->run();
std::cerr << "The impossible happened" << std::endl;
io->reset();
}
}
static pthread_t asio_worker_thread;
boost::asio::io_service&
get_io_service(bool startWorkerThread)
{
static boost::asio::io_service* io = 0;
static bool hasWorkerThread = false;
if (!startWorkerThread && hasWorkerThread)
{
std::cerr <<"fatal, worker thread allready running" << std::endl;
abort();
}
if (!io)
{
io = new boost::asio::io_service;
if (startWorkerThread)
{
hasWorkerThread = true;
asio_worker_thread =
libport::startThread(boost::bind(&runIoService, io));
}
else
asio_worker_thread = pthread_self();
}
return *io;
}
#if ! defined WIN32
int
Socket::stealFD()
{
if (base_)
return base_->stealFD();
else
return -1;
}
int
Socket::getFD()
{
if (base_)
return base_->getFD();
else
return -1;
}
#endif
void
Socket::destroy()
{
// Lock in case the user calls destroy() in its error handler.
Destructible::DestructionLock l = getDestructionLock();
// It is safe to reach that point with an open socket.
close();
AsioDestructible::destroy();
}
Socket::~Socket()
{
/* FIXME: ensure no false positive before activating
if (!checkDestructionPermission())
std::cerr <<"WARNING, attempting to delete a Socket that is still in use."
<< "\n\tThis is likely a bug if you overrided onRead or onError"
<< "\n\tSee Socket documentation for more informations."
<< std::endl;
*/
wasDestroyed();
if (base_)
{
Destructible::DestructionLock l = base_->getDestructionLock();
base_->close();
base_->destroy();
BlockLock bl(base_->callbackLock);
base_->onReadFunc = 0;
base_->onErrorFunc = 0;
base_ = 0;
}
// FIXME: optimize
while (!checkDestructionPermission())
{
sleep(100);
}
//waitForDestructionPermission();
}
Socket::Handle
Socket::listenUDP(const std::string& host,
const std::string& port,
netdetail::UDPSocket::onread_type onRead,
boost::system::error_code& erc)
{
using namespace boost::asio::ip;
netdetail::UDPSocket* s = new netdetail::UDPSocket();
s->onRead = onRead;
/* On some configurations, the resolver will resolve an ipv6 address even
* if this protocol is not supported by the system. So try to bind using all
* the endopints until one succeeds, and not just the first. */
udp::resolver::query query(host, port);
udp::resolver resolver(libport::get_io_service());
udp::resolver::iterator iter = resolver.resolve(query, erc);
if (erc)
return Handle();
// Careful to use the protocol reported by the endpoint.
while (iter != udp::resolver::iterator())
{
s->socket_.open(iter->endpoint().protocol(), erc);
if (!erc)
s->socket_.bind(iter->endpoint(), erc);
if (!erc)
goto ok;
iter++;
}
if (!erc)
erc =
netdetail::errorcodes::make_error_code(
netdetail::errorcodes::bad_address);
return Handle();
ok:
s->start_receive();
return Handle();
}
void
Socket::setBase(BaseSocket* b)
{
base_ = b;
BlockLock bl(base_->callbackLock);
base_-> onReadFunc = boost::bind(&Socket::onRead_, this, _1);
base_->onErrorFunc = boost::bind(&Socket::onError, this, _1);
}
bool
Socket::onRead_(boost::asio::streambuf& buf)
{
DestructionLock lock = getDestructionLock();
// Dump the stream in our linear buffer
std::istream is(&buf);
static const int blockSize = 1024;
while (is.good())
{
size_t oldBufferLength = buffer.length();
buffer.resize(oldBufferLength + blockSize);
is.read(&buffer[0] + oldBufferLength, blockSize);
long len = is.gcount();
buffer.resize(oldBufferLength + len);
}
// Call onRead until it eats 0 characters.
size_t r;
do
{
r = onRead(buffer.c_str(), buffer.length());
if (r)
buffer = buffer.substr(r, buffer.npos);
}
while(r && !buffer.empty());
return true;
}
void
Socket::sleep(useconds_t duration)
{
//FIXME: implement for real
if (isPollThread())
pollFor(duration);
else
usleep(duration);
}
static void stop_io_service(boost::asio::io_service& io)
{
io.stop();
}
void pollFor(useconds_t duration, bool once, boost::asio::io_service& io)
{
boost::asio::io_service::work work(io);
io.reset();
AsyncCallHandler asc =
asyncCall(boost::bind(&stop_io_service, boost::ref(io)), duration, io);
if (once)
io.run_one();
else
io.run();
}
bool isPollThread()
{
return pthread_self() == asio_worker_thread;
}
# if BOOST_VERSION >= 103600
boost::system::error_code
Socket::open_serial(const std::string& device,
unsigned int rate)
{
boost::system::error_code erc;
Rs232& sp = *new Rs232(get_io_service());
sp.open(device, erc);
if (erc)
return erc;
sp.set_option(boost::asio::serial_port::baud_rate(rate), erc);
if (erc)
return erc;
typedef libport::netdetail::SocketImpl<Rs232> SerBase;
SerBase* sb = (SerBase*)SerBase::create(&sp);
this->setBase(sb);
sb->startReader();
onConnect();
return erc;
}
# endif
}
<|endoftext|> |
<commit_before>// HW-4-4-8 Data Statistics - Patrick Kubiak - 6/3/2015
// Reading floating point-values and display average, smallest, largest, and range of the dataset.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main()
{
const int OUTPUT_WIDTH = 12;
double num, total = 0, smallest, largest;
int count = 0;
smallest = numeric_limits<double>::max(); // set smallest to the largest possible double
largest = -numeric_limits<double>::max(); // set largest to the smallest possible double
// welcome
cout << "Data Statistics" << endl;
cout << "Enter Values (NAN to stop): ";
while (cin >> num)
{
count++; // increment number of values
total += num; // update total
if (count < 1 || num < smallest) // first value or smallest
{
smallest = num;
}
else if (count < 1 || num > largest) // first value or largest
{
largest = num;
}
cout << "Enter Values (NAN to stop): ";
}
// analysis of data
double average = total / count;
double range = largest - smallest;
setprecision(5);
cout << "Analysis of Data" << endl;
cout << setw(OUTPUT_WIDTH) << "Average: " << average << endl;
cout << setw(OUTPUT_WIDTH) << "Smallest: " << smallest << endl;
cout << setw(OUTPUT_WIDTH) << "Largest: " << largest << endl;
cout << setw(OUTPUT_WIDTH) << "Range: " << range << endl;
system("pause");
return 0;
}
<commit_msg>uses relative smallest and largest<commit_after>// HW-4-4-8 Data Statistics - Patrick Kubiak - 6/3/2015
// Reading floating point-values and display average, smallest, largest, and range of the dataset.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int OUTPUT_WIDTH = 12;
double num, total = 0, smallest, largest;
int count = 0;
// welcome
cout << "Data Statistics" << endl;
cout << "Enter Values (NAN to stop): ";
while (cin >> num)
{
count++; // increment number of values
total += num; // update total
if (count == 1) // first value is both smallest and largest
{
smallest = num;
largest = num;
}
if (count > 1)
{
if (num < smallest) // num is new smallest
{
smallest = num;
}
else if (num > largest) // num is new largest
{
largest = num;
}
}
cout << "Enter Values (NAN to stop): ";
}
// analysis of data
double average = total / count;
double range = largest - smallest;
setprecision(5);
cout << "Analysis of Data" << endl;
cout << setw(OUTPUT_WIDTH) << "Average: " << average << endl;
cout << setw(OUTPUT_WIDTH) << "Smallest: " << smallest << endl;
cout << setw(OUTPUT_WIDTH) << "Largest: " << largest << endl;
cout << setw(OUTPUT_WIDTH) << "Range: " << range << endl;
system("pause");
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>直接交换两变量值的例子<commit_after><|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <malloc.h>
#include "../MemoryModule.h"
typedef int (*addNumberProc)(int, int);
BOOL LoadFromMemory(char *filename)
{
FILE *fp;
unsigned char *data=NULL;
size_t size;
HMEMORYMODULE handle;
addNumberProc addNumber;
addNumberProc addNumber2;
HMEMORYRSRC resourceInfo;
DWORD resourceSize;
LPVOID resourceData;
TCHAR buffer[100];
BOOL result = TRUE;
fp = fopen(filename, "rb");
if (fp == NULL)
{
printf("Can't open DLL file \"%s\".", filename);
result = FALSE;
goto exit;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
data = (unsigned char *)malloc(size);
fseek(fp, 0, SEEK_SET);
fread(data, 1, size, fp);
fclose(fp);
handle = MemoryLoadLibrary(data);
if (handle == NULL)
{
_tprintf(_T("Can't load library from memory.\n"));
result = FALSE;
goto exit;
}
addNumber = (addNumberProc)MemoryGetProcAddress(handle, NULL);
if (addNumber != NULL) {
_tprintf(_T("MemoryGetProcAddress(NULL) returned %p\n"), addNumber);
result = FALSE;
goto exit;
}
addNumber = (addNumberProc)MemoryGetProcAddress(handle, reinterpret_cast<LPCTSTR>(0xff));
if (addNumber != NULL) {
_tprintf(_T("MemoryGetProcAddress(0xff) returned %p\n"), addNumber);
result = FALSE;
goto exit;
}
addNumber = (addNumberProc)MemoryGetProcAddress(handle, "addNumbers");
_tprintf(_T("From memory: %d\n"), addNumber(1, 2));
// the DLL only exports one function, try to load by ordinal value
addNumber2 = (addNumberProc)MemoryGetProcAddress(handle, reinterpret_cast<LPCTSTR>(0x01));
if (addNumber != addNumber2) {
_tprintf(_T("MemoryGetProcAddress(0x01) returned %p (expected %p)\n"), addNumber2, addNumber);
result = FALSE;
goto exit;
}
resourceInfo = MemoryFindResource(handle, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION);
_tprintf(_T("MemoryFindResource returned 0x%p\n"), resourceInfo);
if (resourceInfo != NULL) {
resourceSize = MemorySizeofResource(handle, resourceInfo);
resourceData = MemoryLoadResource(handle, resourceInfo);
_tprintf(_T("Memory resource data: %ld bytes at 0x%p\n"), resourceSize, resourceData);
MemoryLoadString(handle, 1, buffer, sizeof(buffer));
_tprintf(_T("String1: %s\n"), buffer);
MemoryLoadString(handle, 20, buffer, sizeof(buffer));
_tprintf(_T("String2: %s\n"), buffer);
} else {
result = FALSE;
}
MemoryFreeLibrary(handle);
exit:
if (data)
free(data);
return result;
}
int main(int argc, char* argv[])
{
if (argc < 2) {
fprintf(stderr, "USAGE: %s <filename.dll>\n", argv[0]);
return 1;
}
if (!LoadFromMemory(argv[1])) {
return 2;
}
return 0;
}
<commit_msg>Fix compilation of tests with UNICODE defined.<commit_after>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <malloc.h>
#include "../MemoryModule.h"
typedef int (*addNumberProc)(int, int);
BOOL LoadFromMemory(char *filename)
{
FILE *fp;
unsigned char *data=NULL;
size_t size;
HMEMORYMODULE handle;
addNumberProc addNumber;
addNumberProc addNumber2;
HMEMORYRSRC resourceInfo;
DWORD resourceSize;
LPVOID resourceData;
TCHAR buffer[100];
BOOL result = TRUE;
fp = fopen(filename, "rb");
if (fp == NULL)
{
printf("Can't open DLL file \"%s\".", filename);
result = FALSE;
goto exit;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
data = (unsigned char *)malloc(size);
fseek(fp, 0, SEEK_SET);
fread(data, 1, size, fp);
fclose(fp);
handle = MemoryLoadLibrary(data);
if (handle == NULL)
{
_tprintf(_T("Can't load library from memory.\n"));
result = FALSE;
goto exit;
}
addNumber = (addNumberProc)MemoryGetProcAddress(handle, NULL);
if (addNumber != NULL) {
_tprintf(_T("MemoryGetProcAddress(NULL) returned %p\n"), addNumber);
result = FALSE;
goto exit;
}
addNumber = (addNumberProc)MemoryGetProcAddress(handle, reinterpret_cast<LPCSTR>(0xff));
if (addNumber != NULL) {
_tprintf(_T("MemoryGetProcAddress(0xff) returned %p\n"), addNumber);
result = FALSE;
goto exit;
}
addNumber = (addNumberProc)MemoryGetProcAddress(handle, "addNumbers");
_tprintf(_T("From memory: %d\n"), addNumber(1, 2));
// the DLL only exports one function, try to load by ordinal value
addNumber2 = (addNumberProc)MemoryGetProcAddress(handle, reinterpret_cast<LPCSTR>(0x01));
if (addNumber != addNumber2) {
_tprintf(_T("MemoryGetProcAddress(0x01) returned %p (expected %p)\n"), addNumber2, addNumber);
result = FALSE;
goto exit;
}
resourceInfo = MemoryFindResource(handle, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION);
_tprintf(_T("MemoryFindResource returned 0x%p\n"), resourceInfo);
if (resourceInfo != NULL) {
resourceSize = MemorySizeofResource(handle, resourceInfo);
resourceData = MemoryLoadResource(handle, resourceInfo);
_tprintf(_T("Memory resource data: %ld bytes at 0x%p\n"), resourceSize, resourceData);
MemoryLoadString(handle, 1, buffer, sizeof(buffer));
_tprintf(_T("String1: %s\n"), buffer);
MemoryLoadString(handle, 20, buffer, sizeof(buffer));
_tprintf(_T("String2: %s\n"), buffer);
} else {
result = FALSE;
}
MemoryFreeLibrary(handle);
exit:
if (data)
free(data);
return result;
}
int main(int argc, char* argv[])
{
if (argc < 2) {
fprintf(stderr, "USAGE: %s <filename.dll>\n", argv[0]);
return 1;
}
if (!LoadFromMemory(argv[1])) {
return 2;
}
return 0;
}
<|endoftext|> |
<commit_before>//
// CRT.hpp
// Clock Signal
//
// Created by Thomas Harte on 19/07/2015.
// Copyright © 2015 Thomas Harte. All rights reserved.
//
#ifndef CRT_hpp
#define CRT_hpp
#include <stdint.h>
#include "CRTTypes.hpp"
#include "Internals/Flywheel.hpp"
#include "Internals/CRTOpenGL.hpp"
#include "Internals/ArrayBuilder.hpp"
#include "Internals/TextureBuilder.hpp"
namespace Outputs {
namespace CRT {
class CRT;
class Delegate {
public:
virtual void crt_did_end_batch_of_frames(CRT *crt, unsigned int number_of_frames, unsigned int number_of_unexpected_vertical_syncs) = 0;
};
class CRT {
private:
CRT(unsigned int common_output_divisor, unsigned int buffer_depth);
// the incoming clock lengths will be multiplied by something to give at least 1000
// sample points per line
unsigned int time_multiplier_;
const unsigned int common_output_divisor_;
// the two flywheels regulating scanning
std::unique_ptr<Flywheel> horizontal_flywheel_, vertical_flywheel_;
uint16_t vertical_flywheel_output_divider_;
// elements of sync separation
bool is_receiving_sync_; // true if the CRT is currently receiving sync (i.e. this is for edge triggering of horizontal sync)
int sync_capacitor_charge_level_; // this charges up during times of sync and depletes otherwise; needs to hit a required threshold to trigger a vertical sync
int sync_capacitor_charge_threshold_; // this charges up during times of sync and depletes otherwise; needs to hit a required threshold to trigger a vertical sync
unsigned int sync_period_;
struct Scan {
enum Type {
Sync, Level, Data, Blank, ColourBurst
} type;
unsigned int number_of_cycles;
union {
struct {
uint8_t phase, amplitude;
};
};
};
void output_scan(const Scan *scan);
uint8_t colour_burst_phase_, colour_burst_amplitude_;
bool is_writing_composite_run_;
unsigned int phase_denominator_, phase_numerator_, colour_cycle_numerator_;
bool is_alernate_line_, phase_alternates_;
// the outer entry point for dispatching output_sync, output_blank, output_level and output_data
void advance_cycles(unsigned int number_of_cycles, bool hsync_requested, bool vsync_requested, const bool vsync_charging, const Scan::Type type);
// the inner entry point that determines whether and when the next sync event will occur within
// the current output window
Flywheel::SyncEvent get_next_vertical_sync_event(bool vsync_is_requested, unsigned int cycles_to_run_for, unsigned int *cycles_advanced);
Flywheel::SyncEvent get_next_horizontal_sync_event(bool hsync_is_requested, unsigned int cycles_to_run_for, unsigned int *cycles_advanced);
// OpenGL state
OpenGLOutputBuilder openGL_output_builder_;
// temporary storage used during the construction of output runs
struct {
uint16_t x1, y;
} output_run_;
// The delegate
Delegate *delegate_;
unsigned int frames_since_last_delegate_call_;
public:
/*! Constructs the CRT with a specified clock rate, height and colour subcarrier frequency.
The requested number of buffers, each with the requested number of bytes per pixel,
is created for the machine to write raw pixel data to.
@param cycles_per_line The clock rate at which this CRT will be driven, specified as the number
of cycles expected to take up one whole scanline of the display.
@param common_output_divisor The greatest a priori common divisor of all cycle counts that will be
supplied to @c output_sync, @c output_data, etc; supply 1 if no greater divisor is known. For many
machines output will run at a fixed multiple of the clock rate; knowing this divisor can improve
internal precision.
@param height_of_display The number of lines that nominally form one field of the display, rounded
up to the next whole integer.
@param colour_cycle_numerator Specifies the numerator for the per-line frequency of the colour subcarrier.
@param colour_cycle_denominator Specifies the denominator for the per-line frequency of the colour subcarrier.
The colour subcarrier is taken to have colour_cycle_numerator/colour_cycle_denominator cycles per line.
@param buffer_depth The depth per pixel of source data buffers to create for this machine. Machines
may provide per-clock-cycle data in the depth that they consider convenient, supplying a sampling
function to convert between their data format and either a composite or RGB signal, allowing that
work to be offloaded onto the GPU and allowing the output signal to be sampled at a rate appropriate
to the display size.
@see @c set_rgb_sampling_function , @c set_composite_sampling_function
*/
CRT(unsigned int cycles_per_line, unsigned int common_output_divisor, unsigned int height_of_display, ColourSpace colour_space, unsigned int colour_cycle_numerator, unsigned int colour_cycle_denominator, bool should_alternate, unsigned int buffer_depth);
/*! Constructs the CRT with the specified clock rate, with the display height and colour
subcarrier frequency dictated by a standard display type and with the requested number of
buffers, each with the requested number of bytes per pixel.
Exactly identical to calling the designated constructor with colour subcarrier information
looked up by display type.
*/
CRT(unsigned int cycles_per_line, unsigned int common_output_divisor, DisplayType displayType, unsigned int buffer_depth);
/*! Resets the CRT with new timing information. The CRT then continues as though the new timing had
been provided at construction. */
void set_new_timing(unsigned int cycles_per_line, unsigned int height_of_display, ColourSpace colour_space, unsigned int colour_cycle_numerator, unsigned int colour_cycle_denominator, bool should_alternate);
/*! Resets the CRT with new timing information derived from a new display type. The CRT then continues
as though the new timing had been provided at construction. */
void set_new_display_type(unsigned int cycles_per_line, DisplayType displayType);
/*! Output at the sync level.
@param number_of_cycles The amount of time to putput sync for.
*/
void output_sync(unsigned int number_of_cycles);
/*! Output at the blanking level.
@param number_of_cycles The amount of time to putput the blanking level for.
*/
void output_blank(unsigned int number_of_cycles);
/*! Outputs the first written to the most-recently created run of data repeatedly for a prolonged period.
@param number_of_cycles The number of cycles to repeat the output for.
*/
void output_level(unsigned int number_of_cycles);
/*! Declares that the caller has created a run of data via @c allocate_write_area and @c get_write_target_for_buffer
that is at least @c number_of_cycles long, and that the first @c number_of_cycles/source_divider should be spread
over that amount of time.
@param number_of_cycles The amount of data to output.
@param source_divider A divider for source data; if the divider is 1 then one source pixel is output every cycle,
if it is 2 then one source pixel covers two cycles; if it is n then one source pixel covers n cycles.
@see @c allocate_write_area , @c get_write_target_for_buffer
*/
void output_data(unsigned int number_of_cycles, unsigned int source_divider);
/*! Outputs a colour burst.
@param number_of_cycles The length of the colour burst.
@param phase The initial phase of the colour burst in a measuring system with 256 units
per circle, e.g. 0 = 0 degrees, 128 = 180 degrees, 256 = 360 degree.
@param amplitude The amplitude of the colour burst in 1/256ths of the amplitude of the
positive portion of the wave.
*/
void output_colour_burst(unsigned int number_of_cycles, uint8_t phase, uint8_t amplitude);
/*! Outputs a colour burst exactly in phase with CRT expectations using the idiomatic amplitude.
@param number_of_cycles The length of the colour burst;
*/
void output_default_colour_burst(unsigned int number_of_cycles);
/*! Attempts to allocate the given number of output samples for writing.
The beginning of the most recently allocated area is used as the start
of data written by a call to @c output_data; it is acceptable to write and to
output less data than the amount requested but that may be less efficient.
Allocation should fail only if emulation is running significantly below real speed.
@param required_length The number of samples to allocate.
@returns A pointer to the allocated area if room is available; @c nullptr otherwise.
*/
inline uint8_t *allocate_write_area(size_t required_length)
{
std::unique_lock<std::mutex> output_lock = openGL_output_builder_.get_output_lock();
return openGL_output_builder_.texture_builder.allocate_write_area(required_length);
}
/*! Causes appropriate OpenGL or OpenGL ES calls to be issued in order to draw the current CRT state.
The caller is responsible for ensuring that a valid OpenGL context exists for the duration of this call.
*/
inline void draw_frame(unsigned int output_width, unsigned int output_height, bool only_if_dirty)
{
openGL_output_builder_.draw_frame(output_width, output_height, only_if_dirty);
}
/*! Tells the CRT that the next call to draw_frame will occur on a different OpenGL context than
the previous.
@param should_delete_resources If @c true then all resources — textures, vertex arrays, etc —
currently held by the CRT will be deleted now via calls to glDeleteTexture and equivalent. If
@c false then the references are simply marked as invalid.
*/
inline void set_openGL_context_will_change(bool should_delete_resources)
{
openGL_output_builder_.set_openGL_context_will_change(should_delete_resources);
}
/*! Sets a function that will map from whatever data the machine provided to a composite signal.
@param shader A GLSL fragment including a function with the signature
`float composite_sample(usampler2D texID, vec2 coordinate, vec2 iCoordinate, float phase, float amplitude)`
that evaluates to the composite signal level as a function of a source buffer, sampling location, colour
carrier phase and amplitude.
*/
inline void set_composite_sampling_function(const char *shader)
{
openGL_output_builder_.set_composite_sampling_function(shader);
}
/*! Sets a function that will map from whatever data the machine provided to an RGB signal.
If the output mode is composite then a default mapping from RGB to the display's composite
format will be applied.
@param shader A GLSL fragent including a function with the signature
`vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)` that evaluates to an RGB colour
as a function of:
* `usampler2D sampler` representing the source buffer;
* `vec2 coordinate` representing the source buffer location to sample from in the range [0, 1); and
* `vec2 icoordinate` representing the source buffer location to sample from as a pixel count, for easier multiple-pixels-per-byte unpacking.
*/
inline void set_rgb_sampling_function(const char *shader)
{
openGL_output_builder_.set_rgb_sampling_function(shader);
}
inline void set_output_device(OutputDevice output_device)
{
openGL_output_builder_.set_output_device(output_device);
}
inline void set_visible_area(Rect visible_area)
{
openGL_output_builder_.set_visible_area(visible_area);
}
Rect get_rect_for_area(int first_line_after_sync, int number_of_lines, int first_cycle_after_sync, int number_of_cycles, float aspect_ratio);
inline void set_delegate(Delegate *delegate)
{
delegate_ = delegate;
}
};
}
}
#endif /* CRT_cpp */
<commit_msg>Introduced a deferred task list for the OpenGL thread.<commit_after>//
// CRT.hpp
// Clock Signal
//
// Created by Thomas Harte on 19/07/2015.
// Copyright © 2015 Thomas Harte. All rights reserved.
//
#ifndef CRT_hpp
#define CRT_hpp
#include <stdint.h>
#include "CRTTypes.hpp"
#include "Internals/Flywheel.hpp"
#include "Internals/CRTOpenGL.hpp"
#include "Internals/ArrayBuilder.hpp"
#include "Internals/TextureBuilder.hpp"
namespace Outputs {
namespace CRT {
class CRT;
class Delegate {
public:
virtual void crt_did_end_batch_of_frames(CRT *crt, unsigned int number_of_frames, unsigned int number_of_unexpected_vertical_syncs) = 0;
};
class CRT {
private:
CRT(unsigned int common_output_divisor, unsigned int buffer_depth);
// the incoming clock lengths will be multiplied by something to give at least 1000
// sample points per line
unsigned int time_multiplier_;
const unsigned int common_output_divisor_;
// the two flywheels regulating scanning
std::unique_ptr<Flywheel> horizontal_flywheel_, vertical_flywheel_;
uint16_t vertical_flywheel_output_divider_;
// elements of sync separation
bool is_receiving_sync_; // true if the CRT is currently receiving sync (i.e. this is for edge triggering of horizontal sync)
int sync_capacitor_charge_level_; // this charges up during times of sync and depletes otherwise; needs to hit a required threshold to trigger a vertical sync
int sync_capacitor_charge_threshold_; // this charges up during times of sync and depletes otherwise; needs to hit a required threshold to trigger a vertical sync
unsigned int sync_period_;
struct Scan {
enum Type {
Sync, Level, Data, Blank, ColourBurst
} type;
unsigned int number_of_cycles;
union {
struct {
uint8_t phase, amplitude;
};
};
};
void output_scan(const Scan *scan);
uint8_t colour_burst_phase_, colour_burst_amplitude_;
bool is_writing_composite_run_;
unsigned int phase_denominator_, phase_numerator_, colour_cycle_numerator_;
bool is_alernate_line_, phase_alternates_;
// the outer entry point for dispatching output_sync, output_blank, output_level and output_data
void advance_cycles(unsigned int number_of_cycles, bool hsync_requested, bool vsync_requested, const bool vsync_charging, const Scan::Type type);
// the inner entry point that determines whether and when the next sync event will occur within
// the current output window
Flywheel::SyncEvent get_next_vertical_sync_event(bool vsync_is_requested, unsigned int cycles_to_run_for, unsigned int *cycles_advanced);
Flywheel::SyncEvent get_next_horizontal_sync_event(bool hsync_is_requested, unsigned int cycles_to_run_for, unsigned int *cycles_advanced);
// OpenGL state
OpenGLOutputBuilder openGL_output_builder_;
// temporary storage used during the construction of output runs
struct {
uint16_t x1, y;
} output_run_;
// the delegate
Delegate *delegate_;
unsigned int frames_since_last_delegate_call_;
// queued tasks for the OpenGL queue; performed before the next draw
std::mutex function_mutex_;
std::vector<std::function<void(void)>> enqueued_openGL_functions_;
inline void enqueue_openGL_function(const std::function<void(void)> &function)
{
std::lock_guard<std::mutex> function_guard(function_mutex_);
enqueued_openGL_functions_.push_back(function);
}
public:
/*! Constructs the CRT with a specified clock rate, height and colour subcarrier frequency.
The requested number of buffers, each with the requested number of bytes per pixel,
is created for the machine to write raw pixel data to.
@param cycles_per_line The clock rate at which this CRT will be driven, specified as the number
of cycles expected to take up one whole scanline of the display.
@param common_output_divisor The greatest a priori common divisor of all cycle counts that will be
supplied to @c output_sync, @c output_data, etc; supply 1 if no greater divisor is known. For many
machines output will run at a fixed multiple of the clock rate; knowing this divisor can improve
internal precision.
@param height_of_display The number of lines that nominally form one field of the display, rounded
up to the next whole integer.
@param colour_cycle_numerator Specifies the numerator for the per-line frequency of the colour subcarrier.
@param colour_cycle_denominator Specifies the denominator for the per-line frequency of the colour subcarrier.
The colour subcarrier is taken to have colour_cycle_numerator/colour_cycle_denominator cycles per line.
@param buffer_depth The depth per pixel of source data buffers to create for this machine. Machines
may provide per-clock-cycle data in the depth that they consider convenient, supplying a sampling
function to convert between their data format and either a composite or RGB signal, allowing that
work to be offloaded onto the GPU and allowing the output signal to be sampled at a rate appropriate
to the display size.
@see @c set_rgb_sampling_function , @c set_composite_sampling_function
*/
CRT(unsigned int cycles_per_line, unsigned int common_output_divisor, unsigned int height_of_display, ColourSpace colour_space, unsigned int colour_cycle_numerator, unsigned int colour_cycle_denominator, bool should_alternate, unsigned int buffer_depth);
/*! Constructs the CRT with the specified clock rate, with the display height and colour
subcarrier frequency dictated by a standard display type and with the requested number of
buffers, each with the requested number of bytes per pixel.
Exactly identical to calling the designated constructor with colour subcarrier information
looked up by display type.
*/
CRT(unsigned int cycles_per_line, unsigned int common_output_divisor, DisplayType displayType, unsigned int buffer_depth);
/*! Resets the CRT with new timing information. The CRT then continues as though the new timing had
been provided at construction. */
void set_new_timing(unsigned int cycles_per_line, unsigned int height_of_display, ColourSpace colour_space, unsigned int colour_cycle_numerator, unsigned int colour_cycle_denominator, bool should_alternate);
/*! Resets the CRT with new timing information derived from a new display type. The CRT then continues
as though the new timing had been provided at construction. */
void set_new_display_type(unsigned int cycles_per_line, DisplayType displayType);
/*! Output at the sync level.
@param number_of_cycles The amount of time to putput sync for.
*/
void output_sync(unsigned int number_of_cycles);
/*! Output at the blanking level.
@param number_of_cycles The amount of time to putput the blanking level for.
*/
void output_blank(unsigned int number_of_cycles);
/*! Outputs the first written to the most-recently created run of data repeatedly for a prolonged period.
@param number_of_cycles The number of cycles to repeat the output for.
*/
void output_level(unsigned int number_of_cycles);
/*! Declares that the caller has created a run of data via @c allocate_write_area and @c get_write_target_for_buffer
that is at least @c number_of_cycles long, and that the first @c number_of_cycles/source_divider should be spread
over that amount of time.
@param number_of_cycles The amount of data to output.
@param source_divider A divider for source data; if the divider is 1 then one source pixel is output every cycle,
if it is 2 then one source pixel covers two cycles; if it is n then one source pixel covers n cycles.
@see @c allocate_write_area , @c get_write_target_for_buffer
*/
void output_data(unsigned int number_of_cycles, unsigned int source_divider);
/*! Outputs a colour burst.
@param number_of_cycles The length of the colour burst.
@param phase The initial phase of the colour burst in a measuring system with 256 units
per circle, e.g. 0 = 0 degrees, 128 = 180 degrees, 256 = 360 degree.
@param amplitude The amplitude of the colour burst in 1/256ths of the amplitude of the
positive portion of the wave.
*/
void output_colour_burst(unsigned int number_of_cycles, uint8_t phase, uint8_t amplitude);
/*! Outputs a colour burst exactly in phase with CRT expectations using the idiomatic amplitude.
@param number_of_cycles The length of the colour burst;
*/
void output_default_colour_burst(unsigned int number_of_cycles);
/*! Attempts to allocate the given number of output samples for writing.
The beginning of the most recently allocated area is used as the start
of data written by a call to @c output_data; it is acceptable to write and to
output less data than the amount requested but that may be less efficient.
Allocation should fail only if emulation is running significantly below real speed.
@param required_length The number of samples to allocate.
@returns A pointer to the allocated area if room is available; @c nullptr otherwise.
*/
inline uint8_t *allocate_write_area(size_t required_length)
{
std::unique_lock<std::mutex> output_lock = openGL_output_builder_.get_output_lock();
return openGL_output_builder_.texture_builder.allocate_write_area(required_length);
}
/*! Causes appropriate OpenGL or OpenGL ES calls to be issued in order to draw the current CRT state.
The caller is responsible for ensuring that a valid OpenGL context exists for the duration of this call.
*/
inline void draw_frame(unsigned int output_width, unsigned int output_height, bool only_if_dirty)
{
{
std::lock_guard<std::mutex> function_guard(function_mutex_);
for(std::function<void(void)> function : enqueued_openGL_functions_)
{
function();
}
enqueued_openGL_functions_.clear();
}
openGL_output_builder_.draw_frame(output_width, output_height, only_if_dirty);
}
/*! Tells the CRT that the next call to draw_frame will occur on a different OpenGL context than
the previous.
@param should_delete_resources If @c true then all resources — textures, vertex arrays, etc —
currently held by the CRT will be deleted now via calls to glDeleteTexture and equivalent. If
@c false then the references are simply marked as invalid.
*/
inline void set_openGL_context_will_change(bool should_delete_resources)
{
openGL_output_builder_.set_openGL_context_will_change(should_delete_resources);
}
/*! Sets a function that will map from whatever data the machine provided to a composite signal.
@param shader A GLSL fragment including a function with the signature
`float composite_sample(usampler2D texID, vec2 coordinate, vec2 iCoordinate, float phase, float amplitude)`
that evaluates to the composite signal level as a function of a source buffer, sampling location, colour
carrier phase and amplitude.
*/
inline void set_composite_sampling_function(const char *shader)
{
openGL_output_builder_.set_composite_sampling_function(shader);
}
/*! Sets a function that will map from whatever data the machine provided to an RGB signal.
If the output mode is composite then a default mapping from RGB to the display's composite
format will be applied.
@param shader A GLSL fragent including a function with the signature
`vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)` that evaluates to an RGB colour
as a function of:
* `usampler2D sampler` representing the source buffer;
* `vec2 coordinate` representing the source buffer location to sample from in the range [0, 1); and
* `vec2 icoordinate` representing the source buffer location to sample from as a pixel count, for easier multiple-pixels-per-byte unpacking.
*/
inline void set_rgb_sampling_function(const char *shader)
{
openGL_output_builder_.set_rgb_sampling_function(shader);
}
inline void set_output_device(OutputDevice output_device)
{
openGL_output_builder_.set_output_device(output_device);
}
inline void set_visible_area(Rect visible_area)
{
openGL_output_builder_.set_visible_area(visible_area);
}
Rect get_rect_for_area(int first_line_after_sync, int number_of_lines, int first_cycle_after_sync, int number_of_cycles, float aspect_ratio);
inline void set_delegate(Delegate *delegate)
{
delegate_ = delegate;
}
};
}
}
#endif /* CRT_cpp */
<|endoftext|> |
<commit_before>// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <[email protected]>
// Test the DDS scanner, parser and DDS class.
//
// jhrg 8/29/94
#include "config.h"
#include <fstream>
#include <GetOpt.h>
#include "parser.h"
#include "dds.tab.hh"
#include "BaseType.h"
#include "Int32.h"
#include "DDS.h"
#include "util.h"
#include "Error.h"
#ifdef DAP4
#include "D4ParserSax2.h"
#include "D4BaseTypeFactory.h"
#endif
using namespace libdap;
void test_scanner();
void test_parser(const string &name);
void test_class();
void test_dap4_parser(const string &name);
int ddslex();
// int ddsparse(DDS &);
extern YYSTYPE ddslval;
extern int ddsdebug;
static bool print_ddx = false;
const char *prompt = "dds-test: ";
void usage(string name) {
fprintf(stderr, "usage: %s %s\n %s\n %s\n %s\n %s\n %s\n %s\n %s\n", name.c_str(), "[s] [pd] [c]",
"s: Test the scanner.", "p: Test the parser; reads from stdin and prints the",
" internal structure to stdout.", "d: Turn on parser debugging. (only for the hard core.)",
"c: Test the C++ code for manipulating DDS objects.",
" Reads from stdin, parses and writes the modified DDS", " to stdout.");
}
int main(int argc, char *argv[]) {
GetOpt getopt(argc, argv, "spP:dfF:cx");
int option_char;
int scanner_test = 0, parser_test = 0, class_test = 0;
int dap4_parser_test = 0;
string name = "";
// process options
while ((option_char = getopt()) != EOF)
switch (option_char) {
case 'd':
ddsdebug = 1;
break;
case 's':
scanner_test = 1;
break;
case 'p':
parser_test = 1;
break;
case 'P':
parser_test = 1;
name = getopt.optarg;
break;
case 'f':
dap4_parser_test = 1;
break;
case 'F':
dap4_parser_test = 1;
name = getopt.optarg;
break;
case 'x':
print_ddx = true;
break;
case 'c':
class_test = 1;
break;
case '?':
default:
usage(argv[0]);
return 1;
}
if (!scanner_test && !parser_test && !class_test && !dap4_parser_test) {
usage(argv[0]);
return 1;
}
try {
if (scanner_test)
test_scanner();
if (parser_test)
test_parser(name);
if (dap4_parser_test)
test_dap4_parser(name);
if (class_test)
test_class();
}
catch (Error &e) {
cerr << e.get_error_message() << endl;
}
}
void test_scanner(void) {
int tok;
cout << prompt << flush; // first prompt
while ((tok = ddslex())) {
switch (tok) {
case SCAN_DATASET:
cout << "DATASET" << endl;
break;
case SCAN_LIST:
cout << "LIST" << endl;
break;
case SCAN_SEQUENCE:
cout << "SEQUENCE" << endl;
break;
case SCAN_STRUCTURE:
cout << "STRUCTURE" << endl;
break;
case SCAN_FUNCTION:
cout << "FUNCTION" << endl;
break;
case SCAN_GRID:
cout << "GRID" << endl;
break;
case SCAN_BYTE:
cout << "BYTE" << endl;
break;
case SCAN_INT16:
cout << "INT16" << endl;
break;
case SCAN_UINT16:
cout << "UINT16" << endl;
break;
case SCAN_INT32:
cout << "INT32" << endl;
break;
case SCAN_UINT32:
cout << "UINT32" << endl;
break;
case SCAN_FLOAT32:
cout << "FLOAT32" << endl;
break;
case SCAN_FLOAT64:
cout << "FLOAT64" << endl;
break;
case SCAN_STRING:
cout << "STRING" << endl;
break;
case SCAN_URL:
cout << "Url" << endl;
break;
case SCAN_WORD:
cout << "WORD: " << ddslval.word << endl;
break;
case '{':
cout << "Left Brace" << endl;
break;
case '}':
cout << "Right Brace" << endl;
break;
case '[':
cout << "Left Bracket" << endl;
break;
case ']':
cout << "Right Bracket" << endl;
break;
case ';':
cout << "Semicolon" << endl;
break;
case ':':
cout << "Colon" << endl;
break;
case '=':
cout << "Assignment" << endl;
break;
default:
cout << "Error: Unrecognized input" << endl;
break;
}
cout << prompt << flush; // print prompt after output
}
}
void test_parser(const string &name) {
BaseTypeFactory *factory = new BaseTypeFactory;
DDS table(factory);
if (name.empty())
table.parse();
else
table.parse(name);
if (table.check_semantics())
cout << "DDS past semantic check" << endl;
else
cout << "DDS failed semantic check" << endl;
if (table.check_semantics(true))
cout << "DDS past full semantic check" << endl;
else
cout << "DDS failed full semantic check" << endl;
if (print_ddx)
table.print_xml_writer(cout, false, "");
else
table.print(cout);
delete factory;
factory = 0;
}
void test_dap4_parser(const string &name) {
#ifdef DAP4
D4BaseTypeFactory factory;
DDS table(&factory);
D4ParserSax2 parser;
if (name.empty()) {
parser.intern(cin, &table);
}
else {
fstream in(name.c_str(), ios_base::in);
parser.intern(in, &table);
}
if (table.check_semantics())
cout << "DAP4 DDS past semantic check" << endl;
else
cout << "DAP4 DDS failed semantic check" << endl;
if (table.check_semantics(true))
cout << "DAP4 DDS past full semantic check" << endl;
else
cout << "DAP4 DDS failed full semantic check" << endl;
if (print_ddx)
table.print_xml_writer(cout, false, "");
else
table.print(cout);
#else
cerr << "DAP4 parsing not supported by this version of libdap" << endl;
#endif
}
void test_class(void) {
BaseTypeFactory *factory = new BaseTypeFactory;
DDS table(factory);
table.parse();
if (table.check_semantics())
cout << "DDS past semantic check" << endl;
else
cout << "DDS filed semantic check" << endl;
if (table.check_semantics(true))
cout << "DDS past full semantic check" << endl;
else
cout << "DDS filed full semantic check" << endl;
table.print(cout);
DDS table2 = table; // test copy ctor;
table2.print(cout);
BaseTypeFactory *factory2 = new BaseTypeFactory;
DDS table3(factory2);
table3 = table; // test operator=
cout << "Dataset name: " << table.get_dataset_name() << endl;
string name = "goofy";
table.add_var(table.get_factory()->NewInt32(name)); // table dtor should delete this object
table.print(cout);
BaseType *btp = table.var(name);
btp->print_decl(cout, "", true); // print out goofy w/semicolon
table.del_var(name);
table.print(cout);
table.add_var(table.get_factory()->NewInt32("goofy"));
table.print(cout);
btp = table.var("goofy");
btp->print_decl(cout, "", true); // print out goofy w/semicolon
table.del_var("goofy");
table.print(cout);
for (DDS::Vars_iter p = table.var_begin(); p != table.var_end(); p++)
(*p)->print_decl(cout, "", true); // print them all w/semicolons
delete factory;
factory = 0;
delete factory2;
factory2 = 0;
}
<commit_msg>Added stuff to svn:ignore<commit_after>// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <[email protected]>
// Test the DDS scanner, parser and DDS class.
//
// jhrg 8/29/94
#include "config.h"
#include <fstream>
#include <GetOpt.h>
#include "parser.h"
#include "dds.tab.hh"
#include "BaseType.h"
#include "Int32.h"
#include "DDS.h"
#include "util.h"
#include "Error.h"
#ifdef DAP4
#include "D4ParserSax2.h"
#include "D4BaseTypeFactory.h"
#endif
using namespace libdap;
void test_scanner();
void test_parser(const string &name);
void test_class();
void test_dap4_parser(const string &name);
int ddslex();
// int ddsparse(DDS &);
extern YYSTYPE ddslval;
extern int ddsdebug;
static bool print_ddx = false;
const char *prompt = "dds-test: ";
void usage(string name) {
fprintf(stderr, "usage: %s %s\n %s\n %s\n %s\n %s\n %s\n %s\n %s\n", name.c_str(), "[s] [pd] [c]",
"s: Test the scanner.", "p: Test the parser; reads from stdin and prints the",
" internal structure to stdout.", "d: Turn on parser debugging. (only for the hard core.)",
"c: Test the C++ code for manipulating DDS objects.",
" Reads from stdin, parses and writes the modified DDS", " to stdout.");
}
int main(int argc, char *argv[]) {
GetOpt getopt(argc, argv, "spP:dfF:cx");
int option_char;
int scanner_test = 0, parser_test = 0, class_test = 0;
int dap4_parser_test = 0;
string name = "";
// process options
while ((option_char = getopt()) != EOF)
switch (option_char) {
case 'd':
ddsdebug = 1;
break;
case 's':
scanner_test = 1;
break;
case 'p':
parser_test = 1;
break;
case 'P':
parser_test = 1;
name = getopt.optarg;
break;
case 'f':
dap4_parser_test = 1;
break;
case 'F':
dap4_parser_test = 1;
name = getopt.optarg;
break;
case 'x':
print_ddx = true;
break;
case 'c':
class_test = 1;
break;
case '?':
default:
usage(argv[0]);
return 1;
}
if (!scanner_test && !parser_test && !class_test && !dap4_parser_test) {
usage(argv[0]);
return 1;
}
try {
if (scanner_test)
test_scanner();
if (parser_test)
test_parser(name);
if (dap4_parser_test)
test_dap4_parser(name);
if (class_test)
test_class();
}
catch (Error &e) {
cerr << e.get_error_message() << endl;
}
}
void test_scanner(void) {
int tok;
cout << prompt << flush; // first prompt
while ((tok = ddslex())) {
switch (tok) {
case SCAN_DATASET:
cout << "DATASET" << endl;
break;
case SCAN_LIST:
cout << "LIST" << endl;
break;
case SCAN_SEQUENCE:
cout << "SEQUENCE" << endl;
break;
case SCAN_STRUCTURE:
cout << "STRUCTURE" << endl;
break;
case SCAN_FUNCTION:
cout << "FUNCTION" << endl;
break;
case SCAN_GRID:
cout << "GRID" << endl;
break;
case SCAN_BYTE:
cout << "BYTE" << endl;
break;
case SCAN_INT16:
cout << "INT16" << endl;
break;
case SCAN_UINT16:
cout << "UINT16" << endl;
break;
case SCAN_INT32:
cout << "INT32" << endl;
break;
case SCAN_UINT32:
cout << "UINT32" << endl;
break;
case SCAN_FLOAT32:
cout << "FLOAT32" << endl;
break;
case SCAN_FLOAT64:
cout << "FLOAT64" << endl;
break;
case SCAN_STRING:
cout << "STRING" << endl;
break;
case SCAN_URL:
cout << "Url" << endl;
break;
case SCAN_WORD:
cout << "WORD: " << ddslval.word << endl;
break;
case '{':
cout << "Left Brace" << endl;
break;
case '}':
cout << "Right Brace" << endl;
break;
case '[':
cout << "Left Bracket" << endl;
break;
case ']':
cout << "Right Bracket" << endl;
break;
case ';':
cout << "Semicolon" << endl;
break;
case ':':
cout << "Colon" << endl;
break;
case '=':
cout << "Assignment" << endl;
break;
default:
cout << "Error: Unrecognized input" << endl;
break;
}
cout << prompt << flush; // print prompt after output
}
}
void test_parser(const string &name) {
BaseTypeFactory *factory = new BaseTypeFactory;
DDS table(factory);
if (name.empty())
table.parse();
else
table.parse(name);
if (table.check_semantics())
cout << "DDS past semantic check" << endl;
else
cout << "DDS failed semantic check" << endl;
if (table.check_semantics(true))
cout << "DDS past full semantic check" << endl;
else
cout << "DDS failed full semantic check" << endl;
if (print_ddx)
table.print_xml_writer(cout, false, "");
else
table.print(cout);
delete factory;
factory = 0;
}
void test_dap4_parser(const string &/*name*/) {
#ifdef DAP4
D4BaseTypeFactory factory;
DDS table(&factory);
D4ParserSax2 parser;
if (name.empty()) {
parser.intern(cin, &table);
}
else {
fstream in(name.c_str(), ios_base::in);
parser.intern(in, &table);
}
if (table.check_semantics())
cout << "DAP4 DDS past semantic check" << endl;
else
cout << "DAP4 DDS failed semantic check" << endl;
if (table.check_semantics(true))
cout << "DAP4 DDS past full semantic check" << endl;
else
cout << "DAP4 DDS failed full semantic check" << endl;
if (print_ddx)
table.print_xml_writer(cout, false, "");
else
table.print(cout);
#else
cerr << "DAP4 parsing not supported by this version of libdap" << endl;
#endif
}
void test_class(void) {
BaseTypeFactory *factory = new BaseTypeFactory;
DDS table(factory);
table.parse();
if (table.check_semantics())
cout << "DDS past semantic check" << endl;
else
cout << "DDS filed semantic check" << endl;
if (table.check_semantics(true))
cout << "DDS past full semantic check" << endl;
else
cout << "DDS filed full semantic check" << endl;
table.print(cout);
DDS table2 = table; // test copy ctor;
table2.print(cout);
BaseTypeFactory *factory2 = new BaseTypeFactory;
DDS table3(factory2);
table3 = table; // test operator=
cout << "Dataset name: " << table.get_dataset_name() << endl;
string name = "goofy";
table.add_var(table.get_factory()->NewInt32(name)); // table dtor should delete this object
table.print(cout);
BaseType *btp = table.var(name);
btp->print_decl(cout, "", true); // print out goofy w/semicolon
table.del_var(name);
table.print(cout);
table.add_var(table.get_factory()->NewInt32("goofy"));
table.print(cout);
btp = table.var("goofy");
btp->print_decl(cout, "", true); // print out goofy w/semicolon
table.del_var("goofy");
table.print(cout);
for (DDS::Vars_iter p = table.var_begin(); p != table.var_end(); p++)
(*p)->print_decl(cout, "", true); // print them all w/semicolons
delete factory;
factory = 0;
delete factory2;
factory2 = 0;
}
<|endoftext|> |
<commit_before>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <[email protected]>
#include "hadesmem/patcher.hpp"
#define BOOST_TEST_MODULE patcher
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/assign/std/vector.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
using namespace boost::assign;
#include "hadesmem/alloc.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/read.hpp"
#include "hadesmem/process.hpp"
// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// TODO: Patcher constructor tests.
// TODO: Improve hook target checks.
// TODO: Fix annoying UAC popup (with manifest).
// TODO: Fix test under Clang and ICC. (Convert to use functions written
// in assembly to ensure it's not caused by compiler-specific call conv
// issues triggering incomplete parts of Patcher such as relative instruction
// conversion. First though, just try an explicit call conv.)
namespace
{
DWORD HookMe()
{
std::string const foo("Foo");
BOOST_CHECK_EQUAL(foo, "Foo");
return 0x1234;
}
std::shared_ptr<hadesmem::PatchDetour> g_ptr_detour_1;
DWORD HookMe_Hook()
{
BOOST_CHECK(g_ptr_detour_1->GetTrampoline() != nullptr);
auto const ptr_orig = reinterpret_cast<DWORD (*)()>(
reinterpret_cast<DWORD_PTR>(g_ptr_detour_1->GetTrampoline()));
BOOST_CHECK_EQUAL(ptr_orig(), static_cast<DWORD>(0x1234));
return 0x1337;
}
}
BOOST_AUTO_TEST_CASE(patcher)
{
hadesmem::Process const process(::GetCurrentProcessId());
hadesmem::Allocator const test_mem_1(&process, 0x1000);
std::vector<BYTE> data_1;
data_1 += 0x00, 0x11, 0x22, 0x33, 0x44;
BOOST_REQUIRE(data_1.size() == 5);
hadesmem::PatchRaw patch_1(&process, test_mem_1.GetBase(), data_1);
auto const orig_1 = hadesmem::ReadVector<BYTE>(process, test_mem_1.GetBase(),
5);
patch_1.Apply();
auto const apply_1 = hadesmem::ReadVector<BYTE>(process, test_mem_1.GetBase(),
5);
patch_1.Remove();
auto const remove_1 = hadesmem::ReadVector<BYTE>(process,
test_mem_1.GetBase(), 5);
BOOST_CHECK(orig_1 == remove_1);
BOOST_CHECK(orig_1 != apply_1);
BOOST_CHECK(data_1 == apply_1);
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
DWORD_PTR const ptr_hook_me = reinterpret_cast<DWORD_PTR>(&HookMe);
DWORD_PTR const ptr_hook_me_hook = reinterpret_cast<DWORD_PTR>(&HookMe_Hook);
g_ptr_detour_1.reset(new hadesmem::PatchDetour(&process,
reinterpret_cast<PVOID>(ptr_hook_me),
reinterpret_cast<PVOID>(ptr_hook_me_hook)));
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
g_ptr_detour_1->Apply();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1337));
g_ptr_detour_1->Remove();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
g_ptr_detour_1->Apply();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1337));
g_ptr_detour_1->Remove();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
}
<commit_msg>* Added a winapi hook test.<commit_after>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <[email protected]>
#include "hadesmem/patcher.hpp"
#define BOOST_TEST_MODULE patcher
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/assign/std/vector.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
using namespace boost::assign;
#include "hadesmem/alloc.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/read.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// TODO: Patcher constructor tests.
// TODO: Improve hook target checks.
// TODO: Fix annoying UAC popup (with manifest).
// TODO: Fix test under Clang and ICC. (Convert to use functions written
// in assembly to ensure it's not caused by compiler-specific call conv
// issues triggering incomplete parts of Patcher such as relative instruction
// conversion. First though, just try an explicit call conv.)
namespace
{
std::shared_ptr<hadesmem::PatchDetour> g_ptr_detour_1;
std::shared_ptr<hadesmem::PatchDetour> g_ptr_detour_2;
DWORD __stdcall HookMe()
{
std::string const foo("Foo");
BOOST_CHECK_EQUAL(foo, "Foo");
return 0x1234;
}
DWORD __stdcall HookMe_Hook()
{
BOOST_CHECK(g_ptr_detour_2->GetTrampoline() != nullptr);
auto const ptr_orig = reinterpret_cast<DWORD (__stdcall *)()>(
reinterpret_cast<DWORD_PTR>(g_ptr_detour_2->GetTrampoline()));
BOOST_CHECK_EQUAL(ptr_orig(), static_cast<DWORD>(0x1234));
return 0x1337;
}
DWORD GetCurrentProcessId_Hook()
{
BOOST_CHECK(g_ptr_detour_1->GetTrampoline() != nullptr);
auto const ptr_orig = reinterpret_cast<DWORD (WINAPI*)()>(
reinterpret_cast<DWORD_PTR>(g_ptr_detour_1->GetTrampoline()));
return ptr_orig() * 2;
}
}
BOOST_AUTO_TEST_CASE(patcher)
{
hadesmem::Process const process(::GetCurrentProcessId());
hadesmem::Allocator const test_mem_1(&process, 0x1000);
std::vector<BYTE> data_1;
data_1 += 0x00, 0x11, 0x22, 0x33, 0x44;
BOOST_REQUIRE(data_1.size() == 5);
hadesmem::PatchRaw patch_1(&process, test_mem_1.GetBase(), data_1);
auto const orig_1 = hadesmem::ReadVector<BYTE>(process,
test_mem_1.GetBase(), 5);
patch_1.Apply();
auto const apply_1 = hadesmem::ReadVector<BYTE>(process,
test_mem_1.GetBase(), 5);
patch_1.Remove();
auto const remove_1 = hadesmem::ReadVector<BYTE>(process,
test_mem_1.GetBase(), 5);
BOOST_CHECK(orig_1 == remove_1);
BOOST_CHECK(orig_1 != apply_1);
BOOST_CHECK(data_1 == apply_1);
DWORD const proc_id = GetCurrentProcessId();
hadesmem::Module const kernel32_mod(&process, L"kernel32.dll");
typedef DWORD (WINAPI * GetCurrentProcessIdFunc)();
GetCurrentProcessIdFunc const get_current_process_id =
reinterpret_cast<GetCurrentProcessIdFunc>(reinterpret_cast<DWORD_PTR>(
hadesmem::FindProcedure(kernel32_mod, "GetCurrentProcessId")));
BOOST_CHECK_EQUAL(get_current_process_id(), GetCurrentProcessId());
g_ptr_detour_1.reset(new hadesmem::PatchDetour(&process,
reinterpret_cast<PVOID>(reinterpret_cast<DWORD_PTR>(get_current_process_id)),
reinterpret_cast<PVOID>(reinterpret_cast<DWORD_PTR>(&GetCurrentProcessId_Hook))));
BOOST_CHECK_EQUAL(GetCurrentProcessId(), proc_id);
g_ptr_detour_1->Apply();
BOOST_CHECK_EQUAL(GetCurrentProcessId(), proc_id * 2);
g_ptr_detour_1->Remove();
BOOST_CHECK_EQUAL(GetCurrentProcessId(), proc_id);
g_ptr_detour_1->Apply();
BOOST_CHECK_EQUAL(GetCurrentProcessId(), proc_id * 2);
g_ptr_detour_1->Remove();
BOOST_CHECK_EQUAL(GetCurrentProcessId(), proc_id);
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
DWORD_PTR const ptr_hook_me = reinterpret_cast<DWORD_PTR>(&HookMe);
DWORD_PTR const ptr_hook_me_hook = reinterpret_cast<DWORD_PTR>(&HookMe_Hook);
g_ptr_detour_2.reset(new hadesmem::PatchDetour(&process,
reinterpret_cast<PVOID>(ptr_hook_me),
reinterpret_cast<PVOID>(ptr_hook_me_hook)));
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
g_ptr_detour_2->Apply();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1337));
g_ptr_detour_2->Remove();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
g_ptr_detour_2->Apply();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1337));
g_ptr_detour_2->Remove();
BOOST_CHECK_EQUAL(HookMe(), static_cast<DWORD>(0x1234));
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 deipi.com LLC and contributors. All rights reserved.
*
* 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 "test_wal.h"
#include "utils.h"
static std::string test_db(".test_wal.db");
static std::string restored_db(".backup_wal.db");
uint32_t get_checksum(int fd) {
ssize_t bytes;
char buf[1024];
XXH32_state_t* xxhash = XXH32_createState();
XXH32_reset(xxhash, 0);
while ((bytes = io::read(fd, buf, sizeof(buf))) > 0) {
XXH32_update(xxhash, buf, bytes);
}
uint32_t checksum = XXH32_digest(xxhash);
XXH32_freeState(xxhash);
return checksum;
}
bool dir_compare(const std::string& dir1, const std::string& dir2) {
bool same_file = true;
DIR* d1 = opendir(dir1.c_str());
if (!d1) {
L_ERR(nullptr, "ERROR: %s", strerror(errno));
return false;
}
DIR* d2 = opendir(dir2.c_str());
if (!d2) {
L_ERR(nullptr, "ERROR: %s", strerror(errno));
return false;
}
struct dirent *ent;
while ((ent = readdir(d1)) != nullptr) {
if (ent->d_type == DT_REG) {
std::string dir1_file (dir1 + "/" + std::string(ent->d_name));
std::string dir2_file (dir2 + "/" + std::string(ent->d_name));
int fd1 = open(dir1_file.c_str(), O_RDONLY);
if (-1 == fd1) {
L_ERR(nullptr, "ERROR: opening file. %s\n", dir1_file.c_str());
same_file = false;
break;
}
int fd2 = open(dir2_file.c_str(), O_RDONLY);
if (-1 == fd2) {
L_ERR(nullptr, "ERROR: opening file. %s\n", dir2_file.c_str());
same_file = false;
close(fd1);
break;
}
if (get_checksum(fd1) != get_checksum(fd2)) {
L_ERR(nullptr, "ERROR: file %s and file %s are not the same\n", std::string(dir1_file).c_str(), std::string(dir2_file).c_str());
same_file = false;
close(fd1);
close(fd2);
break;
}
close(fd1);
close(fd2);
}
}
closedir(d1);
closedir(d2);
return same_file;
}
DB_Test db_wal (test_db, std::vector<std::string>(), DB_WRITABLE | DB_SPAWN);
int create_db_wal() {
int num_documents = 1020;
std::string document("{ \"message\" : \"Hello world\"}");
db_wal.db_handler.index(document, std::to_string(1), true, JSON_TYPE, std::to_string(document.size()));
if (copy_file(test_db.c_str(), restored_db.c_str()) == -1) {
return 1;
}
for (int i = 2; i <= num_documents; ++i) {
db_wal->db_handler.index(document, std::to_string(i), true, JSON_TYPE, std::to_string(document.size()));
}
if (copy_file(test_db.c_str(), restored_db.c_str(), true, std::string("wal.0")) == -1) {
return 1;
}
if (copy_file(test_db.c_str(), restored_db.c_str(), true, std::string("wal.1012")) == -1) {
return 1;
}
return 0;
}
int restore_database() {
try {
if (create_db_wal() == 0) {
if (not dir_compare(test_db, restored_db)) {
RETURN(1);
}
}
RETURN(1);
} catch (const ClientError& exc) {
L_EXC(nullptr, "ERROR: %s", exc.what());
RETURN(1);
} catch (const Xapian::Error& exc) {
L_EXC(nullptr, "ERROR: %s (%s)", exc.get_msg().c_str(), exc.get_error_string());
RETURN(1);
} catch (const std::exception& exc) {
L_EXC(nullptr, "ERROR: %s", exc.what());
RETURN(1);
}
}
<commit_msg>Error message in case the copy is not done<commit_after>/*
* Copyright (C) 2016 deipi.com LLC and contributors. All rights reserved.
*
* 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 "test_wal.h"
#include "utils.h"
static std::string test_db(".test_wal.db");
static std::string restored_db(".backup_wal.db");
uint32_t get_checksum(int fd) {
ssize_t bytes;
char buf[1024];
XXH32_state_t* xxhash = XXH32_createState();
XXH32_reset(xxhash, 0);
while ((bytes = io::read(fd, buf, sizeof(buf))) > 0) {
XXH32_update(xxhash, buf, bytes);
}
uint32_t checksum = XXH32_digest(xxhash);
XXH32_freeState(xxhash);
return checksum;
}
bool dir_compare(const std::string& dir1, const std::string& dir2) {
bool same_file = true;
DIR* d1 = opendir(dir1.c_str());
if (!d1) {
L_ERR(nullptr, "ERROR: %s", strerror(errno));
return false;
}
DIR* d2 = opendir(dir2.c_str());
if (!d2) {
L_ERR(nullptr, "ERROR: %s", strerror(errno));
return false;
}
struct dirent *ent;
while ((ent = readdir(d1)) != nullptr) {
if (ent->d_type == DT_REG) {
std::string dir1_file (dir1 + "/" + std::string(ent->d_name));
std::string dir2_file (dir2 + "/" + std::string(ent->d_name));
int fd1 = open(dir1_file.c_str(), O_RDONLY);
if (-1 == fd1) {
L_ERR(nullptr, "ERROR: opening file. %s\n", dir1_file.c_str());
same_file = false;
break;
}
int fd2 = open(dir2_file.c_str(), O_RDONLY);
if (-1 == fd2) {
L_ERR(nullptr, "ERROR: opening file. %s\n", dir2_file.c_str());
same_file = false;
close(fd1);
break;
}
if (get_checksum(fd1) != get_checksum(fd2)) {
L_ERR(nullptr, "ERROR: file %s and file %s are not the same\n", std::string(dir1_file).c_str(), std::string(dir2_file).c_str());
same_file = false;
close(fd1);
close(fd2);
break;
}
close(fd1);
close(fd2);
}
}
closedir(d1);
closedir(d2);
return same_file;
}
DB_Test db_wal (test_db, std::vector<std::string>(), DB_WRITABLE | DB_SPAWN);
int create_db_wal() {
int num_documents = 1020;
std::string document("{ \"message\" : \"Hello world\"}");
db_wal.db_handler.index(document, std::to_string(1), true, JSON_TYPE, std::to_string(document.size()));
if (copy_file(test_db.c_str(), restored_db.c_str()) == -1) {
L_ERR(nullptr, "ERROR: Could not copy the dir %s to dir %s\n", test_db.c_str(), restored_db.c_str());
return 1;
}
for (int i = 2; i <= num_documents; ++i) {
db_wal.db_handler.index(document, std::to_string(i), true, JSON_TYPE, std::to_string(document.size()));
}
if (copy_file(test_db.c_str(), restored_db.c_str(), true, std::string("wal.0")) == -1) {
L_ERR(nullptr, "ERROR: Could not copy the dir %s to dir %s\n", "wal.0", restored_db.c_str());
return 1;
}
if (copy_file(test_db.c_str(), restored_db.c_str(), true, std::string("wal.1012")) == -1) {
L_ERR(nullptr, "ERROR: Could not copy the file %s to dir %s\n", "wal.1012", restored_db.c_str());
return 1;
}
return 0;
}
int restore_database() {
try {
if (create_db_wal() == 0) {
if (not dir_compare(test_db, restored_db)) {
RETURN(1);
}
}
RETURN(1);
} catch (const ClientError& exc) {
L_EXC(nullptr, "ERROR: %s", exc.what());
RETURN(1);
} catch (const Xapian::Error& exc) {
L_EXC(nullptr, "ERROR: %s (%s)", exc.get_msg().c_str(), exc.get_error_string());
RETURN(1);
} catch (const std::exception& exc) {
L_EXC(nullptr, "ERROR: %s", exc.what());
RETURN(1);
}
}
<|endoftext|> |
<commit_before>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage
#include <boost/test/unit_test.hpp>
#include "storage/Devices/Disk.h"
#include "storage/Devices/LvmVg.h"
#include "storage/Devices/LvmLvImpl.h"
#include "storage/Utils/HumanString.h"
#include "storage/Devicegraph.h"
#include "storage/Storage.h"
#include "storage/Environment.h"
#include "testsuite/helpers/CallbacksRecorder.h"
using namespace std;
using namespace storage;
BOOST_AUTO_TEST_CASE(sizes1)
{
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 2 * TiB);
Disk* sdb = Disk::create(staging, "/dev/sdb", 2 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
lvm_vg->add_lvm_pv(sdb);
// one extent for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->number_of_extents(), 4 * TiB / (4 * MiB) - 2);
BOOST_CHECK_EQUAL(lvm_vg->number_of_used_extents(), 0);
BOOST_CHECK_EQUAL(lvm_vg->number_of_free_extents(), 4 * TiB / (4 * MiB) - 2);
BOOST_CHECK_EQUAL(lvm_vg->max_size_for_lvm_lv(LvType::NORMAL), lvm_vg->number_of_free_extents() * 4 * MiB);
// twice 128 MiB for metadata
BOOST_CHECK_EQUAL(lvm_vg->max_size_for_lvm_lv(LvType::THIN_POOL), lvm_vg->number_of_free_extents() * 4 * MiB - 256 * MiB);
unsigned long long used_extents = 0;
{
LvmLv* thin_pool1 = lvm_vg->create_lvm_lv("thin-pool1", LvType::THIN_POOL, 1 * GiB);
BOOST_CHECK_EQUAL(thin_pool1->get_chunk_size(), 0 * B);
BOOST_CHECK_EQUAL(thin_pool1->get_impl().default_chunk_size(), 64 * KiB);
BOOST_CHECK_EQUAL(thin_pool1->get_impl().default_metadata_size(), 4 * MiB);
BOOST_CHECK_EQUAL(thin_pool1->max_size_for_lvm_lv(LvType::THIN), 16 * PiB - 4 * MiB);
used_extents += (1 * GiB) / (4 * MiB); // data
used_extents += (4 * MiB) / (4 * MiB); // metadata
}
{
LvmLv* thin_pool2 = lvm_vg->create_lvm_lv("thin-pool2", LvType::THIN_POOL, 1 * TiB);
BOOST_CHECK_EQUAL(thin_pool2->get_chunk_size(), 0 * B);
BOOST_CHECK_EQUAL(thin_pool2->get_impl().default_chunk_size(), 512 * KiB);
BOOST_CHECK_EQUAL(thin_pool2->get_impl().default_metadata_size(), 128 * MiB);
used_extents += (1 * TiB) / (4 * MiB); // data
used_extents += (128 * MiB) / (4 * MiB); // metadata
used_extents += (128 * MiB) / (4 * MiB); // spare metadata
}
{
LvmLv* thin_pool3 = lvm_vg->create_lvm_lv("thin-pool3", LvType::THIN_POOL, 1 * TiB);
thin_pool3->set_chunk_size(4 * MiB);
BOOST_CHECK_EQUAL(thin_pool3->get_chunk_size(), 4 * MiB);
BOOST_CHECK_EQUAL(thin_pool3->get_impl().default_chunk_size(), 512 * KiB);
BOOST_CHECK_EQUAL(thin_pool3->get_impl().default_metadata_size(), 16 * MiB);
used_extents += (1 * TiB) / (4 * MiB); // data
used_extents += (16 * MiB) / (4 * MiB); // metadata
}
BOOST_CHECK_EQUAL(lvm_vg->number_of_used_extents(), used_extents);
BOOST_CHECK_EQUAL(lvm_vg->number_of_free_extents(), 4 * TiB / (4 * MiB) - 2 - used_extents);
}
BOOST_AUTO_TEST_CASE(lvm_vg_overcommitted)
{
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 1 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
lvm_vg->create_lvm_lv("normal1", LvType::NORMAL, 600 * GiB);
BOOST_CHECK(!lvm_vg->is_overcommitted());
lvm_vg->create_lvm_lv("normal2", LvType::NORMAL, 600 * GiB);
BOOST_CHECK(lvm_vg->is_overcommitted());
}
BOOST_AUTO_TEST_CASE(chunk_size_too_small)
{
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 20 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
LvmLv* thin_pool = lvm_vg->create_lvm_lv("thin-pool", LvType::THIN_POOL, 16 * TiB);
thin_pool->set_chunk_size(64 * KiB);
vector<string> check_messages;
CheckCallbacksRecorder check_callbacks_recorder(check_messages);
staging->check(&check_callbacks_recorder);
BOOST_CHECK_EQUAL(check_messages.size(), 1);
BOOST_CHECK_EQUAL(check_messages[0], "Chunk size is too small for thin pool logical volume "
"thin-pool in volume group test.");
}
BOOST_AUTO_TEST_CASE(change_extent_size)
{
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 1 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
LvmLv* normal1 = lvm_vg->create_lvm_lv("normal1", LvType::NORMAL, 1 * GiB);
LvmLv* normal2 = lvm_vg->create_lvm_lv("normal2", LvType::NORMAL, 6 * MiB);
// one extent (4 MiB per default) for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->get_size(), 1 * TiB - 4 * MiB);
BOOST_CHECK_EQUAL(normal1->get_size(), 1 * GiB);
BOOST_CHECK_EQUAL(normal2->get_size(), 4 * MiB);
lvm_vg->set_extent_size(128 * MiB);
// one extent (now 128 MiB) for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->get_size(), 1 * TiB - 128 * MiB);
BOOST_CHECK_EQUAL(normal1->get_size(), 1 * GiB);
BOOST_CHECK_EQUAL(normal2->get_size(), 0 * MiB);
}
BOOST_AUTO_TEST_CASE(set_invalid_extent_size)
{
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 1 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
LvmLv* normal1 = lvm_vg->create_lvm_lv("normal1", LvType::NORMAL, 1 * GiB);
LvmLv* normal2 = lvm_vg->create_lvm_lv("normal2", LvType::NORMAL, 6 * MiB);
// one extent (4 MiB per default) for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->get_size(), 1 * TiB - 4 * MiB);
BOOST_CHECK_EQUAL(normal1->get_size(), 1 * GiB);
BOOST_CHECK_EQUAL(normal2->get_size(), 4 * MiB);
BOOST_CHECK_THROW(lvm_vg->set_extent_size(48 * MiB), InvalidExtentSize);
}
<commit_msg>- enable logging<commit_after>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage
#include <boost/test/unit_test.hpp>
#include "storage/Devices/Disk.h"
#include "storage/Devices/LvmVg.h"
#include "storage/Devices/LvmLvImpl.h"
#include "storage/Utils/HumanString.h"
#include "storage/Devicegraph.h"
#include "storage/Storage.h"
#include "storage/Environment.h"
#include "testsuite/helpers/CallbacksRecorder.h"
using namespace std;
using namespace storage;
BOOST_AUTO_TEST_CASE(sizes1)
{
set_logger(get_stdout_logger());
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 2 * TiB);
Disk* sdb = Disk::create(staging, "/dev/sdb", 2 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
lvm_vg->add_lvm_pv(sdb);
// one extent for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->number_of_extents(), 4 * TiB / (4 * MiB) - 2);
BOOST_CHECK_EQUAL(lvm_vg->number_of_used_extents(), 0);
BOOST_CHECK_EQUAL(lvm_vg->number_of_free_extents(), 4 * TiB / (4 * MiB) - 2);
BOOST_CHECK_EQUAL(lvm_vg->max_size_for_lvm_lv(LvType::NORMAL), lvm_vg->number_of_free_extents() * 4 * MiB);
// twice 128 MiB for metadata
BOOST_CHECK_EQUAL(lvm_vg->max_size_for_lvm_lv(LvType::THIN_POOL), lvm_vg->number_of_free_extents() * 4 * MiB - 256 * MiB);
unsigned long long used_extents = 0;
{
LvmLv* thin_pool1 = lvm_vg->create_lvm_lv("thin-pool1", LvType::THIN_POOL, 1 * GiB);
BOOST_CHECK_EQUAL(thin_pool1->get_chunk_size(), 0 * B);
BOOST_CHECK_EQUAL(thin_pool1->get_impl().default_chunk_size(), 64 * KiB);
BOOST_CHECK_EQUAL(thin_pool1->get_impl().default_metadata_size(), 4 * MiB);
BOOST_CHECK_EQUAL(thin_pool1->max_size_for_lvm_lv(LvType::THIN), 16 * PiB - 4 * MiB);
used_extents += (1 * GiB) / (4 * MiB); // data
used_extents += (4 * MiB) / (4 * MiB); // metadata
}
{
LvmLv* thin_pool2 = lvm_vg->create_lvm_lv("thin-pool2", LvType::THIN_POOL, 1 * TiB);
BOOST_CHECK_EQUAL(thin_pool2->get_chunk_size(), 0 * B);
BOOST_CHECK_EQUAL(thin_pool2->get_impl().default_chunk_size(), 512 * KiB);
BOOST_CHECK_EQUAL(thin_pool2->get_impl().default_metadata_size(), 128 * MiB);
used_extents += (1 * TiB) / (4 * MiB); // data
used_extents += (128 * MiB) / (4 * MiB); // metadata
used_extents += (128 * MiB) / (4 * MiB); // spare metadata
}
{
LvmLv* thin_pool3 = lvm_vg->create_lvm_lv("thin-pool3", LvType::THIN_POOL, 1 * TiB);
thin_pool3->set_chunk_size(4 * MiB);
BOOST_CHECK_EQUAL(thin_pool3->get_chunk_size(), 4 * MiB);
BOOST_CHECK_EQUAL(thin_pool3->get_impl().default_chunk_size(), 512 * KiB);
BOOST_CHECK_EQUAL(thin_pool3->get_impl().default_metadata_size(), 16 * MiB);
used_extents += (1 * TiB) / (4 * MiB); // data
used_extents += (16 * MiB) / (4 * MiB); // metadata
}
BOOST_CHECK_EQUAL(lvm_vg->number_of_used_extents(), used_extents);
BOOST_CHECK_EQUAL(lvm_vg->number_of_free_extents(), 4 * TiB / (4 * MiB) - 2 - used_extents);
}
BOOST_AUTO_TEST_CASE(lvm_vg_overcommitted)
{
set_logger(get_stdout_logger());
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 1 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
lvm_vg->create_lvm_lv("normal1", LvType::NORMAL, 600 * GiB);
BOOST_CHECK(!lvm_vg->is_overcommitted());
lvm_vg->create_lvm_lv("normal2", LvType::NORMAL, 600 * GiB);
BOOST_CHECK(lvm_vg->is_overcommitted());
}
BOOST_AUTO_TEST_CASE(chunk_size_too_small)
{
set_logger(get_stdout_logger());
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 20 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
LvmLv* thin_pool = lvm_vg->create_lvm_lv("thin-pool", LvType::THIN_POOL, 16 * TiB);
thin_pool->set_chunk_size(64 * KiB);
vector<string> check_messages;
CheckCallbacksRecorder check_callbacks_recorder(check_messages);
staging->check(&check_callbacks_recorder);
BOOST_CHECK_EQUAL(check_messages.size(), 1);
BOOST_CHECK_EQUAL(check_messages[0], "Chunk size is too small for thin pool logical volume "
"thin-pool in volume group test.");
}
BOOST_AUTO_TEST_CASE(change_extent_size)
{
set_logger(get_stdout_logger());
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 1 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
LvmLv* normal1 = lvm_vg->create_lvm_lv("normal1", LvType::NORMAL, 1 * GiB);
LvmLv* normal2 = lvm_vg->create_lvm_lv("normal2", LvType::NORMAL, 6 * MiB);
// one extent (4 MiB per default) for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->get_size(), 1 * TiB - 4 * MiB);
BOOST_CHECK_EQUAL(normal1->get_size(), 1 * GiB);
BOOST_CHECK_EQUAL(normal2->get_size(), 4 * MiB);
lvm_vg->set_extent_size(128 * MiB);
// one extent (now 128 MiB) for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->get_size(), 1 * TiB - 128 * MiB);
BOOST_CHECK_EQUAL(normal1->get_size(), 1 * GiB);
BOOST_CHECK_EQUAL(normal2->get_size(), 0 * MiB);
}
BOOST_AUTO_TEST_CASE(set_invalid_extent_size)
{
set_logger(get_stdout_logger());
Environment environment(true, ProbeMode::NONE, TargetMode::DIRECT);
Storage storage(environment);
Devicegraph* staging = storage.get_staging();
Disk* sda = Disk::create(staging, "/dev/sda", 1 * TiB);
LvmVg* lvm_vg = LvmVg::create(staging, "test");
lvm_vg->add_lvm_pv(sda);
LvmLv* normal1 = lvm_vg->create_lvm_lv("normal1", LvType::NORMAL, 1 * GiB);
LvmLv* normal2 = lvm_vg->create_lvm_lv("normal2", LvType::NORMAL, 6 * MiB);
// one extent (4 MiB per default) for metadata per PV
BOOST_CHECK_EQUAL(lvm_vg->get_size(), 1 * TiB - 4 * MiB);
BOOST_CHECK_EQUAL(normal1->get_size(), 1 * GiB);
BOOST_CHECK_EQUAL(normal2->get_size(), 4 * MiB);
BOOST_CHECK_THROW(lvm_vg->set_extent_size(48 * MiB), InvalidExtentSize);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
using namespace std;
int main() {
short int cResult = (8*2) + 7 + 1;
cout << cResult;
return 0;
}
<commit_msg>Second step: header file inclusive<commit_after>#include <iostream>
#include <math.h>
// Functions inclusive:
#include <new-feature.h>
// End.
using namespace std;
int main() {
short int cResult = (8*2) + 7 + 1;
cout << cResult;
return 0;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include "SpMP/CSR.hpp"
#include "CSR_Interface.h"
using namespace std;
using namespace SpMP;
// w = (alpha*A*x + beta*y + gamma)*z
template<class T, bool HAS_VALUE = true, bool HAS_Z = false>
static void SpMV_(
int m,
T *w,
T alpha,
const int *rowptr, const int *colidx, const T* values,
const T *x,
T beta,
const T *y,
T gamma,
const T *z)
{
assert(w != x);
int base = rowptr[0];
rowptr -= base;
colidx -= base;
if (values) values -= base;
w -= base;
x -= base;
if (y) y -= base;
if (z) z -= base;
//#define MEASURE_LOAD_BALANCE
#ifdef MEASURE_LOAD_BALANCE
double barrierTimes[omp_get_max_threads()];
double tBegin = omp_get_wtime();
#endif
#pragma omp parallel
{
int iBegin, iEnd;
getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, m);
iBegin += base;
iEnd += base;
if (1 == alpha) {
if (0 == beta) {
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = gamma;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
else {
// alpha == 1 && beta != 0
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = beta*y[i];
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = beta*y[i] + gamma;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
}
else {
// alpha != 1
if (0 == beta) {
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum *= alpha;
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = gamma;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum *= alpha;
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
else {
// alpha != 1 && beta != 0
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = beta*y[i];
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum *= alpha;
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = beta*y[i] + gamma;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (values) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum *= alpha;
if (z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
} // alpha != 1
#ifdef MEASURE_LOAD_BALANCE
double t = omp_get_wtime();
#pragma omp barrier
barrierTimes[tid] = omp_get_wtime() - t;
#pragma omp barrier
#pragma omp master
{
double tEnd = omp_get_wtime();
double barrierTimeSum = 0;
for (int i = 0; i < nthreads; ++i) {
barrierTimeSum += barrierTimes[i];
}
printf("%f load imbalance = %f\n", tEnd - tBegin, barrierTimeSum/(tEnd - tBegin)/nthreads);
}
#undef MEASURE_LOAD_BALANCE
#endif // MEASURE_LOAD_BALANCE
} // omp parallel
}
void multiplyWithVector(
double *w,
double alpha, const CSR *A, const double *x,
double beta, const double *y,
double gamma,
const double *z)
{
if (A->values) {
if (z) {
SpMV_<double, true, true>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
else {
SpMV_<double, true, false>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
}
else {
if (z) {
SpMV_<double, false, true>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
else {
SpMV_<double, false, false>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
}
}
extern "C" {
void CSR_MultiplyWithVector(
double *w,
double alpha, const CSR_Handle *A, const double *x,
double beta, const double *y,
double gamma,
const double *z)
{
multiplyWithVector(w, alpha, (CSR *)A, x, beta, y, gamma, z);
}
void CSR_MultiplyWithDenseMatrix(
double *W, int k, int wRowStride, int wColumnStride,
double alpha, const CSR_Handle *A,
const double *X, int xRowStride, int xColumnStride,
double beta, const double *Y, int yRowStride, int yColumnStride,
double gamma)
{
((CSR *)A)->multiplyWithDenseMatrix(
W, k, wRowStride, wColumnStride,
alpha,
X, xRowStride, xColumnStride,
beta, Y, yRowStride, yColumnStride,
gamma);
}
} // extern "C"
<commit_msg>bug fix<commit_after>#include <algorithm>
#include "SpMP/CSR.hpp"
#include "CSR_Interface.h"
using namespace std;
using namespace SpMP;
// w = (alpha*A*x + beta*y + gamma)*z
template<class T, bool HAS_VALUE = true, bool HAS_Z = false>
static void SpMV_(
int m,
T *w,
T alpha,
const int *rowptr, const int *colidx, const T* values,
const T *x,
T beta,
const T *y,
T gamma,
const T *z)
{
assert(w != x);
int base = rowptr[0];
rowptr -= base;
colidx -= base;
if (values) values -= base;
w -= base;
x -= base;
if (y) y -= base;
if (z) z -= base;
//#define MEASURE_LOAD_BALANCE
#ifdef MEASURE_LOAD_BALANCE
double barrierTimes[omp_get_max_threads()];
double tBegin = omp_get_wtime();
#endif
#pragma omp parallel
{
int iBegin, iEnd;
getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, m);
iBegin += base;
iEnd += base;
if (1 == alpha) {
if (0 == beta) {
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum += gamma;
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
else {
// alpha == 1 && beta != 0
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum += beta*y[i];
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum += beta*y[i] + gamma;
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
}
else {
// alpha != 1
if (0 == beta) {
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum *= alpha;
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum = alpha*sum + beta*y[i];
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
else {
// alpha != 1 && beta != 0
if (0 == gamma) {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum = alpha*sum + beta*y[i];
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
else {
for (int i = iBegin; i < iEnd; ++i) {
T sum = 0;
for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
if (HAS_VALUE) {
sum += values[j]*x[colidx[j]];
}
else {
sum += x[colidx[j]];
}
}
sum = alpha*sum + beta*y[i] + gamma;
if (HAS_Z) w[i] = z[i]*sum;
else w[i] = sum;
}
}
}
} // alpha != 1
#ifdef MEASURE_LOAD_BALANCE
double t = omp_get_wtime();
#pragma omp barrier
barrierTimes[tid] = omp_get_wtime() - t;
#pragma omp barrier
#pragma omp master
{
double tEnd = omp_get_wtime();
double barrierTimeSum = 0;
for (int i = 0; i < nthreads; ++i) {
barrierTimeSum += barrierTimes[i];
}
printf("%f load imbalance = %f\n", tEnd - tBegin, barrierTimeSum/(tEnd - tBegin)/nthreads);
}
#undef MEASURE_LOAD_BALANCE
#endif // MEASURE_LOAD_BALANCE
} // omp parallel
}
void multiplyWithVector(
double *w,
double alpha, const CSR *A, const double *x,
double beta, const double *y,
double gamma,
const double *z)
{
if (A->values) {
if (z) {
SpMV_<double, true, true>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
else {
SpMV_<double, true, false>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
}
else {
if (z) {
SpMV_<double, false, true>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
else {
SpMV_<double, false, false>(
A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
}
}
}
extern "C" {
void CSR_MultiplyWithVector(
double *w,
double alpha, const CSR_Handle *A, const double *x,
double beta, const double *y,
double gamma,
const double *z)
{
multiplyWithVector(w, alpha, (CSR *)A, x, beta, y, gamma, z);
}
void CSR_MultiplyWithDenseMatrix(
double *W, int k, int wRowStride, int wColumnStride,
double alpha, const CSR_Handle *A,
const double *X, int xRowStride, int xColumnStride,
double beta, const double *Y, int yRowStride, int yColumnStride,
double gamma)
{
((CSR *)A)->multiplyWithDenseMatrix(
W, k, wRowStride, wColumnStride,
alpha,
X, xRowStride, xColumnStride,
beta, Y, yRowStride, yColumnStride,
gamma);
}
} // extern "C"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: columninfo.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-04-07 10:51:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef COLUMNINFO_HXX_INCLUDED
#define COLUMNINFO_HXX_INCLUDED
#include <shlobj.h>
class CColumnInfo : public IColumnProvider
{
public:
CColumnInfo(long RefCnt = 1);
virtual ~CColumnInfo();
//-----------------------------
// IUnknown methods
//-----------------------------
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( void);
virtual ULONG STDMETHODCALLTYPE Release( void);
//-----------------------------
// IColumnProvider
//-----------------------------
virtual HRESULT STDMETHODCALLTYPE Initialize(LPCSHCOLUMNINIT psci);
virtual HRESULT STDMETHODCALLTYPE GetColumnInfo(DWORD dwIndex, SHCOLUMNINFO *psci);
virtual HRESULT STDMETHODCALLTYPE GetItemData(
LPCSHCOLUMNID pscid, LPCSHCOLUMNDATA pscd, VARIANT *pvarData);
private:
bool IsOOFileExtension(wchar_t* Extension) const;
private:
long m_RefCnt;
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.122); FILE MERGED 2005/09/05 14:04:41 rt 1.2.122.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: columninfo.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:35:11 $
*
* 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 COLUMNINFO_HXX_INCLUDED
#define COLUMNINFO_HXX_INCLUDED
#include <shlobj.h>
class CColumnInfo : public IColumnProvider
{
public:
CColumnInfo(long RefCnt = 1);
virtual ~CColumnInfo();
//-----------------------------
// IUnknown methods
//-----------------------------
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( void);
virtual ULONG STDMETHODCALLTYPE Release( void);
//-----------------------------
// IColumnProvider
//-----------------------------
virtual HRESULT STDMETHODCALLTYPE Initialize(LPCSHCOLUMNINIT psci);
virtual HRESULT STDMETHODCALLTYPE GetColumnInfo(DWORD dwIndex, SHCOLUMNINFO *psci);
virtual HRESULT STDMETHODCALLTYPE GetItemData(
LPCSHCOLUMNID pscid, LPCSHCOLUMNDATA pscd, VARIANT *pvarData);
private:
bool IsOOFileExtension(wchar_t* Extension) const;
private:
long m_RefCnt;
};
#endif
<|endoftext|> |
<commit_before>/* Copyright 2015 Stanford University, NVIDIA Corporation
*
* 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 "bishop_c.h"
#include "bishop_mapper.h"
#include "legion.h"
#include "legion_c_util.h"
#include "utilities.h"
#include <vector>
#include <set>
#include <cstdlib>
using namespace std;
using namespace LegionRuntime;
using namespace LegionRuntime::HighLevel;
static vector<bishop_task_rule_t> task_rules;
static vector<bishop_region_rule_t> region_rules;
extern Logger::Category log_bishop;
static void
bishop_mapper_registration_callback(Machine machine, Runtime *runtime,
const set<Processor> &local_procs)
{
for (set<Processor>::const_iterator it = local_procs.begin();
it != local_procs.end(); it++)
{
runtime->replace_default_mapper(new BishopMapper(task_rules, region_rules,
machine, runtime, *it),
*it);
}
}
void
register_bishop_mappers(bishop_task_rule_t* _task_rules,
unsigned _num_task_rules,
bishop_region_rule_t* _region_rules,
unsigned _num_region_rules)
{
for (unsigned i = 0; i < _num_task_rules; ++i)
task_rules.push_back(_task_rules[i]);
for (unsigned i = 0; i < _num_region_rules; ++i)
region_rules.push_back(_region_rules[i]);
HighLevelRuntime::set_registration_callback(
bishop_mapper_registration_callback);
}
#define LIST_OP(NAME, TYPE, BASE) \
static TYPE \
bishop_create_##NAME##_list(unsigned size) \
{ \
TYPE l; \
l.size = size; \
if (size > 0) \
l.list = (BASE*)malloc(sizeof(BASE) * size); \
return l; \
} \
void \
bishop_delete_##NAME##_list(TYPE l) \
{ \
if (l.size > 0) free(l.list); \
} \
LIST_OP(processor, bishop_processor_list_t, legion_processor_t)
LIST_OP(memory, bishop_memory_list_t, legion_memory_t)
bishop_processor_list_t
bishop_all_processors()
{
Machine m = Machine::get_machine();
set<Processor> procs;
m.get_all_processors(procs);
bishop_processor_list_t procs_ = bishop_create_processor_list(procs.size());
int idx = 0;
for (set<Processor>::iterator it = procs.begin(); it != procs.end(); ++it)
procs_.list[idx++] = CObjectWrapper::wrap(*it);
return procs_;
}
legion_processor_t
bishop_get_no_processor()
{
return CObjectWrapper::wrap(Processor::NO_PROC);
}
bishop_processor_list_t
bishop_filter_processors_by_isa(bishop_processor_list_t source,
bishop_isa_t isa)
{
vector<legion_processor_t> result;
for (unsigned i = 0; i < source.size; ++i)
{
legion_processor_t proc_ = source.list[i];
Processor proc = CObjectWrapper::unwrap(proc_);
switch (isa)
{
case X86_ISA:
{
if (proc.kind() == Processor::LOC_PROC) result.push_back(proc_);
break;
}
case CUDA_ISA:
{
if (proc.kind() == Processor::TOC_PROC) result.push_back(proc_);
break;
}
}
}
bishop_processor_list_t result_ = bishop_create_processor_list(result.size());
for (unsigned i = 0; i < result.size(); ++i)
result_.list[i] = result[i];
return result_;
}
bishop_memory_list_t
bishop_filter_memories_by_visibility(legion_processor_t proc_)
{
Machine m = Machine::get_machine();
set<Memory> memories;
m.get_all_memories(memories);
bishop_memory_list_t memories_ = bishop_create_memory_list(memories.size());
int idx = 0;
for (set<Memory>::iterator it = memories.begin(); it != memories.end(); ++it)
memories_.list[idx++] = CObjectWrapper::wrap(*it);
return memories_;
}
bishop_memory_list_t
bishop_filter_memories_by_kind(bishop_memory_list_t source,
legion_memory_kind_t kind_)
{
Memory::Kind kind = CObjectWrapper::unwrap(kind_);
vector<legion_memory_t> result;
for (unsigned i = 0; i < source.size; ++i)
{
legion_memory_t memory_ = source.list[i];
Memory memory = CObjectWrapper::unwrap(memory_);
if (memory.kind() == kind) result.push_back(memory_);
}
bishop_memory_list_t result_ = bishop_create_memory_list(result.size());
for (unsigned i = 0; i < result.size(); ++i)
result_.list[i] = result[i];
return result_;
}
bool
bishop_task_set_target_processor(legion_task_t task_, legion_processor_t proc_)
{
Task* task = CObjectWrapper::unwrap(task_);
task->target_proc = CObjectWrapper::unwrap(proc_);
return true;
}
bool
bishop_task_set_target_processor_list(legion_task_t task_,
bishop_processor_list_t list_)
{
if (list_.size > 0)
{
Task* task = CObjectWrapper::unwrap(task_);
task->target_proc = CObjectWrapper::unwrap(list_.list[0]);
for (unsigned i = 1; i < list_.size; ++i)
task->additional_procs.insert(CObjectWrapper::unwrap(list_.list[i]));
return true;
}
else
return false;
}
bool
bishop_region_set_target_memory(legion_region_requirement_t req_,
legion_memory_t memory_)
{
RegionRequirement& req = *CObjectWrapper::unwrap(req_);
req.target_ranking.clear();
req.target_ranking.push_back(CObjectWrapper::unwrap(memory_));
return true;
}
bool
bishop_region_set_target_memory_list(legion_region_requirement_t req_,
bishop_memory_list_t list_)
{
if (list_.size > 0)
{
RegionRequirement& req = *CObjectWrapper::unwrap(req_);
req.target_ranking.clear();
for (unsigned i = 0; i < list_.size; ++i)
req.target_ranking.push_back(CObjectWrapper::unwrap(list_.list[i]));
return true;
}
else
return false;
}
bishop_isa_t
bishop_processor_get_isa(legion_processor_t proc_)
{
Processor proc = CObjectWrapper::unwrap(proc_);
switch (proc.kind())
{
case Processor::LOC_PROC:
{
return X86_ISA;
}
case Processor::TOC_PROC:
{
return CUDA_ISA;
}
default:
{
assert(false);
return X86_ISA; // unreachable
}
}
}
void
bishop_logger_info(const char* msg, ...)
{
va_list args;
va_start(args, msg);
log_bishop.info().vprintf(msg, args);
va_end(args);
}
void
bishop_logger_warning(const char* msg, ...)
{
va_list args;
va_start(args, msg);
log_bishop.warning().vprintf(msg, args);
va_end(args);
}
<commit_msg>bishop: fixing a bug in querying memory objects for a processor<commit_after>/* Copyright 2015 Stanford University, NVIDIA Corporation
*
* 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 "bishop_c.h"
#include "bishop_mapper.h"
#include "legion.h"
#include "legion_c_util.h"
#include "utilities.h"
#include <vector>
#include <set>
#include <cstdlib>
using namespace std;
using namespace LegionRuntime;
using namespace LegionRuntime::HighLevel;
using namespace LegionRuntime::HighLevel::MappingUtilities ;
static vector<bishop_task_rule_t> task_rules;
static vector<bishop_region_rule_t> region_rules;
extern Logger::Category log_bishop;
static void
bishop_mapper_registration_callback(Machine machine, Runtime *runtime,
const set<Processor> &local_procs)
{
for (set<Processor>::const_iterator it = local_procs.begin();
it != local_procs.end(); it++)
{
runtime->replace_default_mapper(new BishopMapper(task_rules, region_rules,
machine, runtime, *it),
*it);
}
}
void
register_bishop_mappers(bishop_task_rule_t* _task_rules,
unsigned _num_task_rules,
bishop_region_rule_t* _region_rules,
unsigned _num_region_rules)
{
for (unsigned i = 0; i < _num_task_rules; ++i)
task_rules.push_back(_task_rules[i]);
for (unsigned i = 0; i < _num_region_rules; ++i)
region_rules.push_back(_region_rules[i]);
HighLevelRuntime::set_registration_callback(
bishop_mapper_registration_callback);
}
#define LIST_OP(NAME, TYPE, BASE) \
static TYPE \
bishop_create_##NAME##_list(unsigned size) \
{ \
TYPE l; \
l.size = size; \
if (size > 0) \
l.list = (BASE*)malloc(sizeof(BASE) * size); \
return l; \
} \
void \
bishop_delete_##NAME##_list(TYPE l) \
{ \
if (l.size > 0) free(l.list); \
} \
LIST_OP(processor, bishop_processor_list_t, legion_processor_t)
LIST_OP(memory, bishop_memory_list_t, legion_memory_t)
bishop_processor_list_t
bishop_all_processors()
{
Machine m = Machine::get_machine();
set<Processor> procs;
m.get_all_processors(procs);
bishop_processor_list_t procs_ = bishop_create_processor_list(procs.size());
int idx = 0;
for (set<Processor>::iterator it = procs.begin(); it != procs.end(); ++it)
procs_.list[idx++] = CObjectWrapper::wrap(*it);
return procs_;
}
legion_processor_t
bishop_get_no_processor()
{
return CObjectWrapper::wrap(Processor::NO_PROC);
}
bishop_processor_list_t
bishop_filter_processors_by_isa(bishop_processor_list_t source,
bishop_isa_t isa)
{
vector<legion_processor_t> result;
for (unsigned i = 0; i < source.size; ++i)
{
legion_processor_t proc_ = source.list[i];
Processor proc = CObjectWrapper::unwrap(proc_);
switch (isa)
{
case X86_ISA:
{
if (proc.kind() == Processor::LOC_PROC) result.push_back(proc_);
break;
}
case CUDA_ISA:
{
if (proc.kind() == Processor::TOC_PROC) result.push_back(proc_);
break;
}
}
}
bishop_processor_list_t result_ = bishop_create_processor_list(result.size());
for (unsigned i = 0; i < result.size(); ++i)
result_.list[i] = result[i];
return result_;
}
bishop_memory_list_t
bishop_filter_memories_by_visibility(legion_processor_t proc_)
{
Machine m = Machine::get_machine();
vector<Memory> memories;
Processor proc = CObjectWrapper::unwrap(proc_);
MachineQueryInterface::find_memory_stack(m, proc, memories,
proc.kind() == Processor::LOC_PROC);
bishop_memory_list_t memories_ = bishop_create_memory_list(memories.size());
int idx = 0;
for (vector<Memory>::iterator it = memories.begin();
it != memories.end(); ++it)
memories_.list[idx++] = CObjectWrapper::wrap(*it);
return memories_;
}
bishop_memory_list_t
bishop_filter_memories_by_kind(bishop_memory_list_t source,
legion_memory_kind_t kind_)
{
Memory::Kind kind = CObjectWrapper::unwrap(kind_);
vector<legion_memory_t> result;
for (unsigned i = 0; i < source.size; ++i)
{
legion_memory_t memory_ = source.list[i];
Memory memory = CObjectWrapper::unwrap(memory_);
if (memory.kind() == kind) result.push_back(memory_);
}
bishop_memory_list_t result_ = bishop_create_memory_list(result.size());
for (unsigned i = 0; i < result.size(); ++i)
result_.list[i] = result[i];
return result_;
}
bool
bishop_task_set_target_processor(legion_task_t task_, legion_processor_t proc_)
{
Task* task = CObjectWrapper::unwrap(task_);
task->target_proc = CObjectWrapper::unwrap(proc_);
return true;
}
bool
bishop_task_set_target_processor_list(legion_task_t task_,
bishop_processor_list_t list_)
{
if (list_.size > 0)
{
Task* task = CObjectWrapper::unwrap(task_);
task->target_proc = CObjectWrapper::unwrap(list_.list[0]);
for (unsigned i = 1; i < list_.size; ++i)
task->additional_procs.insert(CObjectWrapper::unwrap(list_.list[i]));
return true;
}
else
return false;
}
bool
bishop_region_set_target_memory(legion_region_requirement_t req_,
legion_memory_t memory_)
{
RegionRequirement& req = *CObjectWrapper::unwrap(req_);
req.target_ranking.clear();
req.target_ranking.push_back(CObjectWrapper::unwrap(memory_));
return true;
}
bool
bishop_region_set_target_memory_list(legion_region_requirement_t req_,
bishop_memory_list_t list_)
{
if (list_.size > 0)
{
RegionRequirement& req = *CObjectWrapper::unwrap(req_);
req.target_ranking.clear();
for (unsigned i = 0; i < list_.size; ++i)
req.target_ranking.push_back(CObjectWrapper::unwrap(list_.list[i]));
return true;
}
else
return false;
}
bishop_isa_t
bishop_processor_get_isa(legion_processor_t proc_)
{
Processor proc = CObjectWrapper::unwrap(proc_);
switch (proc.kind())
{
case Processor::LOC_PROC:
{
return X86_ISA;
}
case Processor::TOC_PROC:
{
return CUDA_ISA;
}
default:
{
assert(false);
return X86_ISA; // unreachable
}
}
}
void
bishop_logger_info(const char* msg, ...)
{
va_list args;
va_start(args, msg);
log_bishop.info().vprintf(msg, args);
va_end(args);
}
void
bishop_logger_warning(const char* msg, ...)
{
va_list args;
va_start(args, msg);
log_bishop.warning().vprintf(msg, args);
va_end(args);
}
<|endoftext|> |
<commit_before><commit_msg>Enabled glTF samples on Windows<commit_after><|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// 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 other 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 "stdafx.h"
#include "ConsoleLayout.h"
#include <cursespp/Screen.h>
#include <cursespp/IMessage.h>
#include <core/sdk/IPlugin.h>
#include <core/plugin/PluginFactory.h>
#include <app/util/Hotkeys.h>
#include <boost/algorithm/string.hpp>
#define MESSAGE_TYPE_UPDATE 1001
#define UPDATE_INTERVAL_MS 1000
template <class T>
bool tostr(T& t, const std::string& s) {
std::istringstream iss(s);
return !(iss >> t).fail();
}
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::box;
using namespace cursespp;
ConsoleLayout::ConsoleLayout(ITransport& transport, LibraryPtr library)
: LayoutBase()
, transport(transport)
, library(library) {
this->logs.reset(new LogWindow(this));
this->output.reset(new OutputWindow(this));
this->resources.reset(new ResourcesWindow(this));
this->commands.reset(new cursespp::TextInput());
this->shortcuts.reset(new ShortcutsWindow());
this->shortcuts->AddShortcut(Hotkeys::NavigateLibrary, "library");
this->shortcuts->AddShortcut(Hotkeys::NavigateSettings, "settings");
this->shortcuts->AddShortcut("^D", "quit");
this->AddWindow(this->commands);
this->AddWindow(this->logs);
this->AddWindow(this->output);
this->AddWindow(this->resources);
this->AddWindow(this->shortcuts);
this->commands->EnterPressed.connect(this, &ConsoleLayout::OnEnterPressed);
this->Help();
this->PostMessage(MESSAGE_TYPE_UPDATE, 0, 0, UPDATE_INTERVAL_MS);
}
ConsoleLayout::~ConsoleLayout() {
}
void ConsoleLayout::Layout() {
int cx = (int) Screen::GetWidth();
int cy = (int) Screen::GetHeight();
/* this layout */
this->MoveAndResize(0, 0, cx, cy);
this->SetFrameVisible(false);
/* shortcuts at the bottom */
this->shortcuts->MoveAndResize(0, cy - 1, cx, 1);
/* top left */
this->output->MoveAndResize(0, 0, cx / 2, cy - 4);
this->output->SetFocusOrder(1);
/* bottom left */
this->commands->MoveAndResize(0, cy - 4, cx / 2, 3);
this->commands->SetFocusOrder(0);
/* top right */
this->logs->MoveAndResize(cx / 2, 0, cx / 2, cy - 4);
this->logs->SetFocusOrder(2);
/* bottom right */
this->resources->MoveAndResize(cx / 2, cy - 4, cx / 2, 3);
}
void ConsoleLayout::OnEnterPressed(TextInput *input) {
std::string command = this->commands->GetText();
this->commands->SetText("");
output->WriteLine("> " + command + "\n", COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
if (!this->ProcessCommand(command)) {
if (command.size()) {
output->WriteLine(
"illegal command: '" +
command +
"'\n", COLOR_PAIR(CURSESPP_TEXT_ERROR));
}
}
}
void ConsoleLayout::Show() {
LayoutBase::Show();
this->UpdateWindows();
}
void ConsoleLayout::ProcessMessage(IMessage &message) {
if (message.Type() == MESSAGE_TYPE_UPDATE) {
this->UpdateWindows();
this->PostMessage(MESSAGE_TYPE_UPDATE, 0, 0, UPDATE_INTERVAL_MS);
}
}
void ConsoleLayout::UpdateWindows() {
this->logs->Update();
this->resources->Update();
}
void ConsoleLayout::Seek(const std::vector<std::string>& args) {
if (args.size() > 0) {
double newPosition = 0;
if (tostr<double>(newPosition, args[0])) {
transport.SetPosition(newPosition);
}
}
}
void ConsoleLayout::SetVolume(const std::vector<std::string>& args) {
if (args.size() > 0) {
float newVolume = 0;
if (tostr<float>(newVolume, args[0])) {
this->SetVolume(newVolume / 100.0f);
}
}
}
void ConsoleLayout::SetVolume(float volume) {
transport.SetVolume(volume);
}
void ConsoleLayout::Help() {
int64 s = -1;
this->output->WriteLine("help:\n", s);
this->output->WriteLine(" <tab> to switch between windows", s);
this->output->WriteLine("", s);
this->output->WriteLine(" addir <dir> add a music directory", s);
this->output->WriteLine(" rmdir <dir>: remove a music directory", s);
this->output->WriteLine(" lsdirs: list scanned directories", s);
this->output->WriteLine(" rescan: rescan paths for new metadata", s);
this->output->WriteLine("", s);
this->output->WriteLine(" play <uri>: play audio at <uri>", s);
this->output->WriteLine(" pause: pause/resume", s);
this->output->WriteLine(" stop: stop and clean up everything", s);
this->output->WriteLine(" volume: <0 - 100>: set % volume", s);
this->output->WriteLine(" clear: clear the log window", s);
this->output->WriteLine(" seek <seconds>: seek to <seconds> into track", s);
this->output->WriteLine("", s);
this->output->WriteLine(" plugins: list loaded plugins", s);
this->output->WriteLine("", s);
this->output->WriteLine(" <ctrl+d>: quit\n", s);
}
bool ConsoleLayout::ProcessCommand(const std::string& cmd) {
std::vector<std::string> args;
boost::algorithm::split(args, cmd, boost::is_any_of(" "));
auto it = args.begin();
while (it != args.end()) {
std::string trimmed = boost::algorithm::trim_copy(*it);
if (trimmed.size()) {
*it = trimmed;
++it;
}
else {
it = args.erase(it);
}
}
if (args.size() == 0) {
return true;
}
std::string name = args.size() > 0 ? args[0] : "";
args.erase(args.begin());
if (name == "plugins") {
this->ListPlugins();
}
else if (name == "clear") {
this->logs->ClearContents();
}
else if (name == "play" || name == "pl" || name == "p") {
return this->PlayFile(args);
}
else if (name == "addir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->AddPath(path);
}
else if (name == "rmdir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->RemovePath(path);
}
else if (name == "lsdirs") {
std::vector<std::string> paths;
library->Indexer()->GetPaths(paths);
this->output->WriteLine("paths:");
for (size_t i = 0; i < paths.size(); i++) {
this->output->WriteLine(" " + paths.at(i));
}
this->output->WriteLine("");
}
else if (name == "rescan" || name == "scan" || name == "index") {
library->Indexer()->Synchronize();
}
else if (name == "h" || name == "help") {
this->Help();
}
else if (name == "pa" || name == "pause") {
this->Pause();
}
else if (name == "s" || name =="stop") {
this->Stop();
}
else if (name == "sk" || name == "seek") {
this->Seek(args);
}
else if (name == "plugins") {
this->ListPlugins();
}
else if (name == "v" || name == "volume") {
this->SetVolume(args);
}
else {
return false;
}
return true;
}
bool ConsoleLayout::PlayFile(const std::vector<std::string>& args) {
if (args.size() > 0) {
std::string filename = boost::algorithm::join(args, " ");
transport.Start(filename);
return true;
}
return false;
}
void ConsoleLayout::Pause() {
int state = this->transport.GetPlaybackState();
if (state == ITransport::PlaybackPaused) {
this->transport.Resume();
}
else if (state == ITransport::PlaybackPlaying) {
this->transport.Pause();
}
}
void ConsoleLayout::Stop() {
this->transport.Stop();
}
void ConsoleLayout::ListPlugins() const {
using musik::core::IPlugin;
using musik::core::PluginFactory;
typedef std::vector<std::shared_ptr<IPlugin> > PluginList;
typedef PluginFactory::NullDeleter<IPlugin> Deleter;
PluginList plugins = PluginFactory::Instance()
.QueryInterface<IPlugin, Deleter>("GetPlugin");
PluginList::iterator it = plugins.begin();
for (; it != plugins.end(); it++) {
std::string format =
" " + std::string((*it)->Name()) + " "
"v" + std::string((*it)->Version()) + "\n"
" by " + std::string((*it)->Author()) + "\n";
this->output->WriteLine(format, COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
}
}
<commit_msg>Added a missing colon in ConsoleLayout.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// 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 other 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 "stdafx.h"
#include "ConsoleLayout.h"
#include <cursespp/Screen.h>
#include <cursespp/IMessage.h>
#include <core/sdk/IPlugin.h>
#include <core/plugin/PluginFactory.h>
#include <app/util/Hotkeys.h>
#include <boost/algorithm/string.hpp>
#define MESSAGE_TYPE_UPDATE 1001
#define UPDATE_INTERVAL_MS 1000
template <class T>
bool tostr(T& t, const std::string& s) {
std::istringstream iss(s);
return !(iss >> t).fail();
}
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::box;
using namespace cursespp;
ConsoleLayout::ConsoleLayout(ITransport& transport, LibraryPtr library)
: LayoutBase()
, transport(transport)
, library(library) {
this->logs.reset(new LogWindow(this));
this->output.reset(new OutputWindow(this));
this->resources.reset(new ResourcesWindow(this));
this->commands.reset(new cursespp::TextInput());
this->shortcuts.reset(new ShortcutsWindow());
this->shortcuts->AddShortcut(Hotkeys::NavigateLibrary, "library");
this->shortcuts->AddShortcut(Hotkeys::NavigateSettings, "settings");
this->shortcuts->AddShortcut("^D", "quit");
this->AddWindow(this->commands);
this->AddWindow(this->logs);
this->AddWindow(this->output);
this->AddWindow(this->resources);
this->AddWindow(this->shortcuts);
this->commands->EnterPressed.connect(this, &ConsoleLayout::OnEnterPressed);
this->Help();
this->PostMessage(MESSAGE_TYPE_UPDATE, 0, 0, UPDATE_INTERVAL_MS);
}
ConsoleLayout::~ConsoleLayout() {
}
void ConsoleLayout::Layout() {
int cx = (int) Screen::GetWidth();
int cy = (int) Screen::GetHeight();
/* this layout */
this->MoveAndResize(0, 0, cx, cy);
this->SetFrameVisible(false);
/* shortcuts at the bottom */
this->shortcuts->MoveAndResize(0, cy - 1, cx, 1);
/* top left */
this->output->MoveAndResize(0, 0, cx / 2, cy - 4);
this->output->SetFocusOrder(1);
/* bottom left */
this->commands->MoveAndResize(0, cy - 4, cx / 2, 3);
this->commands->SetFocusOrder(0);
/* top right */
this->logs->MoveAndResize(cx / 2, 0, cx / 2, cy - 4);
this->logs->SetFocusOrder(2);
/* bottom right */
this->resources->MoveAndResize(cx / 2, cy - 4, cx / 2, 3);
}
void ConsoleLayout::OnEnterPressed(TextInput *input) {
std::string command = this->commands->GetText();
this->commands->SetText("");
output->WriteLine("> " + command + "\n", COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
if (!this->ProcessCommand(command)) {
if (command.size()) {
output->WriteLine(
"illegal command: '" +
command +
"'\n", COLOR_PAIR(CURSESPP_TEXT_ERROR));
}
}
}
void ConsoleLayout::Show() {
LayoutBase::Show();
this->UpdateWindows();
}
void ConsoleLayout::ProcessMessage(IMessage &message) {
if (message.Type() == MESSAGE_TYPE_UPDATE) {
this->UpdateWindows();
this->PostMessage(MESSAGE_TYPE_UPDATE, 0, 0, UPDATE_INTERVAL_MS);
}
}
void ConsoleLayout::UpdateWindows() {
this->logs->Update();
this->resources->Update();
}
void ConsoleLayout::Seek(const std::vector<std::string>& args) {
if (args.size() > 0) {
double newPosition = 0;
if (tostr<double>(newPosition, args[0])) {
transport.SetPosition(newPosition);
}
}
}
void ConsoleLayout::SetVolume(const std::vector<std::string>& args) {
if (args.size() > 0) {
float newVolume = 0;
if (tostr<float>(newVolume, args[0])) {
this->SetVolume(newVolume / 100.0f);
}
}
}
void ConsoleLayout::SetVolume(float volume) {
transport.SetVolume(volume);
}
void ConsoleLayout::Help() {
int64 s = -1;
this->output->WriteLine("help:\n", s);
this->output->WriteLine(" <tab> to switch between windows", s);
this->output->WriteLine("", s);
this->output->WriteLine(" addir <dir>: add a music directory", s);
this->output->WriteLine(" rmdir <dir>: remove a music directory", s);
this->output->WriteLine(" lsdirs: list scanned directories", s);
this->output->WriteLine(" rescan: rescan paths for new metadata", s);
this->output->WriteLine("", s);
this->output->WriteLine(" play <uri>: play audio at <uri>", s);
this->output->WriteLine(" pause: pause/resume", s);
this->output->WriteLine(" stop: stop and clean up everything", s);
this->output->WriteLine(" volume: <0 - 100>: set % volume", s);
this->output->WriteLine(" clear: clear the log window", s);
this->output->WriteLine(" seek <seconds>: seek to <seconds> into track", s);
this->output->WriteLine("", s);
this->output->WriteLine(" plugins: list loaded plugins", s);
this->output->WriteLine("", s);
this->output->WriteLine(" <ctrl+d>: quit\n", s);
}
bool ConsoleLayout::ProcessCommand(const std::string& cmd) {
std::vector<std::string> args;
boost::algorithm::split(args, cmd, boost::is_any_of(" "));
auto it = args.begin();
while (it != args.end()) {
std::string trimmed = boost::algorithm::trim_copy(*it);
if (trimmed.size()) {
*it = trimmed;
++it;
}
else {
it = args.erase(it);
}
}
if (args.size() == 0) {
return true;
}
std::string name = args.size() > 0 ? args[0] : "";
args.erase(args.begin());
if (name == "plugins") {
this->ListPlugins();
}
else if (name == "clear") {
this->logs->ClearContents();
}
else if (name == "play" || name == "pl" || name == "p") {
return this->PlayFile(args);
}
else if (name == "addir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->AddPath(path);
}
else if (name == "rmdir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->RemovePath(path);
}
else if (name == "lsdirs") {
std::vector<std::string> paths;
library->Indexer()->GetPaths(paths);
this->output->WriteLine("paths:");
for (size_t i = 0; i < paths.size(); i++) {
this->output->WriteLine(" " + paths.at(i));
}
this->output->WriteLine("");
}
else if (name == "rescan" || name == "scan" || name == "index") {
library->Indexer()->Synchronize();
}
else if (name == "h" || name == "help") {
this->Help();
}
else if (name == "pa" || name == "pause") {
this->Pause();
}
else if (name == "s" || name =="stop") {
this->Stop();
}
else if (name == "sk" || name == "seek") {
this->Seek(args);
}
else if (name == "plugins") {
this->ListPlugins();
}
else if (name == "v" || name == "volume") {
this->SetVolume(args);
}
else {
return false;
}
return true;
}
bool ConsoleLayout::PlayFile(const std::vector<std::string>& args) {
if (args.size() > 0) {
std::string filename = boost::algorithm::join(args, " ");
transport.Start(filename);
return true;
}
return false;
}
void ConsoleLayout::Pause() {
int state = this->transport.GetPlaybackState();
if (state == ITransport::PlaybackPaused) {
this->transport.Resume();
}
else if (state == ITransport::PlaybackPlaying) {
this->transport.Pause();
}
}
void ConsoleLayout::Stop() {
this->transport.Stop();
}
void ConsoleLayout::ListPlugins() const {
using musik::core::IPlugin;
using musik::core::PluginFactory;
typedef std::vector<std::shared_ptr<IPlugin> > PluginList;
typedef PluginFactory::NullDeleter<IPlugin> Deleter;
PluginList plugins = PluginFactory::Instance()
.QueryInterface<IPlugin, Deleter>("GetPlugin");
PluginList::iterator it = plugins.begin();
for (; it != plugins.end(); it++) {
std::string format =
" " + std::string((*it)->Name()) + " "
"v" + std::string((*it)->Version()) + "\n"
" by " + std::string((*it)->Author()) + "\n";
this->output->WriteLine(format, COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
}
}
<|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 "abiwidget.h"
#include "abi.h"
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
/*!
\class ProjectExplorer::AbiWidget
\brief The AbiWidget class is a widget to set an ABI.
\sa ProjectExplorer::Abi
*/
namespace ProjectExplorer {
namespace Internal {
// --------------------------------------------------------------------------
// AbiWidgetPrivate:
// --------------------------------------------------------------------------
class AbiWidgetPrivate
{
public:
QComboBox *m_abi;
QComboBox *m_architectureComboBox;
QComboBox *m_osComboBox;
QComboBox *m_osFlavorComboBox;
QComboBox *m_binaryFormatComboBox;
QComboBox *m_wordWidthComboBox;
};
} // namespace Internal
// --------------------------------------------------------------------------
// AbiWidget
// --------------------------------------------------------------------------
AbiWidget::AbiWidget(QWidget *parent) :
QWidget(parent),
d(new Internal::AbiWidgetPrivate)
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(2);
d->m_abi = new QComboBox(this);
layout->addWidget(d->m_abi);
connect(d->m_abi, SIGNAL(currentIndexChanged(int)), this, SLOT(modeChanged()));
d->m_architectureComboBox = new QComboBox(this);
layout->addWidget(d->m_architectureComboBox);
for (int i = 0; i <= static_cast<int>(Abi::UnknownArchitecture); ++i)
d->m_architectureComboBox->addItem(Abi::toString(static_cast<Abi::Architecture>(i)), i);
d->m_architectureComboBox->setCurrentIndex(static_cast<int>(Abi::UnknownArchitecture));
connect(d->m_architectureComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
QLabel *separator1 = new QLabel(this);
separator1->setText(QLatin1String("-"));
separator1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator1);
d->m_osComboBox = new QComboBox(this);
layout->addWidget(d->m_osComboBox);
for (int i = 0; i <= static_cast<int>(Abi::UnknownOS); ++i)
d->m_osComboBox->addItem(Abi::toString(static_cast<Abi::OS>(i)), i);
d->m_osComboBox->setCurrentIndex(static_cast<int>(Abi::UnknownOS));
connect(d->m_osComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(osChanged()));
QLabel *separator2 = new QLabel(this);
separator2->setText(QLatin1String("-"));
separator2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator2);
d->m_osFlavorComboBox = new QComboBox(this);
layout->addWidget(d->m_osFlavorComboBox);
osChanged();
connect(d->m_osFlavorComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
QLabel *separator3 = new QLabel(this);
separator3->setText(QLatin1String("-"));
separator3->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator3);
d->m_binaryFormatComboBox = new QComboBox(this);
layout->addWidget(d->m_binaryFormatComboBox);
for (int i = 0; i <= static_cast<int>(Abi::UnknownFormat); ++i)
d->m_binaryFormatComboBox->addItem(Abi::toString(static_cast<Abi::BinaryFormat>(i)), i);
d->m_binaryFormatComboBox->setCurrentIndex(static_cast<int>(Abi::UnknownFormat));
connect(d->m_binaryFormatComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
QLabel *separator4 = new QLabel(this);
separator4->setText(QLatin1String("-"));
separator4->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator4);
d->m_wordWidthComboBox = new QComboBox(this);
layout->addWidget(d->m_wordWidthComboBox);
d->m_wordWidthComboBox->addItem(Abi::toString(32), 32);
d->m_wordWidthComboBox->addItem(Abi::toString(64), 64);
d->m_wordWidthComboBox->addItem(Abi::toString(0), 0);
d->m_wordWidthComboBox->setCurrentIndex(2);
connect(d->m_wordWidthComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
layout->setStretchFactor(d->m_abi, 1);
setAbis(QList<Abi>(), Abi::hostAbi());
}
AbiWidget::~AbiWidget()
{
delete d;
}
void AbiWidget::setAbis(const QList<Abi> &abiList, const Abi ¤t)
{
blockSignals(true);
d->m_abi->clear();
d->m_abi->addItem(tr("<custom>"), QLatin1String("custom"));
d->m_abi->setCurrentIndex(0);
for (int i = 0; i < abiList.count(); ++i) {
const QString abiString = abiList.at(i).toString();
d->m_abi->addItem(abiString, abiString);
if (abiList.at(i) == current)
d->m_abi->setCurrentIndex(i + 1);
}
d->m_abi->setVisible(!abiList.isEmpty());
if (d->m_abi->currentIndex() == 0) {
if (!current.isValid() && !abiList.isEmpty())
d->m_abi->setCurrentIndex(1); // default to the first Abi if none is selected.
else
setCustomAbi(current);
}
modeChanged();
blockSignals(false);
}
Abi AbiWidget::currentAbi() const
{
if (d->m_abi->currentIndex() > 0)
return Abi(d->m_abi->itemData(d->m_abi->currentIndex()).toString());
return Abi(static_cast<Abi::Architecture>(d->m_architectureComboBox->currentIndex()),
static_cast<Abi::OS>(d->m_osComboBox->currentIndex()),
static_cast<Abi::OSFlavor>(d->m_osFlavorComboBox->itemData(d->m_osFlavorComboBox->currentIndex()).toInt()),
static_cast<Abi::BinaryFormat>(d->m_binaryFormatComboBox->currentIndex()),
d->m_wordWidthComboBox->itemData(d->m_wordWidthComboBox->currentIndex()).toInt());
}
void AbiWidget::osChanged()
{
d->m_osFlavorComboBox->blockSignals(true);
d->m_osFlavorComboBox->clear();
Abi::OS os = static_cast<Abi::OS>(d->m_osComboBox->itemData(d->m_osComboBox->currentIndex()).toInt());
QList<Abi::OSFlavor> flavors = Abi::flavorsForOs(os);
foreach (Abi::OSFlavor f, flavors)
d->m_osFlavorComboBox->addItem(Abi::toString(f), static_cast<int>(f));
d->m_osFlavorComboBox->setCurrentIndex(0); // default to generic flavor
d->m_osFlavorComboBox->blockSignals(false);
emit abiChanged();
}
void AbiWidget::modeChanged()
{
const bool customMode = (d->m_abi->currentIndex() == 0);
d->m_architectureComboBox->setEnabled(customMode);
d->m_osComboBox->setEnabled(customMode);
d->m_osFlavorComboBox->setEnabled(customMode);
d->m_binaryFormatComboBox->setEnabled(customMode);
d->m_wordWidthComboBox->setEnabled(customMode);
if (!customMode) {
Abi current(d->m_abi->itemData(d->m_abi->currentIndex()).toString());
setCustomAbi(current);
}
}
void AbiWidget::setCustomAbi(const Abi ¤t)
{
d->m_architectureComboBox->setCurrentIndex(static_cast<int>(current.architecture()));
d->m_osComboBox->setCurrentIndex(static_cast<int>(current.os()));
osChanged();
for (int i = 0; i < d->m_osFlavorComboBox->count(); ++i) {
if (d->m_osFlavorComboBox->itemData(i).toInt() == current.osFlavor()) {
d->m_osFlavorComboBox->setCurrentIndex(i);
break;
}
}
d->m_binaryFormatComboBox->setCurrentIndex(static_cast<int>(current.binaryFormat()));
for (int i = 0; i < d->m_wordWidthComboBox->count(); ++i) {
if (d->m_wordWidthComboBox->itemData(i).toInt() == current.wordWidth()) {
d->m_wordWidthComboBox->setCurrentIndex(i);
break;
}
}
}
} // namespace ProjectExplorer
<commit_msg>AbiWidget: Use blockSignals properly<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 "abiwidget.h"
#include "abi.h"
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
/*!
\class ProjectExplorer::AbiWidget
\brief The AbiWidget class is a widget to set an ABI.
\sa ProjectExplorer::Abi
*/
namespace ProjectExplorer {
namespace Internal {
// --------------------------------------------------------------------------
// AbiWidgetPrivate:
// --------------------------------------------------------------------------
class AbiWidgetPrivate
{
public:
QComboBox *m_abi;
QComboBox *m_architectureComboBox;
QComboBox *m_osComboBox;
QComboBox *m_osFlavorComboBox;
QComboBox *m_binaryFormatComboBox;
QComboBox *m_wordWidthComboBox;
};
} // namespace Internal
// --------------------------------------------------------------------------
// AbiWidget
// --------------------------------------------------------------------------
AbiWidget::AbiWidget(QWidget *parent) :
QWidget(parent),
d(new Internal::AbiWidgetPrivate)
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(2);
d->m_abi = new QComboBox(this);
layout->addWidget(d->m_abi);
connect(d->m_abi, SIGNAL(currentIndexChanged(int)), this, SLOT(modeChanged()));
d->m_architectureComboBox = new QComboBox(this);
layout->addWidget(d->m_architectureComboBox);
for (int i = 0; i <= static_cast<int>(Abi::UnknownArchitecture); ++i)
d->m_architectureComboBox->addItem(Abi::toString(static_cast<Abi::Architecture>(i)), i);
d->m_architectureComboBox->setCurrentIndex(static_cast<int>(Abi::UnknownArchitecture));
connect(d->m_architectureComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
QLabel *separator1 = new QLabel(this);
separator1->setText(QLatin1String("-"));
separator1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator1);
d->m_osComboBox = new QComboBox(this);
layout->addWidget(d->m_osComboBox);
for (int i = 0; i <= static_cast<int>(Abi::UnknownOS); ++i)
d->m_osComboBox->addItem(Abi::toString(static_cast<Abi::OS>(i)), i);
d->m_osComboBox->setCurrentIndex(static_cast<int>(Abi::UnknownOS));
connect(d->m_osComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(osChanged()));
QLabel *separator2 = new QLabel(this);
separator2->setText(QLatin1String("-"));
separator2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator2);
d->m_osFlavorComboBox = new QComboBox(this);
layout->addWidget(d->m_osFlavorComboBox);
osChanged();
connect(d->m_osFlavorComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
QLabel *separator3 = new QLabel(this);
separator3->setText(QLatin1String("-"));
separator3->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator3);
d->m_binaryFormatComboBox = new QComboBox(this);
layout->addWidget(d->m_binaryFormatComboBox);
for (int i = 0; i <= static_cast<int>(Abi::UnknownFormat); ++i)
d->m_binaryFormatComboBox->addItem(Abi::toString(static_cast<Abi::BinaryFormat>(i)), i);
d->m_binaryFormatComboBox->setCurrentIndex(static_cast<int>(Abi::UnknownFormat));
connect(d->m_binaryFormatComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
QLabel *separator4 = new QLabel(this);
separator4->setText(QLatin1String("-"));
separator4->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(separator4);
d->m_wordWidthComboBox = new QComboBox(this);
layout->addWidget(d->m_wordWidthComboBox);
d->m_wordWidthComboBox->addItem(Abi::toString(32), 32);
d->m_wordWidthComboBox->addItem(Abi::toString(64), 64);
d->m_wordWidthComboBox->addItem(Abi::toString(0), 0);
d->m_wordWidthComboBox->setCurrentIndex(2);
connect(d->m_wordWidthComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(abiChanged()));
layout->setStretchFactor(d->m_abi, 1);
setAbis(QList<Abi>(), Abi::hostAbi());
}
AbiWidget::~AbiWidget()
{
delete d;
}
void AbiWidget::setAbis(const QList<Abi> &abiList, const Abi ¤t)
{
bool blocked = blockSignals(true);
d->m_abi->clear();
d->m_abi->addItem(tr("<custom>"), QLatin1String("custom"));
d->m_abi->setCurrentIndex(0);
for (int i = 0; i < abiList.count(); ++i) {
const QString abiString = abiList.at(i).toString();
d->m_abi->addItem(abiString, abiString);
if (abiList.at(i) == current)
d->m_abi->setCurrentIndex(i + 1);
}
d->m_abi->setVisible(!abiList.isEmpty());
if (d->m_abi->currentIndex() == 0) {
if (!current.isValid() && !abiList.isEmpty())
d->m_abi->setCurrentIndex(1); // default to the first Abi if none is selected.
else
setCustomAbi(current);
}
modeChanged();
blockSignals(blocked);
}
Abi AbiWidget::currentAbi() const
{
if (d->m_abi->currentIndex() > 0)
return Abi(d->m_abi->itemData(d->m_abi->currentIndex()).toString());
return Abi(static_cast<Abi::Architecture>(d->m_architectureComboBox->currentIndex()),
static_cast<Abi::OS>(d->m_osComboBox->currentIndex()),
static_cast<Abi::OSFlavor>(d->m_osFlavorComboBox->itemData(d->m_osFlavorComboBox->currentIndex()).toInt()),
static_cast<Abi::BinaryFormat>(d->m_binaryFormatComboBox->currentIndex()),
d->m_wordWidthComboBox->itemData(d->m_wordWidthComboBox->currentIndex()).toInt());
}
void AbiWidget::osChanged()
{
bool blocked = d->m_osFlavorComboBox->blockSignals(true);
d->m_osFlavorComboBox->clear();
Abi::OS os = static_cast<Abi::OS>(d->m_osComboBox->itemData(d->m_osComboBox->currentIndex()).toInt());
QList<Abi::OSFlavor> flavors = Abi::flavorsForOs(os);
foreach (Abi::OSFlavor f, flavors)
d->m_osFlavorComboBox->addItem(Abi::toString(f), static_cast<int>(f));
d->m_osFlavorComboBox->setCurrentIndex(0); // default to generic flavor
d->m_osFlavorComboBox->blockSignals(blocked);
emit abiChanged();
}
void AbiWidget::modeChanged()
{
const bool customMode = (d->m_abi->currentIndex() == 0);
d->m_architectureComboBox->setEnabled(customMode);
d->m_osComboBox->setEnabled(customMode);
d->m_osFlavorComboBox->setEnabled(customMode);
d->m_binaryFormatComboBox->setEnabled(customMode);
d->m_wordWidthComboBox->setEnabled(customMode);
if (!customMode) {
Abi current(d->m_abi->itemData(d->m_abi->currentIndex()).toString());
setCustomAbi(current);
}
}
void AbiWidget::setCustomAbi(const Abi ¤t)
{
d->m_architectureComboBox->setCurrentIndex(static_cast<int>(current.architecture()));
d->m_osComboBox->setCurrentIndex(static_cast<int>(current.os()));
osChanged();
for (int i = 0; i < d->m_osFlavorComboBox->count(); ++i) {
if (d->m_osFlavorComboBox->itemData(i).toInt() == current.osFlavor()) {
d->m_osFlavorComboBox->setCurrentIndex(i);
break;
}
}
d->m_binaryFormatComboBox->setCurrentIndex(static_cast<int>(current.binaryFormat()));
for (int i = 0; i < d->m_wordWidthComboBox->count(); ++i) {
if (d->m_wordWidthComboBox->itemData(i).toInt() == current.wordWidth()) {
d->m_wordWidthComboBox->setCurrentIndex(i);
break;
}
}
}
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/test/test_server.h"
#include <windows.h>
#include <wincrypt.h>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "base/win/scoped_handle.h"
#pragma comment(lib, "crypt32.lib")
namespace {
// Writes |size| bytes to |handle| and sets |*unblocked| to true.
// Used as a crude timeout mechanism by ReadData().
void UnblockPipe(HANDLE handle, DWORD size, bool* unblocked) {
std::string unblock_data(size, '\0');
// Unblock the ReadFile in TestServer::WaitToStart by writing to the pipe.
// Make sure the call succeeded, otherwise we are very likely to hang.
DWORD bytes_written = 0;
LOG(WARNING) << "Timeout reached; unblocking pipe by writing "
<< size << " bytes";
CHECK(WriteFile(handle, unblock_data.data(), size, &bytes_written,
NULL));
CHECK_EQ(size, bytes_written);
*unblocked = true;
}
// Given a file handle, reads into |buffer| until |bytes_max| bytes
// has been read or an error has been encountered. Returns
// true if the read was successful.
bool ReadData(HANDLE read_fd, HANDLE write_fd,
DWORD bytes_max, uint8* buffer) {
base::Thread thread("test_server_watcher");
if (!thread.Start())
return false;
// Prepare a timeout in case the server fails to start.
bool unblocked = false;
thread.message_loop()->PostDelayedTask(
FROM_HERE,
NewRunnableFunction(UnblockPipe, write_fd, bytes_max, &unblocked),
TestTimeouts::action_timeout_ms());
DWORD bytes_read = 0;
while (bytes_read < bytes_max) {
DWORD num_bytes;
if (!ReadFile(read_fd, buffer + bytes_read, bytes_max - bytes_read,
&num_bytes, NULL)) {
PLOG(ERROR) << "ReadFile failed";
return false;
}
if (num_bytes <= 0) {
LOG(ERROR) << "ReadFile returned invalid byte count: " << num_bytes;
return false;
}
bytes_read += num_bytes;
}
thread.Stop();
// If the timeout kicked in, abort.
if (unblocked) {
LOG(ERROR) << "Timeout exceeded for ReadData";
return false;
}
return true;
}
} // namespace
namespace net {
bool TestServer::LaunchPython(const FilePath& testserver_path) {
FilePath python_exe;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &python_exe))
return false;
python_exe = python_exe
.Append(FILE_PATH_LITERAL("third_party"))
.Append(FILE_PATH_LITERAL("python_26"))
.Append(FILE_PATH_LITERAL("python.exe"));
CommandLine python_command(python_exe);
python_command.AppendArgPath(testserver_path);
if (!AddCommandLineArguments(&python_command))
return false;
HANDLE child_read = NULL;
HANDLE child_write = NULL;
if (!CreatePipe(&child_read, &child_write, NULL, 0)) {
PLOG(ERROR) << "Failed to create pipe";
return false;
}
child_read_fd_.Set(child_read);
child_write_fd_.Set(child_write);
// Have the child inherit the write half.
if (!SetHandleInformation(child_write, HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT)) {
PLOG(ERROR) << "Failed to enable pipe inheritance";
return false;
}
// Pass the handle on the command-line. Although HANDLE is a
// pointer, truncating it on 64-bit machines is okay. See
// http://msdn.microsoft.com/en-us/library/aa384203.aspx
//
// "64-bit versions of Windows use 32-bit handles for
// interoperability. When sharing a handle between 32-bit and 64-bit
// applications, only the lower 32 bits are significant, so it is
// safe to truncate the handle (when passing it from 64-bit to
// 32-bit) or sign-extend the handle (when passing it from 32-bit to
// 64-bit)."
python_command.AppendArg("--startup-pipe=" +
base::IntToString(reinterpret_cast<uintptr_t>(child_write)));
job_handle_.Set(CreateJobObject(NULL, NULL));
if (!job_handle_.IsValid()) {
LOG(ERROR) << "Could not create JobObject.";
return false;
}
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0};
limit_info.BasicLimitInformation.LimitFlags =
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (0 == SetInformationJobObject(job_handle_.Get(),
JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info))) {
LOG(ERROR) << "Could not SetInformationJobObject.";
return false;
}
base::LaunchOptions launch_options;
launch_options.inherit_handles = true;
launch_options.job_handle = job_handle_.Get();
if (!base::LaunchProcess(python_command, launch_options, &process_handle_)) {
LOG(ERROR) << "Failed to launch " << python_command.GetCommandLineString();
return false;
}
return true;
}
bool TestServer::WaitToStart() {
base::win::ScopedHandle read_fd(child_read_fd_.Take());
base::win::ScopedHandle write_fd(child_write_fd_.Take());
uint32 server_data_len = 0;
if (!ReadData(read_fd.Get(), write_fd.Get(), sizeof(server_data_len),
reinterpret_cast<uint8*>(&server_data_len))) {
LOG(ERROR) << "Could not read server_data_len";
return false;
}
std::string server_data(server_data_len, '\0');
if (!ReadData(read_fd.Get(), write_fd.Get(), server_data_len,
reinterpret_cast<uint8*>(&server_data[0]))) {
LOG(ERROR) << "Could not read server_data (" << server_data_len
<< " bytes)";
return false;
}
if (!ParseServerData(server_data)) {
LOG(ERROR) << "Could not parse server_data: " << server_data;
return false;
}
return true;
}
} // namespace net
<commit_msg>Force test server to crash if it times out on launch.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/test/test_server.h"
#include <windows.h>
#include <wincrypt.h>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "base/win/scoped_handle.h"
#pragma comment(lib, "crypt32.lib")
namespace {
// Writes |size| bytes to |handle| and sets |*unblocked| to true.
// Used as a crude timeout mechanism by ReadData().
void UnblockPipe(HANDLE handle, DWORD size, bool* unblocked) {
std::string unblock_data(size, '\0');
// Unblock the ReadFile in TestServer::WaitToStart by writing to the pipe.
// Make sure the call succeeded, otherwise we are very likely to hang.
DWORD bytes_written = 0;
LOG(WARNING) << "Timeout reached; unblocking pipe by writing "
<< size << " bytes";
CHECK(WriteFile(handle, unblock_data.data(), size, &bytes_written,
NULL));
CHECK_EQ(size, bytes_written);
*unblocked = true;
}
// Given a file handle, reads into |buffer| until |bytes_max| bytes
// has been read or an error has been encountered. Returns
// true if the read was successful.
bool ReadData(HANDLE read_fd, HANDLE write_fd,
DWORD bytes_max, uint8* buffer) {
base::Thread thread("test_server_watcher");
if (!thread.Start())
return false;
// Prepare a timeout in case the server fails to start.
bool unblocked = false;
thread.message_loop()->PostDelayedTask(
FROM_HERE,
NewRunnableFunction(UnblockPipe, write_fd, bytes_max, &unblocked),
TestTimeouts::action_timeout_ms());
DWORD bytes_read = 0;
while (bytes_read < bytes_max) {
DWORD num_bytes;
if (!ReadFile(read_fd, buffer + bytes_read, bytes_max - bytes_read,
&num_bytes, NULL)) {
PLOG(ERROR) << "ReadFile failed";
return false;
}
if (num_bytes <= 0) {
LOG(ERROR) << "ReadFile returned invalid byte count: " << num_bytes;
return false;
}
bytes_read += num_bytes;
}
thread.Stop();
// If the timeout kicked in, abort.
if (unblocked) {
LOG(ERROR) << "Timeout exceeded for ReadData";
return false;
}
return true;
}
} // namespace
namespace net {
bool TestServer::LaunchPython(const FilePath& testserver_path) {
FilePath python_exe;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &python_exe))
return false;
python_exe = python_exe
.Append(FILE_PATH_LITERAL("third_party"))
.Append(FILE_PATH_LITERAL("python_26"))
.Append(FILE_PATH_LITERAL("python.exe"));
CommandLine python_command(python_exe);
python_command.AppendArgPath(testserver_path);
if (!AddCommandLineArguments(&python_command))
return false;
HANDLE child_read = NULL;
HANDLE child_write = NULL;
if (!CreatePipe(&child_read, &child_write, NULL, 0)) {
PLOG(ERROR) << "Failed to create pipe";
return false;
}
child_read_fd_.Set(child_read);
child_write_fd_.Set(child_write);
// Have the child inherit the write half.
if (!SetHandleInformation(child_write, HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT)) {
PLOG(ERROR) << "Failed to enable pipe inheritance";
return false;
}
// Pass the handle on the command-line. Although HANDLE is a
// pointer, truncating it on 64-bit machines is okay. See
// http://msdn.microsoft.com/en-us/library/aa384203.aspx
//
// "64-bit versions of Windows use 32-bit handles for
// interoperability. When sharing a handle between 32-bit and 64-bit
// applications, only the lower 32 bits are significant, so it is
// safe to truncate the handle (when passing it from 64-bit to
// 32-bit) or sign-extend the handle (when passing it from 32-bit to
// 64-bit)."
python_command.AppendArg("--startup-pipe=" +
base::IntToString(reinterpret_cast<uintptr_t>(child_write)));
job_handle_.Set(CreateJobObject(NULL, NULL));
if (!job_handle_.IsValid()) {
LOG(ERROR) << "Could not create JobObject.";
return false;
}
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0};
limit_info.BasicLimitInformation.LimitFlags =
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (0 == SetInformationJobObject(job_handle_.Get(),
JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info))) {
LOG(ERROR) << "Could not SetInformationJobObject.";
return false;
}
base::LaunchOptions launch_options;
launch_options.inherit_handles = true;
launch_options.job_handle = job_handle_.Get();
if (!base::LaunchProcess(python_command, launch_options, &process_handle_)) {
LOG(ERROR) << "Failed to launch " << python_command.GetCommandLineString();
return false;
}
return true;
}
bool TestServer::WaitToStart() {
base::win::ScopedHandle read_fd(child_read_fd_.Take());
base::win::ScopedHandle write_fd(child_write_fd_.Take());
uint32 server_data_len = 0;
if (!ReadData(read_fd.Get(), write_fd.Get(), sizeof(server_data_len),
reinterpret_cast<uint8*>(&server_data_len))) {
LOG(ERROR) << "Could not read server_data_len";
DebugBreakProcess(process_handle_);
return false;
}
std::string server_data(server_data_len, '\0');
if (!ReadData(read_fd.Get(), write_fd.Get(), server_data_len,
reinterpret_cast<uint8*>(&server_data[0]))) {
LOG(ERROR) << "Could not read server_data (" << server_data_len
<< " bytes)";
return false;
}
if (!ParseServerData(server_data)) {
LOG(ERROR) << "Could not parse server_data: " << server_data;
return false;
}
return true;
}
} // namespace net
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/optimizer/initializer.h"
#include "core/optimizer/layer_norm_fusion.h"
#include "core/graph/graph_utils.h"
#include "float.h"
#include <deque>
using namespace ONNX_NAMESPACE;
using namespace onnxruntime::common;
namespace onnxruntime {
// LayerNorm supports limited data types.
static std::vector<std::string> supported_data_types{"tensor(float16)", "tensor(float)", "tensor(double)"};
static bool IsSupportedDataType(const Node& node) {
for (const auto& input_arg : node.InputDefs()) {
if (std::find(supported_data_types.begin(), supported_data_types.end(),
*(input_arg->Type())) == supported_data_types.end()) {
return false;
}
}
return true;
}
/**
Layer Normalization will fuse LayerNormalization into one node :
+---------------------+
| |
| v
X --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
| ^
| |
+-----------------------------------------------+
It also handles cases of duplicated sub nodes exported from older version of PyTorch :
+---------------------+
| v
| +-------> Sub ---------------------------------------------+
| | |
| | v
X --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
| ^
| |
+---------------------+
*/
Status LayerNormFusion::ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const {
GraphViewer graph_viewer(graph);
const auto& node_topology_list = graph_viewer.GetNodesInTopologicalOrder();
std::vector<std::reference_wrapper<Node>> nodes_to_remove;
for (auto node_index : node_topology_list) {
nodes_to_remove.clear();
auto* p_reduce_mean = graph.GetNode(node_index);
if (p_reduce_mean == nullptr)
continue; // we removed the node as part of an earlier fusion
Node& reduce_mean_node = *p_reduce_mean;
ORT_RETURN_IF_ERROR(Recurse(reduce_mean_node, modified, graph_level, logger));
if (!graph_utils::IsSupportedOptypeVersionAndDomain(reduce_mean_node, "ReduceMean", {1, 11}) ||
!graph_utils::IsSupportedProvider(reduce_mean_node, GetCompatibleExecutionProviders()) ||
(reduce_mean_node.GetOutputEdgesCount() != 1 && reduce_mean_node.GetOutputEdgesCount() != 2) ||
!IsSupportedDataType(reduce_mean_node)) {
continue;
}
nodes_to_remove.push_back(reduce_mean_node);
// Loop through the children of current "ReduceMean" node. See if they match ["Sub"] or ["Sub", "Sub"]
int subCnt = 0;
const Node* p_sub_node = nullptr;
const Node* p_sub_node_dup = nullptr;
for (auto iter = reduce_mean_node.OutputNodesBegin(); iter != reduce_mean_node.OutputNodesEnd(); ++iter) {
if ((*iter).OpType().compare("Sub") == 0) {
if (subCnt == 0) {
p_sub_node = &(*iter);
} else {
p_sub_node_dup = &(*iter);
}
subCnt++;
} else {
// doesn't match layer norm pattern. break.
subCnt = -1;
break;
}
}
if (subCnt != 1 && subCnt != 2) {
continue;
}
Node& sub_node = *graph.GetNode(p_sub_node->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sub_node, "Sub", {7}) ||
sub_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(sub_node)) {
continue;
}
nodes_to_remove.push_back(sub_node);
// Find the "Div" node after "Sub".
const Node* p_div = nullptr;
p_div = graph_utils::FirstChildByType(sub_node, "Div");
// Find the sub_dup node if exist
if (p_sub_node_dup != nullptr) {
Node& sub_node_dup = *graph.GetNode(p_sub_node_dup->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sub_node_dup, "Sub", {7}) ||
sub_node_dup.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
sub_node_dup.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(sub_node_dup)) {
continue;
}
nodes_to_remove.push_back(sub_node_dup);
// Find Div node after the duplicated sub node if it's not found after the first sub node.
if (p_div == nullptr) {
p_div = graph_utils::FirstChildByType(sub_node_dup, "Div");
}
}
if (p_div == nullptr) {
continue;
}
Node& div_node = *graph.GetNode(p_div->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(div_node, "Div", {7}) ||
div_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
div_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(div_node)) {
continue;
}
nodes_to_remove.push_back(div_node);
// Traceback the div node to find sqrt --> div
const Node* p_sqrt = graph_utils::FirstParentByType(div_node, "Sqrt");
if (p_sqrt == nullptr) {
continue;
}
Node& sqrt_node = *graph.GetNode(p_sqrt->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sqrt_node, "Sqrt", {6}) ||
sqrt_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
sqrt_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(sqrt_node) ||
sqrt_node.GetInputEdgesCount() == 0) {
continue;
}
nodes_to_remove.push_back(sqrt_node);
// Traceback the sqrt node to find add --> sqrt
Node& add2_node = *graph.GetNode(sqrt_node.InputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(add2_node, "Add", {7}) ||
add2_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
add2_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(add2_node)) {
continue;
}
nodes_to_remove.push_back(add2_node);
// Traceback the add node to find reduceMean --> add
const Node* p_reduce_mean2 = nullptr;
p_reduce_mean2 = graph_utils::FirstParentByType(add2_node, "ReduceMean");
if (p_reduce_mean2 == nullptr) {
continue;
}
Node& reduce_mean2_node = *graph.GetNode(p_reduce_mean2->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(reduce_mean2_node, "ReduceMean", {1, 11}) ||
reduce_mean2_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
reduce_mean2_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(reduce_mean2_node) ||
reduce_mean2_node.GetInputEdgesCount() == 0) {
continue;
}
nodes_to_remove.push_back(reduce_mean2_node);
// Traceback the reduceMean node to find pow --> reduceMean
Node& pow_node = *graph.GetNode(reduce_mean2_node.InputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(pow_node, "Pow", {7}) ||
pow_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
pow_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(pow_node)) {
continue;
}
nodes_to_remove.push_back(pow_node);
// Traceback the pow node to find sub --> pow
const Node* p_sub2_node = graph_utils::FirstParentByType(pow_node, "Sub");
if (p_sub2_node == nullptr) {
continue;
}
Node& sub2_node = *graph.GetNode(p_sub2_node->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sub2_node, "Sub", {7}) ||
sub2_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(sub2_node)) {
continue;
}
// Traceback the sub node to find reduceMean --> sub
const Node* p_reduce_mean_check = graph_utils::FirstParentByType(sub2_node, "ReduceMean");
// Check if the reduceMean node after traceback is the same node as the reduceMean node from the beginning.
if (p_reduce_mean_check == nullptr || p_reduce_mean_check != &reduce_mean_node) {
continue;
}
// div --> mul
Node& mul_node = *graph.GetNode(div_node.OutputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(mul_node, "Mul", {7}) ||
mul_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(mul_node)) {
continue;
}
nodes_to_remove.push_back(mul_node);
// mul --> add
Node& last_add_node = *graph.GetNode(mul_node.OutputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(last_add_node, "Add", {7}) ||
last_add_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(last_add_node)) {
continue;
}
nodes_to_remove.push_back(last_add_node);
// Get the inputs for the new LayerNormalization node.
NodeArg* scale = nullptr;
NodeArg* bias = nullptr;
for (size_t i = 0; i < mul_node.MutableInputDefs().size(); i++) {
if (graph_utils::NodeArgIsConstant(graph, *(mul_node.MutableInputDefs()[i])) ||
graph_utils::IsGraphInput(graph, mul_node.MutableInputDefs()[i])) {
// Scale must be 1d.
if (mul_node.MutableInputDefs()[i]->Shape()->dim_size() == 1) {
scale = mul_node.MutableInputDefs()[i];
}
}
}
for (size_t i = 0; i < last_add_node.MutableInputDefs().size(); i++) {
if (graph_utils::NodeArgIsConstant(graph, *(last_add_node.MutableInputDefs()[i])) ||
graph_utils::IsGraphInput(graph, last_add_node.MutableInputDefs()[i])) {
// Bias must be 1d.
if (last_add_node.MutableInputDefs()[i]->Shape()->dim_size() == 1) {
bias = last_add_node.MutableInputDefs()[i];
}
}
}
if (scale == nullptr || bias == nullptr) {
continue;
}
// Scale and bias must have the same dimension.
if (scale->Shape()->dim(0).dim_value() != bias->Shape()->dim(0).dim_value()) {
continue;
}
const std::vector<NodeArg*> layer_norm_input_defs{reduce_mean_node.MutableInputDefs()[0], scale, bias};
Node& layer_norm_node = graph.AddNode(graph.GenerateNodeName("LayerNormalization"),
"LayerNormalization",
"fused LayerNorm subgraphs ",
layer_norm_input_defs,
{}, {}, kOnnxDomain);
// Assign provider to this new node. Provider should be same as the provider for old node.
layer_norm_node.SetExecutionProviderType(reduce_mean_node.GetExecutionProviderType());
// move input edges to add (first in list) across to the layer_norm_node.
// move output definitions and output edges from mul_node (last in list) to layer_norm_node.
// remove all the other nodes.
graph_utils::FinalizeNodeFusion(graph, nodes_to_remove, layer_norm_node);
modified = true;
}
return Status::OK();
}
} // namespace onnxruntime
<commit_msg>epsilon attribute for layernormalization fusion (#2639)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/optimizer/initializer.h"
#include "core/optimizer/layer_norm_fusion.h"
#include "core/graph/graph_utils.h"
#include "float.h"
#include <deque>
using namespace ONNX_NAMESPACE;
using namespace onnxruntime::common;
namespace onnxruntime {
// LayerNorm supports limited data types.
static std::vector<std::string> supported_data_types{"tensor(float16)", "tensor(float)", "tensor(double)"};
static bool IsSupportedDataType(const Node& node) {
for (const auto& input_arg : node.InputDefs()) {
if (std::find(supported_data_types.begin(), supported_data_types.end(),
*(input_arg->Type())) == supported_data_types.end()) {
return false;
}
}
return true;
}
/**
Layer Normalization will fuse LayerNormalization into one node :
+---------------------+
| |
| v
X --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
| ^
| |
+-----------------------------------------------+
It also handles cases of duplicated sub nodes exported from older version of PyTorch :
+---------------------+
| v
| +-------> Sub ---------------------------------------------+
| | |
| | v
X --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
| ^
| |
+---------------------+
*/
Status LayerNormFusion::ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const {
GraphViewer graph_viewer(graph);
const auto& node_topology_list = graph_viewer.GetNodesInTopologicalOrder();
std::vector<std::reference_wrapper<Node>> nodes_to_remove;
for (auto node_index : node_topology_list) {
nodes_to_remove.clear();
auto* p_reduce_mean = graph.GetNode(node_index);
if (p_reduce_mean == nullptr)
continue; // we removed the node as part of an earlier fusion
Node& reduce_mean_node = *p_reduce_mean;
ORT_RETURN_IF_ERROR(Recurse(reduce_mean_node, modified, graph_level, logger));
if (!graph_utils::IsSupportedOptypeVersionAndDomain(reduce_mean_node, "ReduceMean", {1, 11}) ||
!graph_utils::IsSupportedProvider(reduce_mean_node, GetCompatibleExecutionProviders()) ||
(reduce_mean_node.GetOutputEdgesCount() != 1 && reduce_mean_node.GetOutputEdgesCount() != 2) ||
!IsSupportedDataType(reduce_mean_node)) {
continue;
}
nodes_to_remove.push_back(reduce_mean_node);
// Loop through the children of current "ReduceMean" node. See if they match ["Sub"] or ["Sub", "Sub"]
int subCnt = 0;
const Node* p_sub_node = nullptr;
const Node* p_sub_node_dup = nullptr;
for (auto iter = reduce_mean_node.OutputNodesBegin(); iter != reduce_mean_node.OutputNodesEnd(); ++iter) {
if ((*iter).OpType().compare("Sub") == 0) {
if (subCnt == 0) {
p_sub_node = &(*iter);
} else {
p_sub_node_dup = &(*iter);
}
subCnt++;
} else {
// doesn't match layer norm pattern. break.
subCnt = -1;
break;
}
}
if (subCnt != 1 && subCnt != 2) {
continue;
}
Node& sub_node = *graph.GetNode(p_sub_node->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sub_node, "Sub", {7}) ||
sub_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(sub_node)) {
continue;
}
nodes_to_remove.push_back(sub_node);
// Find the "Div" node after "Sub".
const Node* p_div = nullptr;
p_div = graph_utils::FirstChildByType(sub_node, "Div");
// Find the sub_dup node if exist
if (p_sub_node_dup != nullptr) {
Node& sub_node_dup = *graph.GetNode(p_sub_node_dup->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sub_node_dup, "Sub", {7}) ||
sub_node_dup.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
sub_node_dup.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(sub_node_dup)) {
continue;
}
nodes_to_remove.push_back(sub_node_dup);
// Find Div node after the duplicated sub node if it's not found after the first sub node.
if (p_div == nullptr) {
p_div = graph_utils::FirstChildByType(sub_node_dup, "Div");
}
}
if (p_div == nullptr) {
continue;
}
Node& div_node = *graph.GetNode(p_div->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(div_node, "Div", {7}) ||
div_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
div_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(div_node)) {
continue;
}
nodes_to_remove.push_back(div_node);
// Traceback the div node to find sqrt --> div
const Node* p_sqrt = graph_utils::FirstParentByType(div_node, "Sqrt");
if (p_sqrt == nullptr) {
continue;
}
Node& sqrt_node = *graph.GetNode(p_sqrt->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sqrt_node, "Sqrt", {6}) ||
sqrt_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
sqrt_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(sqrt_node) ||
sqrt_node.GetInputEdgesCount() == 0) {
continue;
}
nodes_to_remove.push_back(sqrt_node);
// Traceback the sqrt node to find add --> sqrt
Node& add2_node = *graph.GetNode(sqrt_node.InputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(add2_node, "Add", {7}) ||
add2_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
add2_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(add2_node)) {
continue;
}
nodes_to_remove.push_back(add2_node);
// Traceback the add node to find reduceMean --> add
const Node* p_reduce_mean2 = nullptr;
p_reduce_mean2 = graph_utils::FirstParentByType(add2_node, "ReduceMean");
if (p_reduce_mean2 == nullptr) {
continue;
}
Node& reduce_mean2_node = *graph.GetNode(p_reduce_mean2->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(reduce_mean2_node, "ReduceMean", {1, 11}) ||
reduce_mean2_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
reduce_mean2_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(reduce_mean2_node) ||
reduce_mean2_node.GetInputEdgesCount() == 0) {
continue;
}
nodes_to_remove.push_back(reduce_mean2_node);
// Traceback the reduceMean node to find pow --> reduceMean
Node& pow_node = *graph.GetNode(reduce_mean2_node.InputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(pow_node, "Pow", {7}) ||
pow_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
pow_node.GetOutputEdgesCount() != 1 ||
!IsSupportedDataType(pow_node)) {
continue;
}
nodes_to_remove.push_back(pow_node);
// Traceback the pow node to find sub --> pow
const Node* p_sub2_node = graph_utils::FirstParentByType(pow_node, "Sub");
if (p_sub2_node == nullptr) {
continue;
}
Node& sub2_node = *graph.GetNode(p_sub2_node->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(sub2_node, "Sub", {7}) ||
sub2_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(sub2_node)) {
continue;
}
// Traceback the sub node to find reduceMean --> sub
const Node* p_reduce_mean_check = graph_utils::FirstParentByType(sub2_node, "ReduceMean");
// Check if the reduceMean node after traceback is the same node as the reduceMean node from the beginning.
if (p_reduce_mean_check == nullptr || p_reduce_mean_check != &reduce_mean_node) {
continue;
}
// div --> mul
Node& mul_node = *graph.GetNode(div_node.OutputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(mul_node, "Mul", {7}) ||
mul_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(mul_node)) {
continue;
}
nodes_to_remove.push_back(mul_node);
// mul --> add
Node& last_add_node = *graph.GetNode(mul_node.OutputNodesBegin()->Index());
if (!graph_utils::IsSupportedOptypeVersionAndDomain(last_add_node, "Add", {7}) ||
last_add_node.GetExecutionProviderType() != reduce_mean_node.GetExecutionProviderType() ||
!IsSupportedDataType(last_add_node)) {
continue;
}
nodes_to_remove.push_back(last_add_node);
// Get the inputs for the new LayerNormalization node.
NodeArg* scale = nullptr;
NodeArg* bias = nullptr;
for (size_t i = 0; i < mul_node.MutableInputDefs().size(); i++) {
if (graph_utils::NodeArgIsConstant(graph, *(mul_node.MutableInputDefs()[i])) ||
graph_utils::IsGraphInput(graph, mul_node.MutableInputDefs()[i])) {
// Scale must be 1d.
if (mul_node.MutableInputDefs()[i]->Shape()->dim_size() == 1) {
scale = mul_node.MutableInputDefs()[i];
}
}
}
for (size_t i = 0; i < last_add_node.MutableInputDefs().size(); i++) {
if (graph_utils::NodeArgIsConstant(graph, *(last_add_node.MutableInputDefs()[i])) ||
graph_utils::IsGraphInput(graph, last_add_node.MutableInputDefs()[i])) {
// Bias must be 1d.
if (last_add_node.MutableInputDefs()[i]->Shape()->dim_size() == 1) {
bias = last_add_node.MutableInputDefs()[i];
}
}
}
if (scale == nullptr || bias == nullptr) {
continue;
}
// Scale and bias must have the same dimension.
if (scale->Shape()->dim(0).dim_value() != bias->Shape()->dim(0).dim_value()) {
continue;
}
const std::vector<NodeArg*> layer_norm_input_defs{reduce_mean_node.MutableInputDefs()[0], scale, bias};
Node& layer_norm_node = graph.AddNode(graph.GenerateNodeName("LayerNormalization"),
"LayerNormalization",
"fused LayerNorm subgraphs ",
layer_norm_input_defs,
{}, {}, kOnnxDomain);
// Get constant "epsilon" from "Add2" node if available. Else, default value will be used.
const ONNX_NAMESPACE::TensorProto* tensor_proto = graph_utils::GetConstantInitializer(graph, add2_node.MutableInputDefs()[1]->Name());
if (tensor_proto != nullptr) {
if (tensor_proto->data_type() == ONNX_NAMESPACE::TensorProto_DataType_FLOAT) {
const float* val = onnxruntime::make_unique<Initializer>(*tensor_proto)->data<float>();
layer_norm_node.AddAttribute("epsilon", val[0]);
}
}
// Assign provider to this new node. Provider should be same as the provider for old node.
layer_norm_node.SetExecutionProviderType(reduce_mean_node.GetExecutionProviderType());
// move input edges to add (first in list) across to the layer_norm_node.
// move output definitions and output edges from mul_node (last in list) to layer_norm_node.
// remove all the other nodes.
graph_utils::FinalizeNodeFusion(graph, nodes_to_remove, layer_norm_node);
modified = true;
}
return Status::OK();
}
} // namespace onnxruntime
<|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: seriesconverter.hxx,v $
*
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef OOX_DRAWINGML_CHART_SERIESCONVERTER_HXX
#define OOX_DRAWINGML_CHART_SERIESCONVERTER_HXX
#include "oox/drawingml/chart/converterbase.hxx"
#include "oox/drawingml/chart/seriesmodel.hxx"
namespace com { namespace sun { namespace star {
namespace chart2 { class XDataSeries; }
namespace chart2 { namespace data { class XLabeledDataSequence; } }
} } }
namespace oox {
namespace drawingml {
namespace chart {
// #i66858# enable this when Chart2 supports smoothed lines per data series
#define OOX_CHART_SMOOTHED_PER_SERIES 0
// ============================================================================
class ErrorBarConverter : public ConverterBase< ErrorBarModel >
{
public:
explicit ErrorBarConverter( const ConverterRoot& rParent, ErrorBarModel& rModel );
virtual ~ErrorBarConverter();
/** Converts an OOXML errorbar and inserts it into the passed data series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries );
private:
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createLabeledDataSequence( ErrorBarModel::SourceType eSourceType );
};
// ============================================================================
class TrendlineConverter : public ConverterBase< TrendlineModel >
{
public:
explicit TrendlineConverter( const ConverterRoot& rParent, TrendlineModel& rModel );
virtual ~TrendlineConverter();
/** Converts an OOXML trendline and inserts it into the passed data series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries );
};
// ============================================================================
class TypeGroupConverter;
class SeriesConverter;
class DataPointConverter : public ConverterBase< DataPointModel >
{
public:
explicit DataPointConverter( const ConverterRoot& rParent, DataPointModel& rModel );
virtual ~DataPointConverter();
/** Converts settings for a data point in the passed series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries,
const TypeGroupConverter& rTypeGroup,
const SeriesModel& rSeries );
};
// ============================================================================
class SeriesConverter : public ConverterBase< SeriesModel >
{
public:
explicit SeriesConverter( const ConverterRoot& rParent, SeriesModel& rModel );
virtual ~SeriesConverter();
/** Creates a labeled data sequence object from category data link. */
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createCategorySequence( const ::rtl::OUString& rRole );
/** Creates a labeled data sequence object from value data link. */
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createValueSequence( const ::rtl::OUString& rRole );
/** Creates a data series object with initialized source links. */
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >
createDataSeries( const TypeGroupConverter& rTypeGroup );
private:
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createLabeledDataSequence(
SeriesModel::SourceType eSourceType,
const ::rtl::OUString& rRole,
bool bUseTextLabel );
};
// ============================================================================
} // namespace chart
} // namespace drawingml
} // namespace oox
#endif
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.2.6); FILE MERGED 2008/07/04 11:46:55 dr 1.2.6.5: #i10000# resync errors 2008/07/04 11:02:43 dr 1.2.6.4: RESYNC: (1.2-1.3); FILE MERGED 2008/06/26 08:37:57 dr 1.2.6.3: import bubble charts as symbol scatter charts, handle varyColorsByPoint correctly 2008/06/25 14:58:37 dr 1.2.6.2: import chart data point labels and trendline label 2008/05/27 10:40:29 dr 1.2.6.1: joined changes from CWS xmlfilter05<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: seriesconverter.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.
*
************************************************************************/
#ifndef OOX_DRAWINGML_CHART_SERIESCONVERTER_HXX
#define OOX_DRAWINGML_CHART_SERIESCONVERTER_HXX
#include "oox/drawingml/chart/converterbase.hxx"
#include "oox/drawingml/chart/seriesmodel.hxx"
namespace com { namespace sun { namespace star {
namespace chart2 { class XDataSeries; }
namespace chart2 { namespace data { class XLabeledDataSequence; } }
} } }
namespace oox {
namespace drawingml {
namespace chart {
class TypeGroupConverter;
// #i66858# enable this when Chart2 supports smoothed lines per data series
#define OOX_CHART_SMOOTHED_PER_SERIES 0
// ============================================================================
class DataLabelConverter : public ConverterBase< DataLabelModel >
{
public:
explicit DataLabelConverter( const ConverterRoot& rParent, DataLabelModel& rModel );
virtual ~DataLabelConverter();
/** Converts OOXML data label settings for the passed data point. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries,
const TypeGroupConverter& rTypeGroup );
/** Conversion helper for data series and data points. */
static void convertLabelFormatting(
PropertySet& rPropSet,
ObjectFormatter& rFormatter,
const DataLabelModelBase& rDataLabel,
const TypeGroupConverter& rTypeGroup,
bool bDataSeriesLabel );
};
// ============================================================================
class DataLabelsConverter : public ConverterBase< DataLabelsModel >
{
public:
explicit DataLabelsConverter( const ConverterRoot& rParent, DataLabelsModel& rModel );
virtual ~DataLabelsConverter();
/** Converts OOXML data label settings for the passed data series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries,
const TypeGroupConverter& rTypeGroup );
};
// ============================================================================
class ErrorBarConverter : public ConverterBase< ErrorBarModel >
{
public:
explicit ErrorBarConverter( const ConverterRoot& rParent, ErrorBarModel& rModel );
virtual ~ErrorBarConverter();
/** Converts an OOXML errorbar and inserts it into the passed data series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries );
private:
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createLabeledDataSequence( ErrorBarModel::SourceType eSourceType );
};
// ============================================================================
class TrendlineConverter : public ConverterBase< TrendlineModel >
{
public:
explicit TrendlineConverter( const ConverterRoot& rParent, TrendlineModel& rModel );
virtual ~TrendlineConverter();
/** Converts an OOXML trendline and inserts it into the passed data series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries );
};
// ============================================================================
class DataPointConverter : public ConverterBase< DataPointModel >
{
public:
explicit DataPointConverter( const ConverterRoot& rParent, DataPointModel& rModel );
virtual ~DataPointConverter();
/** Converts settings for a data point in the passed series. */
void convertFromModel(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxDataSeries,
const TypeGroupConverter& rTypeGroup,
const SeriesModel& rSeries );
};
// ============================================================================
class SeriesConverter : public ConverterBase< SeriesModel >
{
public:
explicit SeriesConverter( const ConverterRoot& rParent, SeriesModel& rModel );
virtual ~SeriesConverter();
/** Creates a labeled data sequence object from category data link. */
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createCategorySequence( const ::rtl::OUString& rRole );
/** Creates a labeled data sequence object from value data link. */
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createValueSequence( const ::rtl::OUString& rRole );
/** Creates a data series object with initialized source links. */
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >
createDataSeries( const TypeGroupConverter& rTypeGroup, bool bVaryColorsByPoint );
private:
::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
createLabeledDataSequence(
SeriesModel::SourceType eSourceType,
const ::rtl::OUString& rRole,
bool bUseTextLabel );
};
// ============================================================================
} // namespace chart
} // namespace drawingml
} // namespace oox
#endif
<|endoftext|> |
<commit_before>/*! \file
*
* \brief Python exports for the tensor library
* \author Benjamin Pritchard ([email protected])
*/
#include "bpmodule/python_helper/Pybind11.hpp"
#include "bpmodule/tensor/InitFinalize.hpp"
namespace bpmodule {
namespace tensor {
namespace export_python {
PYBIND11_PLUGIN(parallel)
{
pybind11::module m("parallel", "Parallelization stuff");
m.def("Init", Init);
m.def("Finalize", Finalize);
return m.ptr();
}
} // close namespace export_python
} // close namespace tensor
} // close namespace bpmodule
<commit_msg>Fix tensor export<commit_after>/*! \file
*
* \brief Python exports for the tensor library
* \author Benjamin Pritchard ([email protected])
*/
#include "bpmodule/python_helper/Pybind11.hpp"
#include "bpmodule/tensor/InitFinalize.hpp"
namespace bpmodule {
namespace tensor {
namespace export_python {
PYBIND11_PLUGIN(tensor)
{
pybind11::module m("tensor", "Matrix and Tensor classes");
m.def("Init", Init);
m.def("Finalize", Finalize);
return m.ptr();
}
} // close namespace export_python
} // close namespace tensor
} // close namespace bpmodule
<|endoftext|> |
<commit_before>#include "ride/finddlg.h"
#include "ride/wx.h"
#include "ride/generated/ui.h"
#include "ride/wxutils.h"
#include "wx/stc/stc.h"
// based on http://docs.wholetomato.com/default.asp?W193
class FindDlg : public ui::Find {
public:
FindDlg(wxWindow* parent, const wxString& find);
const wxString GetText() const {
return uiFindText->GetValue();
}
const int GetFlags();
wxStyledTextCtrl* GetStc() {
return m_scintilla1;
}
protected:
void OnCancel(wxCommandEvent& event);
void OnOk(wxCommandEvent& event);
};
FindDlg::FindDlg(wxWindow* parent, const wxString& find)
: ui::Find(parent, wxID_ANY)
{
uiFindText->SetValue(find);
uiFindText->SelectAll();
uiFindText->SetFocus();
uiLookIn->Append("Current file");
uiLookIn->Append("This project");
uiLookIn->SetSelection(0);
uiFindTarget->Append("Normal text");
uiFindTarget->Append("Regex");
uiFindTarget->Append("Posix");
uiFindTarget->SetSelection(0);
}
void FindDlg::OnCancel(wxCommandEvent& event) {
EndModal(wxID_CANCEL);
}
void FindDlg::OnOk(wxCommandEvent& event) {
EndModal(wxID_OK);
}
const int FindDlg::GetFlags() {
int ret = 0;
if (uiMatchCase->GetValue()) {
ret |= wxSTC_FIND_MATCHCASE;
}
if (uiMatchWholeWord->GetValue()) {
ret |= wxSTC_FIND_WHOLEWORD;
}
if (uiFindWordStart->GetValue()) {
ret |= wxSTC_FIND_WORDSTART;
}
switch (uiFindTarget->GetSelection()) {
case 0:
break;
case 1:
ret |= wxSTC_FIND_REGEXP;
break;
case 2:
ret |= wxSTC_FIND_POSIX;
break;
default:
assert(false && "invalid selection");
break;
}
return ret;
}
struct FindResult {
FindResult(const wxString& f, const wxString& co, const int l, const int c)
: file(f)
, content(co)
, line_number(l)
, column_number(c)
{
}
wxString file;
wxString content;
int line_number;
int column_number;
};
void FindInFiles(wxStyledTextCtrl* dlg, const wxString& file, const wxString& text, int flags, std::vector<FindResult>* res) {
assert(res);
dlg->LoadFile(file);
int index = -1;
while (true) {
index = dlg->FindText(index+1, dlg->GetLength(), text, flags);
if (index == -1) return;
const int line = dlg->LineFromPosition(index);
const int line_start = dlg->PositionFromLine(line);
res->push_back(FindResult(file, dlg->GetLine(line), line, index-line_start));
}
}
bool ShowFindDlg(wxWindow* parent, const wxString& current_selection, const wxString& current_file, const wxString root_folder, wxStyledTextCtrl* output) {
FindDlg dlg(parent, current_selection);
if (wxID_OK != dlg.ShowModal()) return false;
std::vector<FindResult> results;
// we can't create a styled ctrl so we cheat by having a 0x0 widget on the find dlg
// and use that for searching...
// todo: get the current stc from the main application so we can search in not saved files..
FindInFiles(dlg.GetStc(), current_file, dlg.GetText(), dlg.GetFlags(), &results);
ClearOutput(output);
WriteLine(output, wxString::Format("Searching for %s in %s", dlg.GetText(), current_file));
WriteLine(output, "");
for (auto res : results) {
// try to format the same way rust related error looks like so we can reuse the parser code for both and get some synergy effects
const wxString mess = wxString::Format("%s:%d %d %s", res.file, res.line_number, res.column_number, res.content);
WriteLine(output, mess);
}
// todo: output search result on a search result output pane
return true;
}
<commit_msg>fixed wrong line bug and trimming for compact output<commit_after>#include "ride/finddlg.h"
#include "ride/wx.h"
#include "ride/generated/ui.h"
#include "ride/wxutils.h"
#include "wx/stc/stc.h"
// based on http://docs.wholetomato.com/default.asp?W193
class FindDlg : public ui::Find {
public:
FindDlg(wxWindow* parent, const wxString& find);
const wxString GetText() const {
return uiFindText->GetValue();
}
const int GetFlags();
wxStyledTextCtrl* GetStc() {
return m_scintilla1;
}
protected:
void OnCancel(wxCommandEvent& event);
void OnOk(wxCommandEvent& event);
};
FindDlg::FindDlg(wxWindow* parent, const wxString& find)
: ui::Find(parent, wxID_ANY)
{
uiFindText->SetValue(find);
uiFindText->SelectAll();
uiFindText->SetFocus();
uiLookIn->Append("Current file");
uiLookIn->Append("This project");
uiLookIn->SetSelection(0);
uiFindTarget->Append("Normal text");
uiFindTarget->Append("Regex");
uiFindTarget->Append("Posix");
uiFindTarget->SetSelection(0);
}
void FindDlg::OnCancel(wxCommandEvent& event) {
EndModal(wxID_CANCEL);
}
void FindDlg::OnOk(wxCommandEvent& event) {
EndModal(wxID_OK);
}
const int FindDlg::GetFlags() {
int ret = 0;
if (uiMatchCase->GetValue()) {
ret |= wxSTC_FIND_MATCHCASE;
}
if (uiMatchWholeWord->GetValue()) {
ret |= wxSTC_FIND_WHOLEWORD;
}
if (uiFindWordStart->GetValue()) {
ret |= wxSTC_FIND_WORDSTART;
}
switch (uiFindTarget->GetSelection()) {
case 0:
break;
case 1:
ret |= wxSTC_FIND_REGEXP;
break;
case 2:
ret |= wxSTC_FIND_POSIX;
break;
default:
assert(false && "invalid selection");
break;
}
return ret;
}
struct FindResult {
FindResult(const wxString& f, const wxString& co, const int l, const int c)
: file(f)
, content(co)
, line_number(l)
, column_number(c)
{
}
wxString file;
wxString content;
int line_number;
int column_number;
};
void FindInFiles(wxStyledTextCtrl* dlg, const wxString& file, const wxString& text, int flags, std::vector<FindResult>* res) {
assert(res);
dlg->LoadFile(file);
int index = -1;
while (true) {
index = dlg->FindText(index+1, dlg->GetLength(), text, flags);
if (index == -1) return;
const int line = dlg->LineFromPosition(index);
const int line_start = dlg->PositionFromLine(line);
res->push_back(FindResult(file, dlg->GetLine(line).Trim(true).Trim(false), line+1, index-line_start));
}
}
bool ShowFindDlg(wxWindow* parent, const wxString& current_selection, const wxString& current_file, const wxString root_folder, wxStyledTextCtrl* output) {
FindDlg dlg(parent, current_selection);
if (wxID_OK != dlg.ShowModal()) return false;
std::vector<FindResult> results;
// we can't create a styled ctrl so we cheat by having a 0x0 widget on the find dlg
// and use that for searching...
// todo: get the current stc from the main application so we can search in not saved files..
FindInFiles(dlg.GetStc(), current_file, dlg.GetText(), dlg.GetFlags(), &results);
ClearOutput(output);
WriteLine(output, wxString::Format("Searching for %s in %s", dlg.GetText(), current_file));
WriteLine(output, "");
for (auto res : results) {
// try to format the same way rust related error looks like so we can reuse the parser code for both and get some synergy effects
const wxString mess = wxString::Format("%s:%d %d %s", res.file, res.line_number, res.column_number, res.content);
WriteLine(output, mess);
}
// todo: output search result on a search result output pane
return true;
}
<|endoftext|> |
<commit_before>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bytecode.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/System/Signals.h"
#include "llvm/Config/config.h"
#include "llvm/LinkAllVMCore.h"
#include <fstream>
#include <iostream>
#include <memory>
using namespace llvm;
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
static cl::opt<bool> Fast("fast",
cl::desc("Generate code quickly, potentially sacrificing code quality"));
static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
MArch("march", cl::desc("Architecture to generate code for:"));
static cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
static cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::AssemblyFile),
cl::desc("Choose a file type (not all types are supported by all targets):"),
cl::values(
clEnumValN(TargetMachine::AssemblyFile, "asm",
" Emit an assembly ('.s') file"),
clEnumValN(TargetMachine::ObjectFile, "obj",
" Emit a native object ('.o') file [experimental]"),
clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
" Emit a native dynamic library ('.so') file"),
clEnumValEnd));
cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if ((Len > 2) &&
IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
try {
cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
sys::PrintStackTraceOnErrorSignal();
// Load the module to be compiled...
std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
return 1;
}
Module &mod = *M.get();
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
mod.setTargetTriple(TargetTriple);
// Allocate target machine. First, check whether the user has
// explicitly specified an architecture to compile for.
if (MArch == 0) {
std::string Err;
MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
if (MArch == 0) {
std::cerr << argv[0] << ": error auto-selecting target for module '"
<< Err << "'. Please use the -march option to explicitly "
<< "pick a target.\n";
return 1;
}
}
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MCPU.size() || MAttrs.size()) {
SubtargetFeatures Features;
Features.setCPU(MCPU);
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Build up all of the passes that we want to do to the module...
PassManager Passes;
Passes.add(new TargetData(*Target.getTargetData()));
#ifndef NDEBUG
if(!NoVerify)
Passes.add(createVerifierPass());
#endif
// Figure out where we are going to send the output...
std::ostream *Out = 0;
if (OutputFilename != "") {
if (OutputFilename != "-") {
// Specified an output filename?
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
} else {
Out = &std::cout;
}
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &std::cout;
} else {
OutputFilename = GetFileNameRoot(InputFilename);
switch (FileType) {
case TargetMachine::AssemblyFile:
if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
OutputFilename += ".s";
else
OutputFilename += ".cbe.c";
break;
case TargetMachine::ObjectFile:
OutputFilename += ".o";
break;
case TargetMachine::DynamicLibrary:
OutputFilename += LTDL_SHLIB_EXT;
break;
}
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
delete Out;
return 1;
}
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
}
}
// Ask the target to add backend passes as necessary.
if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< "' does not support generation of this file type!\n";
if (Out != &std::cout) delete Out;
// And the Out file is empty and useless, so remove it now.
sys::Path(OutputFilename).eraseFromDisk();
return 1;
} else {
// Run our queue of passes all at once now, efficiently.
Passes.run(*M.get());
}
// Delete the ostream if it's not a stdout stream
if (Out != &std::cout) delete Out;
return 0;
} catch (const std::string& msg) {
std::cerr << argv[0] << ": " << msg << "\n";
} catch (...) {
std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
}
return 1;
}
<commit_msg>Make sure that both non-asm file types are marked as experimental<commit_after>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bytecode.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/System/Signals.h"
#include "llvm/Config/config.h"
#include "llvm/LinkAllVMCore.h"
#include <fstream>
#include <iostream>
#include <memory>
using namespace llvm;
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
static cl::opt<bool> Fast("fast",
cl::desc("Generate code quickly, potentially sacrificing code quality"));
static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
MArch("march", cl::desc("Architecture to generate code for:"));
static cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
static cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::AssemblyFile),
cl::desc("Choose a file type (not all types are supported by all targets):"),
cl::values(
clEnumValN(TargetMachine::AssemblyFile, "asm",
" Emit an assembly ('.s') file"),
clEnumValN(TargetMachine::ObjectFile, "obj",
" Emit a native object ('.o') file [experimental]"),
clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
" Emit a native dynamic library ('.so') file"
" [experimental]"),
clEnumValEnd));
cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if ((Len > 2) &&
IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
try {
cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
sys::PrintStackTraceOnErrorSignal();
// Load the module to be compiled...
std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
return 1;
}
Module &mod = *M.get();
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
mod.setTargetTriple(TargetTriple);
// Allocate target machine. First, check whether the user has
// explicitly specified an architecture to compile for.
if (MArch == 0) {
std::string Err;
MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
if (MArch == 0) {
std::cerr << argv[0] << ": error auto-selecting target for module '"
<< Err << "'. Please use the -march option to explicitly "
<< "pick a target.\n";
return 1;
}
}
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MCPU.size() || MAttrs.size()) {
SubtargetFeatures Features;
Features.setCPU(MCPU);
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Build up all of the passes that we want to do to the module...
PassManager Passes;
Passes.add(new TargetData(*Target.getTargetData()));
#ifndef NDEBUG
if(!NoVerify)
Passes.add(createVerifierPass());
#endif
// Figure out where we are going to send the output...
std::ostream *Out = 0;
if (OutputFilename != "") {
if (OutputFilename != "-") {
// Specified an output filename?
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
} else {
Out = &std::cout;
}
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &std::cout;
} else {
OutputFilename = GetFileNameRoot(InputFilename);
switch (FileType) {
case TargetMachine::AssemblyFile:
if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
OutputFilename += ".s";
else
OutputFilename += ".cbe.c";
break;
case TargetMachine::ObjectFile:
OutputFilename += ".o";
break;
case TargetMachine::DynamicLibrary:
OutputFilename += LTDL_SHLIB_EXT;
break;
}
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
delete Out;
return 1;
}
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
}
}
// Ask the target to add backend passes as necessary.
if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< "' does not support generation of this file type!\n";
if (Out != &std::cout) delete Out;
// And the Out file is empty and useless, so remove it now.
sys::Path(OutputFilename).eraseFromDisk();
return 1;
} else {
// Run our queue of passes all at once now, efficiently.
Passes.run(*M.get());
}
// Delete the ostream if it's not a stdout stream
if (Out != &std::cout) delete Out;
return 0;
} catch (const std::string& msg) {
std::cerr << argv[0] << ": " << msg << "\n";
} catch (...) {
std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
}
return 1;
}
<|endoftext|> |
<commit_before>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/Sparc.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Instrumentation/TraceValues.h"
#include "llvm/Transforms/LowerAllocations.h"
#include "llvm/Transforms/HoistPHIConstants.h"
#include "llvm/Transforms/PrintModulePass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include <memory>
#include <string>
#include <fstream>
cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");
cl::Flag Force ("f", "Overwrite output files");
cl::Flag DumpAsm ("d", "Print bytecode before native code generation",
cl::Hidden);
cl::Flag DoNotEmitAssembly("noasm", "Do not emit assembly code", cl::Hidden);
cl::Flag TraceBBValues ("trace",
"Trace values at basic block and method exits");
cl::Flag TraceMethodValues("tracem", "Trace values only at method exits");
cl::Flag DebugTrace ("dumptrace",
"output trace code to a <fn>.trace.ll file",
cl::Hidden);
// GetFileNameRoot - Helper function to get the basename of a filename...
static inline string GetFileNameRoot(const string &InputFilename) {
string IFN = InputFilename;
string outputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
//===---------------------------------------------------------------------===//
// GenerateCodeForTarget Pass
//
// Native code generation for a specified target.
//===---------------------------------------------------------------------===//
class GenerateCodeForTarget : public ConcretePass {
TargetMachine &Target;
public:
inline GenerateCodeForTarget(TargetMachine &T) : Target(T) {}
// doPerMethodWork - This method does the actual work of generating code for
// the specified method.
//
bool doPerMethodWorkVirt(Method *M) {
if (!M->isExternal() && Target.compileMethod(M)) {
cerr << "Error compiling " << InputFilename << "!\n";
return true;
}
return false;
}
};
//===---------------------------------------------------------------------===//
// EmitAssembly Pass
//
// Write assembly code to specified output stream
//===---------------------------------------------------------------------===//
class EmitAssembly : public ConcretePass {
const TargetMachine &Target; // Target to compile for
ostream *Out; // Stream to print on
bool DeleteStream; // Delete stream in dtor?
Module *TheMod;
public:
inline EmitAssembly(const TargetMachine &T, ostream *O, bool D)
: Target(T), Out(O), DeleteStream(D) {}
virtual bool doPassInitializationVirt(Module *M) {
TheMod = M;
return false;
}
~EmitAssembly() {
// TODO: This should be performed as a moduleCleanup function, but we don't
// have one yet!
Target.emitAssembly(TheMod, *Out);
if (DeleteStream) delete Out;
}
};
//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
// Allocate a target... in the future this will be controllable on the
// command line.
auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Load the module to be compiled...
auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
cerr << "bytecode didn't read correctly.\n";
return 1;
}
// Build up all of the passes that we want to do to the module...
vector<Pass*> Passes;
// Replace malloc and free instructions with library calls
Passes.push_back(new LowerAllocations(Target.DataLayout));
// Hoist constants out of PHI nodes into predecessor BB's
Passes.push_back(new HoistPHIConstants());
if (TraceBBValues || TraceMethodValues) // If tracing enabled...
// Insert trace code in all methods in the module
Passes.push_back(new InsertTraceCode(TraceBBValues,
TraceBBValues || TraceMethodValues));
if (DebugTrace) { // If Trace Debugging is enabled...
// Then write the module with tracing code out in assembly form
assert(InputFilename != "-" && "files on stdin not supported with tracing");
string traceFileName = GetFileNameRoot(InputFilename) + ".trace.ll";
ostream *os = new ofstream(traceFileName.c_str(),
(Force ? 0 : ios::noreplace)|ios::out);
if (!os->good()) {
cerr << "Error opening " << traceFileName << "!\n";
delete os;
return 1;
}
Passes.push_back(new PrintModulePass("", os, true));
}
// If LLVM dumping after transformations is requested, add it to the pipeline
if (DumpAsm)
Passes.push_back(new PrintModulePass("Method after xformations: \n",&cerr));
// Generate Target code...
Passes.push_back(new GenerateCodeForTarget(Target));
if (!DoNotEmitAssembly) { // If asm output is enabled...
// Figure out where we are going to send the output...
ostream *Out = 0;
if (OutputFilename != "") { // Specified an output filename?
Out = new ofstream(OutputFilename.c_str(),
(Force ? 0 : ios::noreplace)|ios::out);
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &cout;
} else {
string OutputFilename = GetFileNameRoot(InputFilename);
OutputFilename += ".s";
Out = new ofstream(OutputFilename.c_str(),
(Force ? 0 : ios::noreplace)|ios::out);
if (!Out->good()) {
cerr << "Error opening " << OutputFilename << "!\n";
delete Out;
return 1;
}
}
}
// Output assembly language to the .s file
Passes.push_back(new EmitAssembly(Target, Out, Out != &cout));
}
// Run our queue of passes all at once now, efficiently. This form of
// runAllPasses frees the Pass objects after runAllPasses completes.
Pass::runAllPassesAndFree(M.get(), Passes);
return 0;
}
<commit_msg>Convert to new simpler, more powerful pass structure<commit_after>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/Sparc.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Instrumentation/TraceValues.h"
#include "llvm/Transforms/LowerAllocations.h"
#include "llvm/Transforms/HoistPHIConstants.h"
#include "llvm/Transforms/PrintModulePass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include <memory>
#include <string>
#include <fstream>
cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");
cl::Flag Force ("f", "Overwrite output files");
cl::Flag DumpAsm ("d", "Print bytecode before native code generation",
cl::Hidden);
cl::Flag DoNotEmitAssembly("noasm", "Do not emit assembly code", cl::Hidden);
cl::Flag TraceBBValues ("trace",
"Trace values at basic block and method exits");
cl::Flag TraceMethodValues("tracem", "Trace values only at method exits");
cl::Flag DebugTrace ("dumptrace",
"output trace code to a <fn>.trace.ll file",
cl::Hidden);
// GetFileNameRoot - Helper function to get the basename of a filename...
static inline string GetFileNameRoot(const string &InputFilename) {
string IFN = InputFilename;
string outputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
//===---------------------------------------------------------------------===//
// GenerateCodeForTarget Pass
//
// Native code generation for a specified target.
//===---------------------------------------------------------------------===//
class GenerateCodeForTarget : public Pass {
TargetMachine &Target;
public:
inline GenerateCodeForTarget(TargetMachine &T) : Target(T) {}
// doPerMethodWork - This method does the actual work of generating code for
// the specified method.
//
bool doPerMethodWork(Method *M) {
if (!M->isExternal() && Target.compileMethod(M)) {
cerr << "Error compiling " << InputFilename << "!\n";
return true;
}
return false;
}
};
//===---------------------------------------------------------------------===//
// EmitAssembly Pass
//
// Write assembly code to specified output stream
//===---------------------------------------------------------------------===//
class EmitAssembly : public Pass {
const TargetMachine &Target; // Target to compile for
ostream *Out; // Stream to print on
bool DeleteStream; // Delete stream in dtor?
public:
inline EmitAssembly(const TargetMachine &T, ostream *O, bool D)
: Target(T), Out(O), DeleteStream(D) {}
virtual bool doPassFinalization(Module *M) {
// TODO: This should be performed as a moduleCleanup function, but we don't
// have one yet!
Target.emitAssembly(M, *Out);
if (DeleteStream) delete Out;
return false;
}
};
//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
// Allocate a target... in the future this will be controllable on the
// command line.
auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Load the module to be compiled...
auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
cerr << "bytecode didn't read correctly.\n";
return 1;
}
// Build up all of the passes that we want to do to the module...
vector<Pass*> Passes;
// Replace malloc and free instructions with library calls
Passes.push_back(new LowerAllocations(Target.DataLayout));
// Hoist constants out of PHI nodes into predecessor BB's
Passes.push_back(new HoistPHIConstants());
if (TraceBBValues || TraceMethodValues) // If tracing enabled...
// Insert trace code in all methods in the module
Passes.push_back(new InsertTraceCode(TraceBBValues,
TraceBBValues || TraceMethodValues));
if (DebugTrace) { // If Trace Debugging is enabled...
// Then write the module with tracing code out in assembly form
assert(InputFilename != "-" && "files on stdin not supported with tracing");
string traceFileName = GetFileNameRoot(InputFilename) + ".trace.ll";
ostream *os = new ofstream(traceFileName.c_str(),
(Force ? 0 : ios::noreplace)|ios::out);
if (!os->good()) {
cerr << "Error opening " << traceFileName << "!\n";
delete os;
return 1;
}
Passes.push_back(new PrintModulePass("", os, true));
}
// If LLVM dumping after transformations is requested, add it to the pipeline
if (DumpAsm)
Passes.push_back(new PrintModulePass("Method after xformations: \n",&cerr));
// Generate Target code...
Passes.push_back(new GenerateCodeForTarget(Target));
if (!DoNotEmitAssembly) { // If asm output is enabled...
// Figure out where we are going to send the output...
ostream *Out = 0;
if (OutputFilename != "") { // Specified an output filename?
Out = new ofstream(OutputFilename.c_str(),
(Force ? 0 : ios::noreplace)|ios::out);
} else {
if (InputFilename == "-") {
OutputFilename = "-";
Out = &cout;
} else {
string OutputFilename = GetFileNameRoot(InputFilename);
OutputFilename += ".s";
Out = new ofstream(OutputFilename.c_str(),
(Force ? 0 : ios::noreplace)|ios::out);
if (!Out->good()) {
cerr << "Error opening " << OutputFilename << "!\n";
delete Out;
return 1;
}
}
}
// Output assembly language to the .s file
Passes.push_back(new EmitAssembly(Target, Out, Out != &cout));
}
// Run our queue of passes all at once now, efficiently. This form of
// runAllPasses frees the Pass objects after runAllPasses completes.
Pass::runAllPassesAndFree(M.get(), Passes);
return 0;
}
<|endoftext|> |
<commit_before>#include <QtNetwork>
#include <QtWidgets>
#define USER_AGENT "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)" \
"Chrome/55.0.0.0 Safari/537.36 Dobostorta/" GIT_VERSION
#define CONNECTION_NAME "dobostorta-downloader.sock"
class TortaRequestHandler : public QLocalServer {
Q_OBJECT
TortaRequestHandler() {
listen(CONNECTION_NAME);
connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);
}
void newConnection() {
QLocalSocket *sock = nextPendingConnection();
connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);
sock->waitForReadyRead();
QDataStream stream(sock);
QByteArray data;
stream >> data;
emit receivedRequest({data});
}
public:
~TortaRequestHandler() {
close();
}
static TortaRequestHandler *open() {
auto server = new TortaRequestHandler();
if (server->isListening())
return server;
delete server;
return nullptr;
}
static bool request(const QUrl &url) {
QLocalSocket sock;
sock.connectToServer(CONNECTION_NAME);
if (!sock.isValid()) {
qCritical() << tr("Failed to open socket: ") << sock.errorString();
return false;
}
QByteArray block;
QDataStream stream(&block, QIODevice::WriteOnly);
stream << url.toEncoded();
sock.write(block);
sock.waitForBytesWritten();
return true;
}
signals:
void receivedRequest(const QUrl &url);
};
class TortaDownload : public QWidget {
Q_OBJECT
QNetworkReply * const reply;
QVBoxLayout layout;
QProgressBar progress;
QPushButton actionButton;
QPushButton clearButton;
QTimer intervalTimer;
QElapsedTimer elapsedTimer;
void saveTo(const QString &path) {
QFile file(path);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox message(QMessageBox::Critical,
reply->url().toString(),
tr("Failed create %1\n%2").arg(path, file.errorString()),
QMessageBox::Retry | QMessageBox::Abort,
this);
if (message.exec() == QMessageBox::Retry)
saveTo(path);
return;
}
file.write(reply->readAll());
file.close();
}
static QString bytesToKMG(int bytes) {
static const char* units[] = {"B", "KB", "MB", "GB", "TB", "PB", nullptr};
for (int i=0; units[i+1] != nullptr; i++) {
if (bytes < qPow(1024, i + 1)) {
if (qPow(1024, i + 1) / 10 < bytes)
return QString("%1%2")
.arg(static_cast<float>(bytes) / qPow(1024, i + 1), 0, 'f', 1)
.arg(units[i + 1]);
else if (bytes < qPow(1024, i + 1) / 100)
return QString("%1%2")
.arg(static_cast<float>(bytes) / qPow(1024, i), 0, 'f', 1)
.arg(units[i]);
else
return QString("%1%2").arg(bytes / qPow(1024, i), 0, 'f', 0).arg(units[i]);
}
}
return QString("%1PB").arg(bytes / qPow(1024, 5), 0, 'f', 0);
}
void setProgressBarColor(const QColor &color) {
QPalette p;
p.setColor(QPalette::Highlight, color);
progress.setPalette(p);
}
void finished(const QString &filePath) {
if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {
QMessageBox message(QMessageBox::Critical,
reply->url().toString(),
tr("Failed download\n%1").arg(reply->errorString()),
QMessageBox::Retry | QMessageBox::Abort,
this);
if (message.exec() == QMessageBox::Retry)
emit retry();
}
clearButton.show();
intervalTimer.stop();
if (!reply->error()) {
saveTo(filePath);
progress.setFormat(QString("done [%1]").arg(bytesToKMG(progress.maximum())));
setProgressBarColor(Qt::gray);
actionButton.setText("open");
} else {
progress.setFormat(QString("%p% [%1] %2").arg(bytesToKMG(progress.maximum()))
.arg(reply->errorString()));
setProgressBarColor(Qt::darkRed);
actionButton.setText("retry");
}
}
public:
TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)
: QWidget(parent), reply(reply), layout(this), progress(this),
actionButton("cancel", this), clearButton("clear", this) {
setLayout(&layout);
auto horizontal = new QHBoxLayout;
layout.addLayout(horizontal);
auto left = new QVBoxLayout;
horizontal->addLayout(left, 1);
QFileInfo info(filePath);
auto path = new QLabel(info.dir().path() + "/<b>" + info.fileName() + "</b>", this);
path->setWordWrap(true);
left->addWidget(path);
auto url = new QLabel(QString("<a href=\"%1\">%1</a>").arg(reply->url().toString()), this);
url->setOpenExternalLinks(true);
url->setWordWrap(true);
left->addWidget(url);
horizontal->addWidget(&actionButton);
horizontal->addWidget(&clearButton);
clearButton.hide();
connect(&actionButton, &QPushButton::clicked, [this, reply, filePath]{
if (reply->isRunning())
reply->abort();
else if (reply->error())
emit retry();
else
QDesktopServices::openUrl(QUrl("file://" + filePath));
});
connect(&clearButton, &QPushButton::clicked, [this]{ emit clear(); });
progress.setFormat("%p% [%vB / %mB]");
setProgressBarColor(Qt::darkGray);
layout.addWidget(&progress);
connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){
updateProgressFormat();
progress.setRange(0, total);
progress.setValue(received);
});
connect(reply, &QNetworkReply::finished, [this, filePath]{ finished(filePath); });
intervalTimer.setSingleShot(false);
connect(&intervalTimer, &QTimer::timeout, this, &TortaDownload::updateProgressFormat);
intervalTimer.start(1000);
elapsedTimer.start();
}
signals:
void clear();
void retry();
private slots:
void updateProgressFormat() {
const int remain = qMax(
0.0f,
((progress.maximum() * elapsedTimer.elapsed()) / static_cast<float>(progress.value())
- elapsedTimer.elapsed()) / 1000
);
QString remainStr;
if (remain < 60)
remainStr = QString("%1 sec").arg(remain);
else if (remain < 60 * 60)
remainStr = QString("%1' %2\"").arg(remain/60).arg(remain % 60, 2, 'd', 0, '0');
else
remainStr = QString("%1:%2'").arg(remain/60/60).arg(remain/60 % 60, 2, 'd', 0, '0');
progress.setFormat("%p% " + QString("[%1 / %2] %3").arg(bytesToKMG(progress.value()))
.arg(bytesToKMG(progress.maximum()))
.arg(remainStr));
}
};
class TortaDL : public QScrollArea {
Q_OBJECT
QVBoxLayout layout;
QNetworkAccessManager manager;
TortaRequestHandler * const handler;
protected:
void closeEvent(QCloseEvent *e) override {
handler->close();
QWidget::closeEvent(e);
}
public:
TortaDL(TortaRequestHandler *handler) : handler(handler) {
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
layout.setAlignment(Qt::AlignTop);
auto listArea = new QWidget(this);
listArea->setLayout(&layout);
setWidget(listArea);
setWidgetResizable(true);
connect(handler, &TortaRequestHandler::receivedRequest,
[this](const QUrl &url){ startDownload(url); });
}
void startDownload(const QUrl &url, const QString &fname) {
QNetworkRequest request(url);
request.setRawHeader("User-Agent", USER_AGENT);
auto dl = new TortaDownload(widget(), manager.get(request), fname);
layout.addWidget(dl);
connect(dl, &TortaDownload::retry, [this, url, fname]{ startDownload(url, fname); });
connect(dl, &TortaDownload::clear, [this, dl]{
layout.removeWidget(dl);
delete dl;
});
}
bool startDownload(const QUrl &url) {
const QString filter(QMimeDatabase().mimeTypeForFile(url.fileName()).filterString());
const QString path(QFileDialog::getSaveFileName(
this,
tr("Save file"),
QFileInfo(QFileDialog().directory(), url.fileName()).absoluteFilePath(),
filter + tr(";; All files (*)")
));
if (path != "")
startDownload(url, path);
return path != "";
}
};
int main(int argc, char **argv) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
app.setApplicationName("Torta-DL");
app.setApplicationVersion(GIT_VERSION);
QCommandLineParser parser;
parser.addPositionalArgument("URL...", "URL that you want download.");
parser.addHelpOption();
parser.addVersionOption();
parser.process(app.arguments());
if (parser.positionalArguments().empty())
parser.showHelp(-1);
auto handler = TortaRequestHandler::open();
if (handler == nullptr) {
for (auto url: parser.positionalArguments()) {
if (!TortaRequestHandler::request({url}))
return -1;
}
return 0;
}
TortaDL win(handler);
bool started = false;
for (auto url: parser.positionalArguments())
started = started || win.startDownload({url});
if (!started) {
win.close();
return 1;
}
win.show();
return app.exec();
}
#include "main.moc"
<commit_msg>Ensured that can download even if omitting URL scheme<commit_after>#include <QtNetwork>
#include <QtWidgets>
#define USER_AGENT "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)" \
"Chrome/55.0.0.0 Safari/537.36 Dobostorta/" GIT_VERSION
#define CONNECTION_NAME "dobostorta-downloader.sock"
class TortaRequestHandler : public QLocalServer {
Q_OBJECT
TortaRequestHandler() {
listen(CONNECTION_NAME);
connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);
}
void newConnection() {
QLocalSocket *sock = nextPendingConnection();
connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);
sock->waitForReadyRead();
QDataStream stream(sock);
QByteArray data;
stream >> data;
emit receivedRequest({data});
}
public:
~TortaRequestHandler() {
close();
}
static TortaRequestHandler *open() {
auto server = new TortaRequestHandler();
if (server->isListening())
return server;
delete server;
return nullptr;
}
static bool request(const QUrl &url) {
QLocalSocket sock;
sock.connectToServer(CONNECTION_NAME);
if (!sock.isValid()) {
qCritical() << tr("Failed to open socket: ") << sock.errorString();
return false;
}
QByteArray block;
QDataStream stream(&block, QIODevice::WriteOnly);
stream << url.toEncoded();
sock.write(block);
sock.waitForBytesWritten();
return true;
}
signals:
void receivedRequest(const QUrl &url);
};
class TortaDownload : public QWidget {
Q_OBJECT
QNetworkReply * const reply;
QVBoxLayout layout;
QProgressBar progress;
QPushButton actionButton;
QPushButton clearButton;
QTimer intervalTimer;
QElapsedTimer elapsedTimer;
void saveTo(const QString &path) {
QFile file(path);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox message(QMessageBox::Critical,
reply->url().toString(),
tr("Failed create %1\n%2").arg(path, file.errorString()),
QMessageBox::Retry | QMessageBox::Abort,
this);
if (message.exec() == QMessageBox::Retry)
saveTo(path);
return;
}
file.write(reply->readAll());
file.close();
}
static QString bytesToKMG(int bytes) {
static const char* units[] = {"B", "KB", "MB", "GB", "TB", "PB", nullptr};
for (int i=0; units[i+1] != nullptr; i++) {
if (bytes < qPow(1024, i + 1)) {
if (qPow(1024, i + 1) / 10 < bytes)
return QString("%1%2")
.arg(static_cast<float>(bytes) / qPow(1024, i + 1), 0, 'f', 1)
.arg(units[i + 1]);
else if (bytes < qPow(1024, i + 1) / 100)
return QString("%1%2")
.arg(static_cast<float>(bytes) / qPow(1024, i), 0, 'f', 1)
.arg(units[i]);
else
return QString("%1%2").arg(bytes / qPow(1024, i), 0, 'f', 0).arg(units[i]);
}
}
return QString("%1PB").arg(bytes / qPow(1024, 5), 0, 'f', 0);
}
void setProgressBarColor(const QColor &color) {
QPalette p;
p.setColor(QPalette::Highlight, color);
progress.setPalette(p);
}
void finished(const QString &filePath) {
if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {
QMessageBox message(QMessageBox::Critical,
reply->url().toString(),
tr("Failed download\n%1").arg(reply->errorString()),
QMessageBox::Retry | QMessageBox::Abort,
this);
if (message.exec() == QMessageBox::Retry)
emit retry();
}
clearButton.show();
intervalTimer.stop();
if (!reply->error()) {
saveTo(filePath);
progress.setFormat(QString("done [%1]").arg(bytesToKMG(progress.maximum())));
setProgressBarColor(Qt::gray);
actionButton.setText("open");
} else {
progress.setFormat(QString("%p% [%1] %2").arg(bytesToKMG(progress.maximum()))
.arg(reply->errorString()));
setProgressBarColor(Qt::darkRed);
actionButton.setText("retry");
}
}
public:
TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)
: QWidget(parent), reply(reply), layout(this), progress(this),
actionButton("cancel", this), clearButton("clear", this) {
setLayout(&layout);
auto horizontal = new QHBoxLayout;
layout.addLayout(horizontal);
auto left = new QVBoxLayout;
horizontal->addLayout(left, 1);
QFileInfo info(filePath);
auto path = new QLabel(info.dir().path() + "/<b>" + info.fileName() + "</b>", this);
path->setWordWrap(true);
left->addWidget(path);
auto url = new QLabel(QString("<a href=\"%1\">%1</a>").arg(reply->url().toString()), this);
url->setOpenExternalLinks(true);
url->setWordWrap(true);
left->addWidget(url);
horizontal->addWidget(&actionButton);
horizontal->addWidget(&clearButton);
clearButton.hide();
connect(&actionButton, &QPushButton::clicked, [this, reply, filePath]{
if (reply->isRunning())
reply->abort();
else if (reply->error())
emit retry();
else
QDesktopServices::openUrl(QUrl("file://" + filePath));
});
connect(&clearButton, &QPushButton::clicked, [this]{ emit clear(); });
progress.setFormat("%p% [%vB / %mB]");
setProgressBarColor(Qt::darkGray);
layout.addWidget(&progress);
connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){
updateProgressFormat();
progress.setRange(0, total);
progress.setValue(received);
});
connect(reply, &QNetworkReply::finished, [this, filePath]{ finished(filePath); });
intervalTimer.setSingleShot(false);
connect(&intervalTimer, &QTimer::timeout, this, &TortaDownload::updateProgressFormat);
intervalTimer.start(1000);
elapsedTimer.start();
}
signals:
void clear();
void retry();
private slots:
void updateProgressFormat() {
const int remain = qMax(
0.0f,
((progress.maximum() * elapsedTimer.elapsed()) / static_cast<float>(progress.value())
- elapsedTimer.elapsed()) / 1000
);
QString remainStr;
if (remain < 60)
remainStr = QString("%1 sec").arg(remain);
else if (remain < 60 * 60)
remainStr = QString("%1' %2\"").arg(remain/60).arg(remain % 60, 2, 'd', 0, '0');
else
remainStr = QString("%1:%2'").arg(remain/60/60).arg(remain/60 % 60, 2, 'd', 0, '0');
progress.setFormat("%p% " + QString("[%1 / %2] %3").arg(bytesToKMG(progress.value()))
.arg(bytesToKMG(progress.maximum()))
.arg(remainStr));
}
};
class TortaDL : public QScrollArea {
Q_OBJECT
QVBoxLayout layout;
QNetworkAccessManager manager;
TortaRequestHandler * const handler;
protected:
void closeEvent(QCloseEvent *e) override {
handler->close();
QWidget::closeEvent(e);
}
public:
TortaDL(TortaRequestHandler *handler) : handler(handler) {
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
layout.setAlignment(Qt::AlignTop);
auto listArea = new QWidget(this);
listArea->setLayout(&layout);
setWidget(listArea);
setWidgetResizable(true);
connect(handler, &TortaRequestHandler::receivedRequest,
[this](const QUrl &url){ startDownload(url); });
}
void startDownload(QUrl url, const QString &fname) {
if (url.scheme().isEmpty()) {
url = QUrl("http://" + url.toString());
}
QNetworkRequest request(url);
request.setRawHeader("User-Agent", USER_AGENT);
auto dl = new TortaDownload(widget(), manager.get(request), fname);
layout.addWidget(dl);
connect(dl, &TortaDownload::retry, [this, url, fname]{ startDownload(url, fname); });
connect(dl, &TortaDownload::clear, [this, dl]{
layout.removeWidget(dl);
delete dl;
});
}
bool startDownload(const QUrl &url) {
const QString filter(QMimeDatabase().mimeTypeForFile(url.fileName()).filterString());
const QString path(QFileDialog::getSaveFileName(
this,
tr("Save file"),
QFileInfo(QFileDialog().directory(), url.fileName()).absoluteFilePath(),
filter + tr(";; All files (*)")
));
if (path != "")
startDownload(url, path);
return path != "";
}
};
int main(int argc, char **argv) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
app.setApplicationName("Torta-DL");
app.setApplicationVersion(GIT_VERSION);
QCommandLineParser parser;
parser.addPositionalArgument("URL...", "URL that you want download.");
parser.addHelpOption();
parser.addVersionOption();
parser.process(app.arguments());
if (parser.positionalArguments().empty())
parser.showHelp(-1);
auto handler = TortaRequestHandler::open();
if (handler == nullptr) {
for (auto url: parser.positionalArguments()) {
if (!TortaRequestHandler::request({url}))
return -1;
}
return 0;
}
TortaDL win(handler);
bool started = false;
for (auto url: parser.positionalArguments())
started = started || win.startDownload({url});
if (!started) {
win.close();
return 1;
}
win.show();
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ・省電力制御 @n
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "RX24T/system.hpp"
#include "RX24T/peripheral.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 省電力制御クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct power_cfg {
//-----------------------------------------------------------------//
/*!
@brief 周辺機器に切り替える
@param[in] t 周辺機器タイプ
@param[in] ena オフにする場合「false」
*/
//-----------------------------------------------------------------//
static void turn(peripheral t, bool ena = true)
{
bool f = !ena;
switch(t) {
case peripheral::DTC:
SYSTEM::MSTPCRA.MSTPA28 = f;
break;
case peripheral::CMT0:
case peripheral::CMT1:
SYSTEM::MSTPCRA.MSTPA15 = f;
break;
case peripheral::CMT2:
case peripheral::CMT3:
SYSTEM::MSTPCRA.MSTPA14 = f;
break;
case peripheral::RSPI0:
SYSTEM::MSTPCRB.MSTPB17 = f;
break;
case peripheral::RIIC0:
SYSTEM::MSTPCRB.MSTPB21 = f;
break;
case peripheral::SCI1:
SYSTEM::MSTPCRB.MSTPB30 = f;
break;
case peripheral::SCI5:
SYSTEM::MSTPCRB.MSTPB26 = f;
break;
case peripheral::SCI6:
SYSTEM::MSTPCRB.MSTPB25 = f;
break;
case peripheral::S12AD:
SYSTEM::MSTPCRA.MSTPA17 = f;
break;
case peripheral::S12AD1:
SYSTEM::MSTPCRA.MSTPA16 = f;
break;
case peripheral::S12AD2:
SYSTEM::MSTPCRA.MSTPA23 = f;
break;
default:
break;
}
}
};
}
<commit_msg>update A/D<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ・省電力制御 @n
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "RX24T/system.hpp"
#include "RX24T/peripheral.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 省電力制御クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct power_cfg {
//-----------------------------------------------------------------//
/*!
@brief モジュール・ストップ機能を設定
@param[in] t 周辺機器タイプ
@param[in] ena オフにする場合「false」
*/
//-----------------------------------------------------------------//
static void turn(peripheral t, bool ena = true)
{
bool f = !ena;
switch(t) {
case peripheral::DTC:
SYSTEM::MSTPCRA.MSTPA28 = f;
break;
case peripheral::CMT0:
case peripheral::CMT1:
SYSTEM::MSTPCRA.MSTPA15 = f;
break;
case peripheral::CMT2:
case peripheral::CMT3:
SYSTEM::MSTPCRA.MSTPA14 = f;
break;
case peripheral::RSPI0:
SYSTEM::MSTPCRB.MSTPB17 = f;
break;
case peripheral::RIIC0:
SYSTEM::MSTPCRB.MSTPB21 = f;
break;
case peripheral::SCI1:
SYSTEM::MSTPCRB.MSTPB30 = f;
break;
case peripheral::SCI5:
SYSTEM::MSTPCRB.MSTPB26 = f;
break;
case peripheral::SCI6:
SYSTEM::MSTPCRB.MSTPB25 = f;
break;
case peripheral::S12AD:
SYSTEM::MSTPCRA.MSTPA17 = f;
break;
case peripheral::S12AD1:
SYSTEM::MSTPCRA.MSTPA16 = f;
break;
case peripheral::S12AD2:
SYSTEM::MSTPCRA.MSTPA23 = f;
break;
default:
break;
}
}
};
}
<|endoftext|> |
<commit_before>/*
* qiunwrap.cpp
*
* Created by Tobias Wood on 11/06/2015.
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Eigen/Dense"
#include "itkImageSource.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMultiplyImageFilter.h"
#include "itkForwardFFTImageFilter.h"
#include "itkInverseFFTImageFilter.h"
#include "itkFFTPadImageFilter.h"
#include "itkMaskImageFilter.h"
#include "Types.h"
#include "Util.h"
using namespace std;
using namespace Eigen;
namespace itk {
class DiscreteLaplacePhaseFilter : public ImageToImageFilter<QI::ImageF, QI::ImageF> {
protected:
public:
/** Standard class typedefs. */
typedef QI::ImageF TImage;
typedef DiscreteLaplacePhaseFilter Self;
typedef ImageToImageFilter<TImage, TImage> Superclass;
typedef SmartPointer<Self> Pointer;
typedef typename TImage::RegionType RegionType;
itkNewMacro(Self);
itkTypeMacro(DiscreteLaplacePhaseFilter, DiscreteLaplacePhaseFilter);
void SetInput(const TImage *img) override { this->SetNthInput(0, const_cast<TImage*>(img)); }
void SetMask(const TImage *img) { this->SetNthInput(1, const_cast<TImage*>(img)); }
typename TImage::ConstPointer GetInput() const { return static_cast<const TImage *>(this->ProcessObject::GetInput(0)); }
typename TImage::ConstPointer GetMask() const { return static_cast<const TImage *>(this->ProcessObject::GetInput(1)); }
virtual void GenerateOutputInformation() override {
Superclass::GenerateOutputInformation();
auto op = this->GetOutput();
op->SetRegions(this->GetInput()->GetLargestPossibleRegion());
op->Allocate();
}
protected:
DiscreteLaplacePhaseFilter() {
this->SetNumberOfRequiredInputs(1);
this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, this->MakeOutput(0));
}
~DiscreteLaplacePhaseFilter() {}
DataObject::Pointer MakeOutput(unsigned int idx) {
//std::cout << __PRETTY_FUNCTION__ << endl;
if (idx == 0) {
DataObject::Pointer output = (TImage::New()).GetPointer();
return output.GetPointer();
} else {
std::cerr << "No output " << idx << std::endl;
return NULL;
}
}
virtual void ThreadedGenerateData(const RegionType ®ion, ThreadIdType threadId) override {
//std::cout << __PRETTY_FUNCTION__ << endl;
ConstNeighborhoodIterator<TImage>::RadiusType radius;
radius.Fill(1);
ConstNeighborhoodIterator<TImage> inputIter(radius, this->GetInput(), region);
ImageRegionIterator<TImage> outputIter(this->GetOutput(), region);
ImageRegionConstIterator<TImage> maskIter;
const auto mask = this->GetMask();
if (mask) {
maskIter = ImageRegionConstIterator<TImage>(mask, region);
}
vector<ConstNeighborhoodIterator<TImage>::OffsetType> back, fwrd;
back.push_back({{-1, 0, 0}});
fwrd.push_back({{ 1, 0, 0}});
back.push_back({{ 0,-1, 0}});
fwrd.push_back({{ 0, 1, 0}});
back.push_back({{ 0, 0,-1}});
fwrd.push_back({{ 0, 0, 1}});
TImage::SpacingType spacing = this->GetInput()->GetSpacing();
TImage::SpacingType s_sqr = spacing * spacing;
while(!inputIter.IsAtEnd()) {
double sum = 0;
if (!mask || maskIter.Get()) {
double cphase = inputIter.GetCenterPixel();
complex<double> c = std::polar(1., cphase);
for (int i = 0; i < fwrd.size(); ++i) {
double bphase = inputIter.GetPixel(back[i]);
double fphase = inputIter.GetPixel(fwrd[i]);
complex<double> b = std::polar(1., bphase);
complex<double> f = std::polar(1., fphase);
sum += std::arg((f*b)/(c*c)) / s_sqr[i];
}
}
outputIter.Set(sum / 7.);
++inputIter;
++outputIter;
if (mask)
++maskIter;
}
}
private:
DiscreteLaplacePhaseFilter(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
};
class DiscreteInverseLaplace : public ImageSource<QI::ImageF> {
public:
typedef QI::ImageF TImage;
typedef DiscreteInverseLaplace Self;
typedef ImageSource<TImage> Superclass;
typedef SmartPointer<Self> Pointer;
itkNewMacro(Self);
itkTypeMacro(DiscreteInverseLaplace, ImageSource);
void SetImageProperties(const TImage *img) {
m_region = img->GetLargestPossibleRegion();
m_spacing = img->GetSpacing();
m_direction = img->GetDirection();
m_origin = img->GetOrigin();
}
protected:
typename TImage::RegionType m_region;
typename TImage::SpacingType m_spacing;
typename TImage::DirectionType m_direction;
typename TImage::PointType m_origin;
DiscreteInverseLaplace(){}
~DiscreteInverseLaplace(){}
virtual void GenerateData() override {
typename TImage::Pointer output = this->GetOutput();
output->SetRegions(m_region);
output->Allocate();
output->SetSpacing(m_spacing);
output->SetDirection(m_direction);
output->SetOrigin(m_origin);
itk::ImageRegionIteratorWithIndex<TImage> imageIt(output,output->GetLargestPossibleRegion());
imageIt.GoToBegin();
imageIt.Set(0.); // There is a pole here
++imageIt;
while(!imageIt.IsAtEnd()) {
auto index = imageIt.GetIndex() - m_region.GetIndex(); // Might be padded to a negative start
double val = 0;
for (int i = 0; i < 3; i++) {
val += 2. - 2. * cos(index[i] * 2. * M_PI / m_region.GetSize()[i]);
}
val /= 7.;
imageIt.Set(1./val);
++imageIt;
}
}
private:
DiscreteInverseLaplace(const Self &);
void operator=(const Self &);
};
} // End namespace itk
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: qiunwrap [options] input \n\
\n\
Input is a single wrapped phase volume\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print more information.\n\
--out, -o path : Specify an output filename (default image base).\n\
--mask, -m file : Mask input with specified file.\n\
--threads, -T N : Use N threads (default=hardware limit).\n\
--lop, -l C : Use Continuous Laplacian operators.\n\
D Use Discrete Laplacian operators (default).\n"
};
const struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"threads", required_argument, 0, 'T'},
{"lop", required_argument, 0, 'l'},
{0, 0, 0, 0}
};
const char *short_options = "hvo:m:T:l:";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Eigen::initParallel();
bool verbose = false;
string prefix;
QI::ReadImageF::Pointer mask = ITK_NULLPTR;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'm':
if (verbose) cout << "Reading mask file " << optarg << endl;
mask = QI::ReadImageF::New();
mask->SetFileName(optarg);
break;
case 'o':
prefix = optarg;
cout << "Output prefix will be: " << prefix << endl;
break;
case 'l':
break;
case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
if (verbose) cout << "Opening input file: " << argv[optind] << endl;
string fname(argv[optind++]);
if (prefix == "")
prefix = fname.substr(0, fname.find(".nii"));
string outname = prefix + "_unwrap" + QI::OutExt();
if (verbose) cout << "Output filename: " << outname << endl;
auto inFile = QI::ReadImageF::New();
auto calcLaplace = itk::DiscreteLaplacePhaseFilter::New();
inFile->SetFileName(fname);
inFile->Update(); // Need the size info
calcLaplace->SetInput(inFile->GetOutput());
if (mask)
calcLaplace->SetMask(mask->GetOutput());
if (verbose) cout << "Padding image to valid FFT size." << endl;
typedef itk::FFTPadImageFilter<QI::ImageF> PadFFTType;
auto padFFT = PadFFTType::New();
padFFT->SetInput(calcLaplace->GetOutput());
padFFT->Update();
if (verbose) {
cout << "Padded image size: " << padFFT->GetOutput()->GetLargestPossibleRegion().GetSize() << endl;
cout << "Calculating Forward FFT." << endl;
}
typedef itk::ForwardFFTImageFilter<QI::ImageF> FFFTType;
auto forwardFFT = FFFTType::New();
forwardFFT->SetInput(padFFT->GetOutput());
forwardFFT->Update();
if (verbose) cout << "Generating Inverse Laplace Kernel." << endl;
auto inverseLaplace = itk::DiscreteInverseLaplace::New();
inverseLaplace->SetImageProperties(padFFT->GetOutput());
inverseLaplace->Update();
if (verbose) cout << "Multiplying." << endl;
auto mult = itk::MultiplyImageFilter<QI::ImageXF, QI::ImageF, QI::ImageXF>::New();
mult->SetInput1(forwardFFT->GetOutput());
mult->SetInput2(inverseLaplace->GetOutput());
if (verbose) cout << "Inverse FFT." << endl;
auto inverseFFT = itk::InverseFFTImageFilter<QI::ImageXF, QI::ImageF>::New();
inverseFFT->SetInput(mult->GetOutput());
inverseFFT->Update();
if (verbose) cout << "Extracting original size image" << endl;
auto extract = itk::ExtractImageFilter<QI::ImageF, QI::ImageF>::New();
extract->SetInput(inverseFFT->GetOutput());
extract->SetDirectionCollapseToSubmatrix();
extract->SetExtractionRegion(calcLaplace->GetOutput()->GetLargestPossibleRegion());
extract->Update();
auto outFile = QI::WriteImageF::New();
if (mask) {
if (verbose) cout << "Re-applying mask" << endl;
auto masker = itk::MaskImageFilter<QI::ImageF, QI::ImageF>::New();
masker->SetMaskImage(mask->GetOutput());
masker->SetInput(extract->GetOutput());
masker->Update();
outFile->SetInput(masker->GetOutput());
} else {
outFile->SetInput(extract->GetOutput());
}
outFile->SetFileName(outname);
if (verbose) cout << "Writing output." << endl;
outFile->Update();
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<commit_msg>Added an option to save the Laplacian-filtered phase image.<commit_after>/*
* qiunwrap.cpp
*
* Created by Tobias Wood on 11/06/2015.
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Eigen/Dense"
#include "itkImageSource.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMultiplyImageFilter.h"
#include "itkForwardFFTImageFilter.h"
#include "itkInverseFFTImageFilter.h"
#include "itkFFTPadImageFilter.h"
#include "itkMaskImageFilter.h"
#include "Types.h"
#include "Util.h"
using namespace std;
using namespace Eigen;
namespace itk {
class DiscreteLaplacePhaseFilter : public ImageToImageFilter<QI::ImageF, QI::ImageF> {
protected:
public:
/** Standard class typedefs. */
typedef QI::ImageF TImage;
typedef DiscreteLaplacePhaseFilter Self;
typedef ImageToImageFilter<TImage, TImage> Superclass;
typedef SmartPointer<Self> Pointer;
typedef typename TImage::RegionType RegionType;
itkNewMacro(Self);
itkTypeMacro(DiscreteLaplacePhaseFilter, DiscreteLaplacePhaseFilter);
void SetInput(const TImage *img) override { this->SetNthInput(0, const_cast<TImage*>(img)); }
void SetMask(const TImage *img) { this->SetNthInput(1, const_cast<TImage*>(img)); }
typename TImage::ConstPointer GetInput() const { return static_cast<const TImage *>(this->ProcessObject::GetInput(0)); }
typename TImage::ConstPointer GetMask() const { return static_cast<const TImage *>(this->ProcessObject::GetInput(1)); }
virtual void GenerateOutputInformation() override {
Superclass::GenerateOutputInformation();
auto op = this->GetOutput();
op->SetRegions(this->GetInput()->GetLargestPossibleRegion());
op->Allocate();
}
protected:
DiscreteLaplacePhaseFilter() {
this->SetNumberOfRequiredInputs(1);
this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, this->MakeOutput(0));
}
~DiscreteLaplacePhaseFilter() {}
DataObject::Pointer MakeOutput(unsigned int idx) {
//std::cout << __PRETTY_FUNCTION__ << endl;
if (idx == 0) {
DataObject::Pointer output = (TImage::New()).GetPointer();
return output.GetPointer();
} else {
std::cerr << "No output " << idx << std::endl;
return NULL;
}
}
virtual void ThreadedGenerateData(const RegionType ®ion, ThreadIdType threadId) override {
//std::cout << __PRETTY_FUNCTION__ << endl;
ConstNeighborhoodIterator<TImage>::RadiusType radius;
radius.Fill(1);
ConstNeighborhoodIterator<TImage> inputIter(radius, this->GetInput(), region);
ImageRegionIterator<TImage> outputIter(this->GetOutput(), region);
ImageRegionConstIterator<TImage> maskIter;
const auto mask = this->GetMask();
if (mask) {
maskIter = ImageRegionConstIterator<TImage>(mask, region);
}
vector<ConstNeighborhoodIterator<TImage>::OffsetType> back, fwrd;
back.push_back({{-1, 0, 0}});
fwrd.push_back({{ 1, 0, 0}});
back.push_back({{ 0,-1, 0}});
fwrd.push_back({{ 0, 1, 0}});
back.push_back({{ 0, 0,-1}});
fwrd.push_back({{ 0, 0, 1}});
TImage::SpacingType spacing = this->GetInput()->GetSpacing();
TImage::SpacingType s_sqr = spacing * spacing;
while(!inputIter.IsAtEnd()) {
double sum = 0;
if (!mask || maskIter.Get()) {
double cphase = inputIter.GetCenterPixel();
complex<double> c = std::polar(1., cphase);
for (int i = 0; i < fwrd.size(); ++i) {
double bphase = inputIter.GetPixel(back[i]);
double fphase = inputIter.GetPixel(fwrd[i]);
complex<double> b = std::polar(1., bphase);
complex<double> f = std::polar(1., fphase);
sum += std::arg((f*b)/(c*c)) / s_sqr[i];
}
}
outputIter.Set(sum / 7.);
++inputIter;
++outputIter;
if (mask)
++maskIter;
}
}
private:
DiscreteLaplacePhaseFilter(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
};
class DiscreteInverseLaplace : public ImageSource<QI::ImageF> {
public:
typedef QI::ImageF TImage;
typedef DiscreteInverseLaplace Self;
typedef ImageSource<TImage> Superclass;
typedef SmartPointer<Self> Pointer;
itkNewMacro(Self);
itkTypeMacro(DiscreteInverseLaplace, ImageSource);
void SetImageProperties(const TImage *img) {
m_region = img->GetLargestPossibleRegion();
m_spacing = img->GetSpacing();
m_direction = img->GetDirection();
m_origin = img->GetOrigin();
}
protected:
typename TImage::RegionType m_region;
typename TImage::SpacingType m_spacing;
typename TImage::DirectionType m_direction;
typename TImage::PointType m_origin;
DiscreteInverseLaplace(){}
~DiscreteInverseLaplace(){}
virtual void GenerateData() override {
typename TImage::Pointer output = this->GetOutput();
output->SetRegions(m_region);
output->Allocate();
output->SetSpacing(m_spacing);
output->SetDirection(m_direction);
output->SetOrigin(m_origin);
itk::ImageRegionIteratorWithIndex<TImage> imageIt(output,output->GetLargestPossibleRegion());
imageIt.GoToBegin();
imageIt.Set(0.); // There is a pole here
++imageIt;
while(!imageIt.IsAtEnd()) {
auto index = imageIt.GetIndex() - m_region.GetIndex(); // Might be padded to a negative start
double val = 0;
for (int i = 0; i < 3; i++) {
val += 2. - 2. * cos(index[i] * 2. * M_PI / m_region.GetSize()[i]);
}
val /= 7.;
imageIt.Set(1./val);
++imageIt;
}
}
private:
DiscreteInverseLaplace(const Self &);
void operator=(const Self &);
};
} // End namespace itk
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: qiunwrap [options] input \n\
\n\
Input is a single wrapped phase volume\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print more information.\n\
--out, -o path : Specify an output filename (default image base).\n\
--mask, -m file : Mask input with specified file.\n\
--savelap, -l : Save the Laplace filtered phase.\n\
--threads, -T N : Use N threads (default=hardware limit).\n"
};
const struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"savelap", no_argument, 0, 'l'},
{"threads", required_argument, 0, 'T'},
{0, 0, 0, 0}
};
const char *short_options = "hvo:m:lT:";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Eigen::initParallel();
bool verbose = false, savelap = false;
string prefix;
QI::ReadImageF::Pointer mask = ITK_NULLPTR;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'm':
if (verbose) cout << "Reading mask file " << optarg << endl;
mask = QI::ReadImageF::New();
mask->SetFileName(optarg);
break;
case 'o':
prefix = optarg;
cout << "Output prefix will be: " << prefix << endl;
break;
case 'l': savelap = true; break;
case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
if (verbose) cout << "Opening input file: " << argv[optind] << endl;
string fname(argv[optind++]);
if (prefix == "")
prefix = fname.substr(0, fname.find(".nii"));
string outname = prefix + "_unwrap" + QI::OutExt();
if (verbose) cout << "Output filename: " << outname << endl;
auto inFile = QI::ReadImageF::New();
auto calcLaplace = itk::DiscreteLaplacePhaseFilter::New();
inFile->SetFileName(fname);
inFile->Update(); // Need the size info
calcLaplace->SetInput(inFile->GetOutput());
if (mask)
calcLaplace->SetMask(mask->GetOutput());
calcLaplace->Update();
if (savelap) {
auto outLap = QI::WriteImageF::New();
outLap->SetInput(calcLaplace->GetOutput());
outLap->SetFileName(prefix + "_laplace" + QI::OutExt());
outLap->Update();
}
if (verbose) cout << "Padding image to valid FFT size." << endl;
typedef itk::FFTPadImageFilter<QI::ImageF> PadFFTType;
auto padFFT = PadFFTType::New();
padFFT->SetInput(calcLaplace->GetOutput());
padFFT->Update();
if (verbose) {
cout << "Padded image size: " << padFFT->GetOutput()->GetLargestPossibleRegion().GetSize() << endl;
cout << "Calculating Forward FFT." << endl;
}
typedef itk::ForwardFFTImageFilter<QI::ImageF> FFFTType;
auto forwardFFT = FFFTType::New();
forwardFFT->SetInput(padFFT->GetOutput());
forwardFFT->Update();
if (verbose) cout << "Generating Inverse Laplace Kernel." << endl;
auto inverseLaplace = itk::DiscreteInverseLaplace::New();
inverseLaplace->SetImageProperties(padFFT->GetOutput());
inverseLaplace->Update();
if (verbose) cout << "Multiplying." << endl;
auto mult = itk::MultiplyImageFilter<QI::ImageXF, QI::ImageF, QI::ImageXF>::New();
mult->SetInput1(forwardFFT->GetOutput());
mult->SetInput2(inverseLaplace->GetOutput());
if (verbose) cout << "Inverse FFT." << endl;
auto inverseFFT = itk::InverseFFTImageFilter<QI::ImageXF, QI::ImageF>::New();
inverseFFT->SetInput(mult->GetOutput());
inverseFFT->Update();
if (verbose) cout << "Extracting original size image" << endl;
auto extract = itk::ExtractImageFilter<QI::ImageF, QI::ImageF>::New();
extract->SetInput(inverseFFT->GetOutput());
extract->SetDirectionCollapseToSubmatrix();
extract->SetExtractionRegion(calcLaplace->GetOutput()->GetLargestPossibleRegion());
extract->Update();
auto outFile = QI::WriteImageF::New();
if (mask) {
if (verbose) cout << "Re-applying mask" << endl;
auto masker = itk::MaskImageFilter<QI::ImageF, QI::ImageF>::New();
masker->SetMaskImage(mask->GetOutput());
masker->SetInput(extract->GetOutput());
masker->Update();
outFile->SetInput(masker->GetOutput());
} else {
outFile->SetInput(extract->GetOutput());
}
outFile->SetFileName(outname);
if (verbose) cout << "Writing output." << endl;
outFile->Update();
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Navigate to the settings tab and block until complete.
const GURL& url = GURL(chrome::kChromeUISettingsURL);
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(url, 1)) << url.spec();
// Verify that the page title is correct.
// The only guarantee we can make about the title of a settings tab is that
// it should contain IDS_SETTINGS_TITLE somewhere.
std::wstring title;
EXPECT_TRUE(tab->GetTabTitle(&title));
string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
EXPECT_NE(WideToUTF16Hack(title).find(expected_title), string16::npos);
// Check navbar's existence.
bool navbar_exist = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"domAutomationController.send("
L"!!document.getElementById('navbar'))", &navbar_exist));
EXPECT_EQ(true, navbar_exist);
// Check section headers in navbar.
// For ChromeOS, there should be 1 + 7:
// Search, Basics, Personal, System, Internet, Under the Hood,
// Users and Extensions.
// For other platforms, there should 1 + 4:
// Search, Basics, Personal, Under the Hood and Extensions.
#if defined(OS_CHROMEOS)
const int kExpectedSections = 1 + 7;
#else
const int kExpectedSections = 1 + 4;
#endif
int num_of_sections = 0;
EXPECT_TRUE(tab->ExecuteAndExtractInt(L"",
L"domAutomationController.send("
L"document.getElementById('navbar').children.length)", &num_of_sections));
EXPECT_EQ(kExpectedSections, num_of_sections);
}
} // namespace
<commit_msg>Revert 101845 - [dom-ui options] Inline helper functions for OptionsUITest.LoadOptionsByURL.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
}
void AssertIsOptionsPage(TabProxy* tab) {
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
// The only guarantee we can make about the title of a settings tab is that
// it should contain IDS_SETTINGS_TITLE somewhere.
ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos);
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
NavigateToURL(GURL(chrome::kChromeUISettingsURL));
AssertIsOptionsPage(tab);
// Check navbar's existence.
bool navbar_exist = false;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"domAutomationController.send("
L"!!document.getElementById('navbar'))", &navbar_exist));
ASSERT_EQ(true, navbar_exist);
// Check section headers in navbar.
// For ChromeOS, there should be 1 + 7:
// Search, Basics, Personal, System, Internet, Under the Hood,
// Users and Extensions.
// For other platforms, there should 1 + 4:
// Search, Basics, Personal, Under the Hood and Extensions.
#if defined(OS_CHROMEOS)
const int kExpectedSections = 1 + 7;
#else
const int kExpectedSections = 1 + 4;
#endif
int num_of_sections = 0;
ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
L"domAutomationController.send("
L"document.getElementById('navbar').children.length)", &num_of_sections));
ASSERT_EQ(kExpectedSections, num_of_sections);
}
} // namespace
<|endoftext|> |
<commit_before>/*
The MIT License
Copyright (c) 2011 by Jorrit Tyberghein
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 "../apparesed.h"
#include "physicallayer/pl.h"
#include "physicallayer/entity.h"
#include "physicallayer/entitytpl.h"
#include "physicallayer/propclas.h"
#include "propclass/camera.h"
#include "propclass/mesh.h"
#include "propclass/mechsys.h"
#include "playmode.h"
//---------------------------------------------------------------------------
DynworldSnapshot::DynworldSnapshot (iPcDynamicWorld* dynworld)
{
csRef<iDynamicCellIterator> cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
for (size_t i = 0 ; i < cell->GetObjectCount () ; i++)
{
iDynamicObject* dynobj = cell->GetObject (i);
Obj obj;
obj.cell = dynobj->GetCell ();
obj.fact = dynobj->GetFactory ();
obj.isStatic = dynobj->IsStatic ();
obj.trans = dynobj->GetTransform ();
if (dynobj->GetEntityTemplate ())
obj.entityName = dynobj->GetEntityTemplate ()->GetName ();
objects.Push (obj);
}
}
}
void DynworldSnapshot::Restore (iPcDynamicWorld* dynworld)
{
csRef<iDynamicCellIterator> cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
cell->DeleteObjects ();
}
for (size_t i = 0 ; i < objects.GetSize () ; i++)
{
Obj& obj = objects[i];
iDynamicObject* dynobj = obj.cell->AddObject (obj.fact->GetName (), obj.trans);
if (!obj.entityName.IsEmpty ())
dynobj->SetEntity (0, obj.entityName, 0);
if (obj.isStatic)
dynobj->MakeStatic ();
else
dynobj->MakeDynamic ();
}
}
//---------------------------------------------------------------------------
PlayMode::PlayMode (AresEdit3DView* aresed3d)
: EditingMode (aresed3d, "Play")
{
snapshot = 0;
}
PlayMode::~PlayMode ()
{
delete snapshot;
}
void PlayMode::Start ()
{
aresed3d->GetSelection ()->SetCurrentObject (0);
delete snapshot;
iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld ();
dynworld->InhibitEntities (false);
dynworld->EnableGameMode (true);
snapshot = new DynworldSnapshot (dynworld);
// Set entities for all dynamic objects and find the player object.
iDynamicFactory* playerFact = dynworld->FindFactory ("Player");
csReversibleTransform playerTrans;
iDynamicCell* foundCell = 0;
iDynamicObject* foundPlayerDynobj = 0;
csRef<iDynamicCellIterator> cellIt = dynworld->GetCells ();
while (!foundPlayerDynobj && cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
for (size_t i = 0 ; i < cell->GetObjectCount () ; i++)
{
iDynamicObject* dynobj = cell->GetObject (i);
if (dynobj->GetFactory () == playerFact)
{
playerTrans = dynobj->GetTransform ();
foundCell = cell;
foundPlayerDynobj = dynobj;
break;
}
}
}
if (foundPlayerDynobj)
{
dynworld->SetCurrentCell (foundCell);
foundCell->DeleteObject (foundPlayerDynobj);
}
else
{
playerTrans.SetOrigin (csVector3 (0, 3, 0));
}
iCelPlLayer* pl = aresed3d->GetPL ();
iCelEntity* zoneEntity = pl->FindEntity ("Zone");
csRef<iPcMechanicsSystem> mechsys = celQueryPropertyClassEntity<iPcMechanicsSystem> (zoneEntity);
mechsys->SetDynamicSystem (dynworld->GetCurrentCell ()->GetDynamicSystem ());
world = pl->CreateEntity (pl->FindEntityTemplate ("World"), "World", 0);
player = pl->CreateEntity (pl->FindEntityTemplate ("Player"), "Player", 0);
csRef<iPcMechanicsObject> mechPlayer = celQueryPropertyClassEntity<iPcMechanicsObject> (player);
iRigidBody* body = mechPlayer->GetBody ();
csRef<CS::Physics::Bullet::iRigidBody> bulletBody = scfQueryInterface<CS::Physics::Bullet::iRigidBody> (body);
//bulletBody->MakeKinematic ();
csRef<iPcCamera> pccamera = celQueryPropertyClassEntity<iPcCamera> (player);
csRef<iPcMesh> pcmesh = celQueryPropertyClassEntity<iPcMesh> (player);
// @@@ Need support for setting transform on pcmesh.
pcmesh->MoveMesh (dynworld->GetCurrentCell ()->GetSector (), playerTrans.GetOrigin ());
body->SetTransform (playerTrans);
iELCM* elcm = aresed3d->GetELCM ();
elcm->SetPlayer (player);
cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
for (size_t i = 0 ; i < cell->GetObjectCount () ; i++)
{
iDynamicObject* dynobj = cell->GetObject (i);
if (dynobj->GetFactory () != playerFact)
dynobj->ForceEntity ();
}
}
}
void PlayMode::Stop ()
{
if (!snapshot) return;
iCelPlLayer* pl = aresed3d->GetPL ();
pl->RemoveEntity (world);
world = 0;
pl->RemoveEntity (player);
player = 0;
iELCM* elcm = aresed3d->GetELCM ();
elcm->SetPlayer (0);
iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld ();
dynworld->InhibitEntities (true);
dynworld->EnableGameMode (false);
snapshot->Restore (dynworld);
delete snapshot;
snapshot = 0;
aresed3d->GetG2D ()->SetMouseCursor (csmcArrow);
}
bool PlayMode::OnKeyboard(iEvent& ev, utf32_char code)
{
if (code == CSKEY_ESC)
{
aresed3d->GetApp ()->SwitchToMainMode ();
return true;
}
return false;
}
<commit_msg>Entity templates are now properly updated even for entities that were already created before a template was modified.<commit_after>/*
The MIT License
Copyright (c) 2011 by Jorrit Tyberghein
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 "../apparesed.h"
#include "physicallayer/pl.h"
#include "physicallayer/entity.h"
#include "physicallayer/entitytpl.h"
#include "physicallayer/propclas.h"
#include "propclass/camera.h"
#include "propclass/mesh.h"
#include "propclass/mechsys.h"
#include "playmode.h"
//---------------------------------------------------------------------------
DynworldSnapshot::DynworldSnapshot (iPcDynamicWorld* dynworld)
{
csRef<iDynamicCellIterator> cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
for (size_t i = 0 ; i < cell->GetObjectCount () ; i++)
{
iDynamicObject* dynobj = cell->GetObject (i);
Obj obj;
obj.cell = dynobj->GetCell ();
obj.fact = dynobj->GetFactory ();
obj.isStatic = dynobj->IsStatic ();
obj.trans = dynobj->GetTransform ();
if (dynobj->GetEntityTemplate ())
obj.entityName = dynobj->GetEntityTemplate ()->GetName ();
objects.Push (obj);
}
}
}
void DynworldSnapshot::Restore (iPcDynamicWorld* dynworld)
{
csRef<iDynamicCellIterator> cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
cell->DeleteObjects ();
}
for (size_t i = 0 ; i < objects.GetSize () ; i++)
{
Obj& obj = objects[i];
iDynamicObject* dynobj = obj.cell->AddObject (obj.fact->GetName (), obj.trans);
if (!obj.entityName.IsEmpty ())
dynobj->SetEntity (0, obj.entityName, 0);
if (obj.isStatic)
dynobj->MakeStatic ();
else
dynobj->MakeDynamic ();
}
}
//---------------------------------------------------------------------------
PlayMode::PlayMode (AresEdit3DView* aresed3d)
: EditingMode (aresed3d, "Play")
{
snapshot = 0;
}
PlayMode::~PlayMode ()
{
delete snapshot;
}
void PlayMode::Start ()
{
aresed3d->GetSelection ()->SetCurrentObject (0);
delete snapshot;
iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld ();
dynworld->InhibitEntities (false);
dynworld->EnableGameMode (true);
snapshot = new DynworldSnapshot (dynworld);
// Set entities for all dynamic objects and find the player object.
iDynamicFactory* playerFact = dynworld->FindFactory ("Player");
csReversibleTransform playerTrans;
iDynamicCell* foundCell = 0;
iDynamicObject* foundPlayerDynobj = 0;
csRef<iDynamicCellIterator> cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
for (size_t i = 0 ; i < cell->GetObjectCount () ; i++)
{
iDynamicObject* dynobj = cell->GetObject (i);
if (dynobj->GetFactory () == playerFact)
{
playerTrans = dynobj->GetTransform ();
foundCell = cell;
foundPlayerDynobj = dynobj;
}
else
{
csString tplName = dynobj->GetFactory ()->GetDefaultEntityTemplate ();
if (tplName.IsEmpty ())
tplName = dynobj->GetFactory ()->GetName ();
printf ("Setting entity %s\n", tplName.GetData ());
dynobj->SetEntity (0, tplName, 0);
}
}
}
if (foundPlayerDynobj)
{
dynworld->SetCurrentCell (foundCell);
foundCell->DeleteObject (foundPlayerDynobj);
}
else
{
playerTrans.SetOrigin (csVector3 (0, 3, 0));
}
iCelPlLayer* pl = aresed3d->GetPL ();
iCelEntity* zoneEntity = pl->FindEntity ("Zone");
csRef<iPcMechanicsSystem> mechsys = celQueryPropertyClassEntity<iPcMechanicsSystem> (zoneEntity);
mechsys->SetDynamicSystem (dynworld->GetCurrentCell ()->GetDynamicSystem ());
world = pl->CreateEntity (pl->FindEntityTemplate ("World"), "World", 0);
player = pl->CreateEntity (pl->FindEntityTemplate ("Player"), "Player", 0);
csRef<iPcMechanicsObject> mechPlayer = celQueryPropertyClassEntity<iPcMechanicsObject> (player);
iRigidBody* body = mechPlayer->GetBody ();
csRef<CS::Physics::Bullet::iRigidBody> bulletBody = scfQueryInterface<CS::Physics::Bullet::iRigidBody> (body);
//bulletBody->MakeKinematic ();
csRef<iPcCamera> pccamera = celQueryPropertyClassEntity<iPcCamera> (player);
csRef<iPcMesh> pcmesh = celQueryPropertyClassEntity<iPcMesh> (player);
// @@@ Need support for setting transform on pcmesh.
pcmesh->MoveMesh (dynworld->GetCurrentCell ()->GetSector (), playerTrans.GetOrigin ());
body->SetTransform (playerTrans);
iELCM* elcm = aresed3d->GetELCM ();
elcm->SetPlayer (player);
cellIt = dynworld->GetCells ();
while (cellIt->HasNext ())
{
iDynamicCell* cell = cellIt->NextCell ();
for (size_t i = 0 ; i < cell->GetObjectCount () ; i++)
{
iDynamicObject* dynobj = cell->GetObject (i);
if (dynobj->GetFactory () != playerFact)
dynobj->ForceEntity ();
}
}
}
void PlayMode::Stop ()
{
if (!snapshot) return;
iCelPlLayer* pl = aresed3d->GetPL ();
pl->RemoveEntity (world);
world = 0;
pl->RemoveEntity (player);
player = 0;
iELCM* elcm = aresed3d->GetELCM ();
elcm->SetPlayer (0);
iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld ();
dynworld->InhibitEntities (true);
dynworld->EnableGameMode (false);
snapshot->Restore (dynworld);
delete snapshot;
snapshot = 0;
aresed3d->GetG2D ()->SetMouseCursor (csmcArrow);
}
bool PlayMode::OnKeyboard(iEvent& ev, utf32_char code)
{
if (code == CSKEY_ESC)
{
aresed3d->GetApp ()->SwitchToMainMode ();
return true;
}
return false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/test/automation/javascript_execution_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Tests the DOMAutomation framework for manipulating DOMElements within
// browser tests.
class DOMAutomationTest : public InProcessBrowserTest {
public:
DOMAutomationTest() {
EnableDOMAutomation();
JavaScriptExecutionController::set_timeout(30000);
}
GURL GetTestURL(const char* path) {
std::string url_path = "files/dom_automation/";
url_path.append(path);
return test_server()->GetURL(url_path);
}
};
typedef DOMElementProxy::By By;
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindByXPath) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_div = main_doc->FindElement(By::XPath("//div"));
ASSERT_TRUE(first_div);
ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//div"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::XPath("//nosuchtag")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::XPath("//nosuchtag"), &elements));
elements.clear();
ASSERT_EQ(0u, elements.size());
// Find with invalid xpath.
ASSERT_FALSE(main_doc->FindElement(By::XPath("'invalid'")));
ASSERT_FALSE(main_doc->FindElement(By::XPath(" / / ")));
ASSERT_FALSE(main_doc->FindElements(By::XPath("'invalid'"), &elements));
ASSERT_FALSE(main_doc->FindElements(By::XPath(" / / "), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::XPath("/html/body/span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::XPath("./span"));
}
ASSERT_EQ(3, nested_count);
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_myclass =
main_doc->FindElement(By::Selectors(".myclass"));
ASSERT_TRUE(first_myclass);
ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors(".myclass"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("#nosuchid")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Selectors("#nosuchid"), &elements));
ASSERT_EQ(0u, elements.size());
// Find with invalid selectors.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("1#2")));
ASSERT_FALSE(main_doc->FindElements(By::Selectors("1#2"), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Selectors("span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Selectors("span"));
}
ASSERT_EQ(3, nested_count);
}
#if defined(OS_WIN)
// http://crbug.com/72745
#define MAYBE_FindByText FLAKY_FindByText
#else
#define MAYBE_FindByText FindByText
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_text = main_doc->FindElement(By::Text("div_text"));
ASSERT_TRUE(first_text);
ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Text("div_text"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Text("nosuchtext")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Text("nosuchtext"), &elements));
ASSERT_EQ(0u, elements.size());
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Text("span_text"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Text("span_text"));
}
ASSERT_EQ(3, nested_count);
// Find only visible text.
DOMElementProxyRef shown_td = main_doc->FindElement(By::Text("table_text"));
ASSERT_TRUE(shown_td);
ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches("shown"));
// Find text in inputs.
ASSERT_TRUE(main_doc->FindElement(By::Text("textarea_text")));
ASSERT_TRUE(main_doc->FindElement(By::Text("input_text")));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef div =
main_doc->WaitFor1VisibleElement(By::Selectors("div"));
ASSERT_TRUE(div.get());
ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches("div_inner"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors("img")));
std::vector<DOMElementProxyRef> img_elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors("img"), &img_elements));
ASSERT_EQ(0u, img_elements.size());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(anchor.get());
ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(
"href", "http://www.google.com"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("frames/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Get both frame elements.
std::vector<DOMElementProxyRef> frame_elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//frame"), &frame_elements));
ASSERT_EQ(2u, frame_elements.size());
// Get both frames, checking their contents are correct.
DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();
DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();
ASSERT_TRUE(frame1 && frame2);
DOMElementProxyRef frame_div =
frame1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 1"));
frame_div = frame2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 2"));
// Get both inner iframes, checking their contents are correct.
DOMElementProxyRef iframe1 =
frame1->GetDocumentFromFrame("0");
DOMElementProxyRef iframe2 =
frame2->GetDocumentFromFrame("0");
ASSERT_TRUE(iframe1 && iframe2);
frame_div = iframe1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 1"));
frame_div = iframe2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 2"));
// Get nested frame.
ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame("0", "0").get());
ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame("1", "0").get());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("events/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Click link and make sure text changes.
DOMElementProxyRef link = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(link && link->Click());
ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches("clicked"));
// Click input button and make sure textfield changes.
DOMElementProxyRef button = main_doc->FindElement(By::Selectors("#button"));
DOMElementProxyRef textfield =
main_doc->FindElement(By::Selectors("#textfield"));
ASSERT_TRUE(textfield && button && button->Click());
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("clicked"));
// Type in the textfield.
ASSERT_TRUE(textfield->SetText("test"));
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("test"));
// Type in the textarea.
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea && textarea->Type("test"));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches("textareatest"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("string_escape/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea);
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L"\u00FF")));
const wchar_t* set_and_expect_strings[] = {
L"\u00FF and \u00FF",
L"\n \t \\",
L"' \""
};
for (size_t i = 0; i < 3; i++) {
ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(
WideToUTF8(set_and_expect_strings[i])));
}
}
} // namespace
<commit_msg>Re-mark DOMAutomationTest.FindByXPath as FLAKY on Windows.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/test/automation/javascript_execution_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Tests the DOMAutomation framework for manipulating DOMElements within
// browser tests.
class DOMAutomationTest : public InProcessBrowserTest {
public:
DOMAutomationTest() {
EnableDOMAutomation();
JavaScriptExecutionController::set_timeout(30000);
}
GURL GetTestURL(const char* path) {
std::string url_path = "files/dom_automation/";
url_path.append(path);
return test_server()->GetURL(url_path);
}
};
typedef DOMElementProxy::By By;
#if defined(OS_WIN)
// See http://crbug.com/61636
#define MAYBE_FindByXPath FLAKY_FindByXPath
#else
#define MAYBE_FindByXPath FindByXPath
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByXPath) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_div = main_doc->FindElement(By::XPath("//div"));
ASSERT_TRUE(first_div);
ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//div"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::XPath("//nosuchtag")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::XPath("//nosuchtag"), &elements));
elements.clear();
ASSERT_EQ(0u, elements.size());
// Find with invalid xpath.
ASSERT_FALSE(main_doc->FindElement(By::XPath("'invalid'")));
ASSERT_FALSE(main_doc->FindElement(By::XPath(" / / ")));
ASSERT_FALSE(main_doc->FindElements(By::XPath("'invalid'"), &elements));
ASSERT_FALSE(main_doc->FindElements(By::XPath(" / / "), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::XPath("/html/body/span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::XPath("./span"));
}
ASSERT_EQ(3, nested_count);
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_myclass =
main_doc->FindElement(By::Selectors(".myclass"));
ASSERT_TRUE(first_myclass);
ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors(".myclass"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("#nosuchid")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Selectors("#nosuchid"), &elements));
ASSERT_EQ(0u, elements.size());
// Find with invalid selectors.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("1#2")));
ASSERT_FALSE(main_doc->FindElements(By::Selectors("1#2"), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Selectors("span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Selectors("span"));
}
ASSERT_EQ(3, nested_count);
}
#if defined(OS_WIN)
// http://crbug.com/72745
#define MAYBE_FindByText FLAKY_FindByText
#else
#define MAYBE_FindByText FindByText
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_text = main_doc->FindElement(By::Text("div_text"));
ASSERT_TRUE(first_text);
ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Text("div_text"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Text("nosuchtext")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Text("nosuchtext"), &elements));
ASSERT_EQ(0u, elements.size());
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Text("span_text"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Text("span_text"));
}
ASSERT_EQ(3, nested_count);
// Find only visible text.
DOMElementProxyRef shown_td = main_doc->FindElement(By::Text("table_text"));
ASSERT_TRUE(shown_td);
ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches("shown"));
// Find text in inputs.
ASSERT_TRUE(main_doc->FindElement(By::Text("textarea_text")));
ASSERT_TRUE(main_doc->FindElement(By::Text("input_text")));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef div =
main_doc->WaitFor1VisibleElement(By::Selectors("div"));
ASSERT_TRUE(div.get());
ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches("div_inner"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors("img")));
std::vector<DOMElementProxyRef> img_elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors("img"), &img_elements));
ASSERT_EQ(0u, img_elements.size());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(anchor.get());
ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(
"href", "http://www.google.com"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("frames/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Get both frame elements.
std::vector<DOMElementProxyRef> frame_elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//frame"), &frame_elements));
ASSERT_EQ(2u, frame_elements.size());
// Get both frames, checking their contents are correct.
DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();
DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();
ASSERT_TRUE(frame1 && frame2);
DOMElementProxyRef frame_div =
frame1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 1"));
frame_div = frame2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 2"));
// Get both inner iframes, checking their contents are correct.
DOMElementProxyRef iframe1 =
frame1->GetDocumentFromFrame("0");
DOMElementProxyRef iframe2 =
frame2->GetDocumentFromFrame("0");
ASSERT_TRUE(iframe1 && iframe2);
frame_div = iframe1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 1"));
frame_div = iframe2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 2"));
// Get nested frame.
ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame("0", "0").get());
ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame("1", "0").get());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("events/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Click link and make sure text changes.
DOMElementProxyRef link = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(link && link->Click());
ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches("clicked"));
// Click input button and make sure textfield changes.
DOMElementProxyRef button = main_doc->FindElement(By::Selectors("#button"));
DOMElementProxyRef textfield =
main_doc->FindElement(By::Selectors("#textfield"));
ASSERT_TRUE(textfield && button && button->Click());
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("clicked"));
// Type in the textfield.
ASSERT_TRUE(textfield->SetText("test"));
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("test"));
// Type in the textarea.
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea && textarea->Type("test"));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches("textareatest"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("string_escape/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea);
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L"\u00FF")));
const wchar_t* set_and_expect_strings[] = {
L"\u00FF and \u00FF",
L"\n \t \\",
L"' \""
};
for (size_t i = 0; i < 3; i++) {
ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(
WideToUTF8(set_and_expect_strings[i])));
}
}
} // namespace
<|endoftext|> |
<commit_before>#include "main.h"
/* example constructor, sets some options */
CaesarAttack::CaesarAttack()
{
// declare options, keep options as uppercase
vector<string> temp;
temp.push_back("INPUTFILE");
temp.push_back("OUTPUTFILE");
set_opts(temp);
// set default values, option must exist or error will printed
set_opt_value("OUTPUTFILE", "/tmp/caesarattackresults.txt");
}
/* I am overriding the default module function
* for displaying the description text
*/
void CaesarAttack::disp_desc()
{
cout << "Module: attacks/caesar_attack\n\tThis module attempts to guess the correct shift for the Caesar cipher.\n\tIt makes use of frequency analysis to determine a proper guess.\n\tMay require user interaction.\n\tPlease define an INPUTFILE." << endl;
cout << endl;
}
/* overrides the virtual function from Module
* this is where the real meaty stuff happens
*/
int CaesarAttack::run()
{
// perform error checking on options first
if (options["INPUTFILE"].empty()) {
cout << "[-] Please specify an input file" << endl;
return 1;
}
if (options["OUTPUTFILE"].empty()) {
cout << "[-] Please specify an output file" << endl;
return 2;
}
ifstream in;
ofstream out;
string buff;
cout << "[*] Opening input file: " << options["INPUTFILE"] << endl;
in.open(options["INPUTFILE"]);
cout << "[*] Beginning attack..." << endl;
begin_attack(in, out);
cout << "[*] Closing files" << endl;
in.close();
out.close();
return 0;
}
/* not safe helper function
* doesn't check array out of bounds
*/
float chisq(float *y, float *ym)
{
float sq = 0.0f;
for (int i = 0; i < 26; i++)
sq += (y[i] - ym[i])*(y[i] - ym[i]);
return sq;
}
/* shifts each entry to the left one */
void left_shift_freq(float *freq)
{
float temp = freq[0];
for (int i = 0; i < 25; i++)
freq[i] = freq[i+1];
freq[25] = temp;
}
/* handles the main attack sequence */
void CaesarAttack::begin_attack(ifstream &in, ofstream &out)
{
/* from analyzing huckleberry finn */
float english[] = {0.0834423, 0.0169666, 0.0191698, 0.0539923, 0.112034, 0.0180501, 0.0246394, 0.0602159, 0.0646833, 0.00280142, 0.0130094, 0.0398317, 0.0236778, 0.0747964, 0.0835958, 0.0138107, 0.000442449, 0.0464413, 0.057629, 0.0967157, 0.0318857, 0.00675638, 0.03031, 0.0011919, 0.0234859, 0.00042439};
int freq[26] = {0}, count = 0;
float ffreq[26] = {0.0f};
string buff;
while (getline(in, buff)) {
for (unsigned int i = 0; i < buff.size(); i++) {
if (isalpha(buff[i])) {
int t = ((int) tolower(buff[i])) - 97;
freq[t]++; count++;
}
}
}
for (int i = 0; i < 26; i++)
ffreq[i] = (float)freq[i]/(float)count;
int mins[26]; float csq[26];
for (int i = 0; i < 26; i++) {
mins[i] = i;
csq[i] = chisq(ffreq, english);
left_shift_freq(ffreq);
}
/* insertion sort */
for (int i = 0; i < 26; i++) {
int j = i;
while (j > 0 && csq[mins[j-1]] > csq[mins[j]]) {
int temp = mins[j-1];
mins[j-1] = mins[j];
mins[j] = temp;
j--;
}
}
cout << "[+] Most likely shift: " << mins[0] << endl;
for (int i = 0; i < 26; i++) {
cout << "[*] Decrypting file with shift " << mins[i] << " (chi^2 = " << csq[mins[i]] << ")..." << endl;
out.open(options["OUTPUTFILE"]);
// reset input
in.clear();
in.seekg(0);
string obuff;
int samplecount = 0;
cout << "[*] Sample from decryption: " << endl;
while (getline(in, buff)) {
Caesar::encrypt(buff, obuff, mins[i], true);
out << obuff << endl;
if (samplecount < 5) {
cout << obuff << endl;
samplecount++;
} else {
break;
}
}
string ans;
cout << "[*] Continue decryption? [Y/n]: ";
getline(cin, ans);
if (ans == "N" || ans == "n") {
out.close();
continue;
}
while (getline(in, buff)) {
Caesar::encrypt(buff, obuff, mins[i], true);
out << obuff << endl;
}
// if we get here we are done
break;
}
}
<commit_msg>added assume yes option<commit_after>#include "main.h"
/* example constructor, sets some options */
CaesarAttack::CaesarAttack()
{
// declare options, keep options as uppercase
vector<string> temp;
temp.push_back("INPUTFILE");
temp.push_back("OUTPUTFILE");
temp.push_back("ASSUMEYES");
set_opts(temp);
// set default values, option must exist or error will printed
set_opt_value("OUTPUTFILE", "/tmp/caesarattackresults.txt");
set_opt_value("ASSUMEYES", "0");
}
/* I am overriding the default module function
* for displaying the description text
*/
void CaesarAttack::disp_desc()
{
cout << "Module: attacks/caesar_attack\n\tThis module attempts to guess the correct shift for the Caesar cipher.\n\tIt makes use of frequency analysis to determine a proper guess.\n\tMay require user interaction.\n\tPlease define an INPUTFILE." << endl;
cout << endl;
}
/* overrides the virtual function from Module
* this is where the real meaty stuff happens
*/
int CaesarAttack::run()
{
// perform error checking on options first
if (options["INPUTFILE"].empty()) {
cout << "[-] Please specify an input file" << endl;
return 1;
}
if (options["OUTPUTFILE"].empty()) {
cout << "[-] Please specify an output file" << endl;
return 2;
}
if (options["ASSUMEYES"].empty() || stoi(options["ASSUMEYES"]) < 0 || stoi(options["ASSUMEYES"]) > 1) {
cout << "[-] Please specify an ASSUMEYES value of 0 or 1" << endl;
return 3;
}
ifstream in;
ofstream out;
string buff;
cout << "[*] Opening input file: " << options["INPUTFILE"] << endl;
in.open(options["INPUTFILE"]);
cout << "[*] Beginning attack..." << endl;
begin_attack(in, out);
cout << "[*] Closing files" << endl;
in.close();
out.close();
return 0;
}
/* not safe helper function
* doesn't check array out of bounds
*/
float chisq(float *y, float *ym)
{
float sq = 0.0f;
for (int i = 0; i < 26; i++)
sq += (y[i] - ym[i])*(y[i] - ym[i]);
return sq;
}
/* shifts each entry to the left one */
void left_shift_freq(float *freq)
{
float temp = freq[0];
for (int i = 0; i < 25; i++)
freq[i] = freq[i+1];
freq[25] = temp;
}
/* handles the main attack sequence */
void CaesarAttack::begin_attack(ifstream &in, ofstream &out)
{
/* from analyzing huckleberry finn */
float english[] = {0.0834423, 0.0169666, 0.0191698, 0.0539923, 0.112034, 0.0180501, 0.0246394, 0.0602159, 0.0646833, 0.00280142, 0.0130094, 0.0398317, 0.0236778, 0.0747964, 0.0835958, 0.0138107, 0.000442449, 0.0464413, 0.057629, 0.0967157, 0.0318857, 0.00675638, 0.03031, 0.0011919, 0.0234859, 0.00042439};
int freq[26] = {0}, count = 0;
float ffreq[26] = {0.0f};
string buff;
while (getline(in, buff)) {
for (unsigned int i = 0; i < buff.size(); i++) {
if (isalpha(buff[i])) {
int t = ((int) tolower(buff[i])) - 97;
freq[t]++; count++;
}
}
}
for (int i = 0; i < 26; i++)
ffreq[i] = (float)freq[i]/(float)count;
int mins[26]; float csq[26];
for (int i = 0; i < 26; i++) {
mins[i] = i;
csq[i] = chisq(ffreq, english);
left_shift_freq(ffreq);
}
/* insertion sort */
for (int i = 0; i < 26; i++) {
int j = i;
while (j > 0 && csq[mins[j-1]] > csq[mins[j]]) {
int temp = mins[j-1];
mins[j-1] = mins[j];
mins[j] = temp;
j--;
}
}
cout << "[+] Most likely shift: " << mins[0] << endl;
for (int i = 0; i < 26; i++) {
cout << "[*] Decrypting file with shift " << mins[i] << " (chi^2 = " << csq[mins[i]] << ")..." << endl;
out.open(options["OUTPUTFILE"]);
// reset input
in.clear();
in.seekg(0);
string obuff;
int samplecount = 0;
cout << "[*] Sample from decryption: " << endl;
while (getline(in, buff)) {
Caesar::encrypt(buff, obuff, mins[i], true);
out << obuff << endl;
if (samplecount < 5) {
cout << obuff << endl;
samplecount++;
} else {
break;
}
}
if (!stoi(options["ASSUMEYES"])) {
string ans;
cout << "[*] Continue decryption? [Y/n]: ";
getline(cin, ans);
if (ans == "N" || ans == "n") {
out.close();
continue;
}
}
while (getline(in, buff)) {
Caesar::encrypt(buff, obuff, mins[i], true);
out << obuff << endl;
}
// if we get here we are done
break;
}
}
<|endoftext|> |
<commit_before>//===- llvm/unittest/VMCore/InstructionsTest.cpp - Instructions unit tests ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Instructions.h"
#include "llvm/BasicBlock.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "gtest/gtest.h"
namespace llvm {
namespace {
TEST(InstructionsTest, ReturnInst) {
LLVMContext &C(getGlobalContext());
// test for PR6589
const ReturnInst* r0 = ReturnInst::Create(C);
EXPECT_EQ(r0->getNumOperands(), 0U);
EXPECT_EQ(r0->op_begin(), r0->op_end());
const IntegerType* Int1 = IntegerType::get(C, 1);
Constant* One = ConstantInt::get(Int1, 1, true);
const ReturnInst* r1 = ReturnInst::Create(C, One);
EXPECT_EQ(r1->getNumOperands(), 1U);
User::const_op_iterator b(r1->op_begin());
EXPECT_NE(b, r1->op_end());
EXPECT_EQ(*b, One);
EXPECT_EQ(r1->getOperand(0), One);
++b;
EXPECT_EQ(b, r1->op_end());
// clean up
delete r0;
delete r1;
}
TEST(InstructionsTest, BranchInst) {
LLVMContext &C(getGlobalContext());
// Make a BasicBlocks
BasicBlock* bb0 = BasicBlock::Create(C);
BasicBlock* bb1 = BasicBlock::Create(C);
// Mandatory BranchInst
const BranchInst* b0 = BranchInst::Create(bb0);
// check num operands
EXPECT_EQ(b0->getNumOperands(), 1U);
EXPECT_NE(b0->op_begin(), b0->op_end());
const IntegerType* Int1 = IntegerType::get(C, 1);
Constant* One = ConstantInt::get(Int1, 1, true);
// Conditional BranchInst
BranchInst* b1 = BranchInst::Create(bb0, bb1, One);
// check num operands
EXPECT_EQ(b1->getNumOperands(), 3U);
User::const_op_iterator b(b1->op_begin());
// check COND
EXPECT_NE(b, b1->op_end());
EXPECT_EQ(*b, One);
EXPECT_EQ(b1->getOperand(0), One);
++b;
// check ELSE
EXPECT_EQ(*b, bb1);
EXPECT_EQ(b1->getOperand(1), bb1);
++b;
// check THEN
EXPECT_EQ(*b, bb0);
EXPECT_EQ(b1->getOperand(2), bb0);
++b;
EXPECT_EQ(b, b1->op_end());
// shrink it
b1->setUnconditionalDest(bb1);
// check num operands
EXPECT_EQ(b1->getNumOperands(), 1U);
User::const_op_iterator c(b1->op_begin());
EXPECT_NE(c, b1->op_end());
// check THEN
EXPECT_EQ(*c, bb1);
EXPECT_EQ(b1->getOperand(0), bb1);
++c;
EXPECT_EQ(c, b1->op_end());
// clean up
delete b0;
delete b1;
delete bb0;
delete bb1;
}
} // end anonymous namespace
} // end namespace llvm
<commit_msg>more BranchInst tests<commit_after>//===- llvm/unittest/VMCore/InstructionsTest.cpp - Instructions unit tests ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Instructions.h"
#include "llvm/BasicBlock.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "gtest/gtest.h"
namespace llvm {
namespace {
TEST(InstructionsTest, ReturnInst) {
LLVMContext &C(getGlobalContext());
// test for PR6589
const ReturnInst* r0 = ReturnInst::Create(C);
EXPECT_EQ(r0->getNumOperands(), 0U);
EXPECT_EQ(r0->op_begin(), r0->op_end());
const IntegerType* Int1 = IntegerType::get(C, 1);
Constant* One = ConstantInt::get(Int1, 1, true);
const ReturnInst* r1 = ReturnInst::Create(C, One);
EXPECT_EQ(r1->getNumOperands(), 1U);
User::const_op_iterator b(r1->op_begin());
EXPECT_NE(b, r1->op_end());
EXPECT_EQ(*b, One);
EXPECT_EQ(r1->getOperand(0), One);
++b;
EXPECT_EQ(b, r1->op_end());
// clean up
delete r0;
delete r1;
}
TEST(InstructionsTest, BranchInst) {
LLVMContext &C(getGlobalContext());
// Make a BasicBlocks
BasicBlock* bb0 = BasicBlock::Create(C);
BasicBlock* bb1 = BasicBlock::Create(C);
// Mandatory BranchInst
const BranchInst* b0 = BranchInst::Create(bb0);
EXPECT_TRUE(b0->isUnconditional());
EXPECT_FALSE(b0->isConditional());
EXPECT_EQ(b0->getNumSuccessors(), 1U);
// check num operands
EXPECT_EQ(b0->getNumOperands(), 1U);
EXPECT_NE(b0->op_begin(), b0->op_end());
EXPECT_EQ(b0->op_begin() + 1, b0->op_end());
EXPECT_EQ(b0->op_begin() + 1, b0->op_end());
const IntegerType* Int1 = IntegerType::get(C, 1);
Constant* One = ConstantInt::get(Int1, 1, true);
// Conditional BranchInst
BranchInst* b1 = BranchInst::Create(bb0, bb1, One);
EXPECT_FALSE(b1->isUnconditional());
EXPECT_TRUE(b1->isConditional());
EXPECT_EQ(b1->getNumSuccessors(), 2U);
// check num operands
EXPECT_EQ(b1->getNumOperands(), 3U);
User::const_op_iterator b(b1->op_begin());
// check COND
EXPECT_NE(b, b1->op_end());
EXPECT_EQ(*b, One);
EXPECT_EQ(b1->getOperand(0), One);
EXPECT_EQ(b1->getCondition(), One);
++b;
// check ELSE
EXPECT_EQ(*b, bb1);
EXPECT_EQ(b1->getOperand(1), bb1);
EXPECT_EQ(b1->getSuccessor(1), bb1);
++b;
// check THEN
EXPECT_EQ(*b, bb0);
EXPECT_EQ(b1->getOperand(2), bb0);
EXPECT_EQ(b1->getSuccessor(0), bb0);
++b;
EXPECT_EQ(b, b1->op_end());
// shrink it
b1->setUnconditionalDest(bb1);
// check num operands
EXPECT_EQ(b1->getNumOperands(), 1U);
User::const_op_iterator c(b1->op_begin());
EXPECT_NE(c, b1->op_end());
// check THEN
EXPECT_EQ(*c, bb1);
EXPECT_EQ(b1->getOperand(0), bb1);
EXPECT_EQ(b1->getSuccessor(0), bb1);
++c;
EXPECT_EQ(c, b1->op_end());
// clean up
delete b0;
delete b1;
delete bb0;
delete bb1;
}
} // end anonymous namespace
} // end namespace llvm
<|endoftext|> |
<commit_before>/*
Copyright 2015-2020 Igor Petrovic
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 <avr/power.h>
#include <avr/eeprom.h>
#include <util/crc16.h>
#include <avr/wdt.h>
#include "board/Board.h"
#include "board/Internal.h"
#include "board/common/constants/Reboot.h"
#include "core/src/general/ADC.h"
#include "core/src/arch/avr/Misc.h"
#include "core/src/general/IO.h"
#include "core/src/general/Interrupt.h"
#include "core/src/general/Reset.h"
#include "bootloader/Config.h"
extern "C" void __cxa_pure_virtual()
{
while (1)
;
}
namespace Board
{
void init()
{
DISABLE_INTERRUPTS();
//clear reset source
MCUSR &= ~(1 << EXTRF);
//disable watchdog
MCUSR &= ~(1 << WDRF);
wdt_disable();
//disable clock division
clock_prescale_set(clock_div_1);
detail::setup::io();
#ifdef FW_APP
#ifndef USB_LINK_MCU
detail::setup::adc();
#else
UART::init(UART_USB_LINK_CHANNEL, UART_BAUDRATE_MIDI_OD);
#endif
#ifdef USB_MIDI_SUPPORTED
detail::setup::usb();
#endif
detail::setup::timers();
#else
detail::setup::bootloader();
//relocate the interrupt vector table to the bootloader section
//note: if this point is reached, bootloader is active
MCUCR = (1 << IVCE);
MCUCR = (1 << IVSEL);
#endif
ENABLE_INTERRUPTS();
}
bool checkNewRevision()
{
uint16_t crc_eeprom = eeprom_read_word(reinterpret_cast<uint16_t*>(SW_CRC_LOCATION_EEPROM));
#if (FLASHEND > 0xFFFF)
uint32_t lastAddress = pgm_read_dword_far(core::misc::pgmGetFarAddress(APP_LENGTH_LOCATION));
uint16_t crc_flash = pgm_read_word_far(core::misc::pgmGetFarAddress(lastAddress));
#else
uint32_t lastAddress = pgm_read_dword(APP_LENGTH_LOCATION);
uint16_t crc_flash = pgm_read_word(lastAddress);
#endif
if (crc_eeprom != crc_flash)
{
eeprom_update_word(reinterpret_cast<uint16_t*>(SW_CRC_LOCATION_EEPROM), crc_flash);
return true;
}
return false;
}
namespace detail
{
void runApplication()
{
__asm__ __volatile__(
// Jump to RST vector
"clr r30\n"
"clr r31\n"
"ijmp\n");
}
bool isAppCRCvalid()
{
if (pgm_read_word(0) == 0xFFFF)
return false;
uint16_t crc = 0x0000;
#if (FLASHEND > 0xFFFF)
uint32_t lastAddress = pgm_read_word(core::misc::pgmGetFarAddress(APP_LENGTH_LOCATION));
#else
uint32_t lastAddress = pgm_read_word(APP_LENGTH_LOCATION);
#endif
for (uint32_t i = 0; i < lastAddress; i++)
{
#if (FLASHEND > 0xFFFF)
crc = _crc_xmodem_update(crc, pgm_read_byte_far(core::misc::pgmGetFarAddress(i)));
#else
crc = _crc_xmodem_update(crc, pgm_read_byte(i));
#endif
}
#if (FLASHEND > 0xFFFF)
return (crc == pgm_read_word_far(core::misc::pgmGetFarAddress(lastAddress)));
#else
return (crc == pgm_read_word(lastAddress));
#endif
}
} // namespace detail
} // namespace Board<commit_msg>bootloader: avr/always use pgm_read_word when retrieving last flash address<commit_after>/*
Copyright 2015-2020 Igor Petrovic
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 <avr/power.h>
#include <avr/eeprom.h>
#include <util/crc16.h>
#include <avr/wdt.h>
#include "board/Board.h"
#include "board/Internal.h"
#include "board/common/constants/Reboot.h"
#include "core/src/general/ADC.h"
#include "core/src/arch/avr/Misc.h"
#include "core/src/general/IO.h"
#include "core/src/general/Interrupt.h"
#include "core/src/general/Reset.h"
#include "bootloader/Config.h"
extern "C" void __cxa_pure_virtual()
{
while (1)
;
}
namespace Board
{
void init()
{
DISABLE_INTERRUPTS();
//clear reset source
MCUSR &= ~(1 << EXTRF);
//disable watchdog
MCUSR &= ~(1 << WDRF);
wdt_disable();
//disable clock division
clock_prescale_set(clock_div_1);
detail::setup::io();
#ifdef FW_APP
#ifndef USB_LINK_MCU
detail::setup::adc();
#else
UART::init(UART_USB_LINK_CHANNEL, UART_BAUDRATE_MIDI_OD);
#endif
#ifdef USB_MIDI_SUPPORTED
detail::setup::usb();
#endif
detail::setup::timers();
#else
detail::setup::bootloader();
//relocate the interrupt vector table to the bootloader section
//note: if this point is reached, bootloader is active
MCUCR = (1 << IVCE);
MCUCR = (1 << IVSEL);
#endif
ENABLE_INTERRUPTS();
}
bool checkNewRevision()
{
uint16_t crc_eeprom = eeprom_read_word(reinterpret_cast<uint16_t*>(SW_CRC_LOCATION_EEPROM));
#if (FLASHEND > 0xFFFF)
uint32_t lastAddress = pgm_read_dword_far(core::misc::pgmGetFarAddress(APP_LENGTH_LOCATION));
uint16_t crc_flash = pgm_read_word_far(core::misc::pgmGetFarAddress(lastAddress));
#else
uint32_t lastAddress = pgm_read_dword(APP_LENGTH_LOCATION);
uint16_t crc_flash = pgm_read_word(lastAddress);
#endif
if (crc_eeprom != crc_flash)
{
eeprom_update_word(reinterpret_cast<uint16_t*>(SW_CRC_LOCATION_EEPROM), crc_flash);
return true;
}
return false;
}
namespace detail
{
void runApplication()
{
__asm__ __volatile__(
// Jump to RST vector
"clr r30\n"
"clr r31\n"
"ijmp\n");
}
bool isAppCRCvalid()
{
if (pgm_read_word(0) == 0xFFFF)
return false;
uint16_t crc = 0x0000;
uint32_t lastAddress = pgm_read_word(APP_LENGTH_LOCATION);
for (uint32_t i = 0; i < lastAddress; i++)
{
#if (FLASHEND > 0xFFFF)
crc = _crc_xmodem_update(crc, pgm_read_byte_far(core::misc::pgmGetFarAddress(i)));
#else
crc = _crc_xmodem_update(crc, pgm_read_byte(i));
#endif
}
#if (FLASHEND > 0xFFFF)
return (crc == pgm_read_word_far(core::misc::pgmGetFarAddress(lastAddress)));
#else
return (crc == pgm_read_word(lastAddress));
#endif
}
} // namespace detail
} // namespace Board<|endoftext|> |
<commit_before>// Fundamentals
#include <iostream>
// Windows headers
#include <Windows.h>
// Kinect Api
#include "NuiApi.h"
#include "Kinect.h"
using namespace ozansKinect;
Kinect::Kinect()
:pNuiSensor(NULL),
kinectWorkingStatus(true),
coordinateX(0), coordinateY(0)
{
}
Kinect::~Kinect()
{
pNuiSensor->NuiShutdown();
//pNuiSensor = nullptr; // neden olmuyor ?
}
HRESULT Kinect::Initialize()
{
INuiSensor* tempNuiSensor;
int iSensorCount = 0;
HRESULT hr = NuiGetSensorCount(&iSensorCount);
if (FAILED(hr))
{
return hr;
}
// Look at each Kinect sensor
for (int i = 0; i < iSensorCount; i++)
{
// Create the sensor so we can check status,
// if we can't create it, move on
hr = NuiCreateSensorByIndex(i, &tempNuiSensor);
if (FAILED(hr))
{
return hr;
}
// Get the status of the sensor, and if connected
// then we can initialize it
hr = tempNuiSensor->NuiStatus();
if (S_OK == hr)
{
pNuiSensor = tempNuiSensor;
break;
}
// This sensor wasn't OK,
// so release it since we're not using it
tempNuiSensor->Release();
}
if (pNuiSensor != NULL)
{
hr = pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON);
if (SUCCEEDED(hr))
{
return hr;
}
}
// Always success for create kinect
return hr;
}
void Kinect::ProcessSkeleton()
{
// Create skeleton frame
NUI_SKELETON_FRAME skeletonFrame = { 0 };
HRESULT hr = pNuiSensor->NuiSkeletonGetNextFrame(LATECY, &skeletonFrame);
if (FAILED(hr))
{
return;
}
// Smooth skeleton data
//pNuiSensor->NuiTransformSmooth(&skeletonFrame, NULL);
for (int i = 0; i < NUI_SKELETON_COUNT; i++)
{
NUI_SKELETON_TRACKING_STATE trackingState = skeletonFrame.SkeletonData[i].eTrackingState;
if (NUI_SKELETON_TRACKED == trackingState)
{
// We're traking the skeleton, write coordinate
setCoordinate2Sens(skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].x, skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].y);
std::cout << getCoordinateX() << std::endl << getCoordinateY() << std::endl;
if (getCoordinateY() == 0 && getCoordinateX() == 0)
{
setKinectExit(false);
}
// setCoordinate2Sens() BURADAN DEVAM *********************
}
}
return;
}
void Kinect::setKinectExit(const bool x)
{
kinectWorkingStatus = x;
}
bool Kinect::getKinectExit() const
{
return kinectWorkingStatus;
}
void Kinect::setCoordinate2Sens(const double x, const double y)
{
coordinateX = x * 100;
coordinateY = y * 100;
}
void ozansKinect::Kinect::setCoordinate3Sens(const double x, const double y)
{
coordinateX = x * 1000;
coordinateY = y * 1000;
}
int Kinect::getCoordinateX() const
{
return coordinateX;
}
int Kinect::getCoordinateY() const
{
return coordinateY;
}
<commit_msg>Some editing<commit_after>// Fundamentals
#include <iostream>
// Windows headers
#include <Windows.h>
// Kinect Api
#include "NuiApi.h"
#include "Kinect.h"
ozansKinect::Kinect::Kinect()
:pNuiSensor(NULL),
kinectWorkingStatus(true),
coordinateX(0), coordinateY(0)
{
}
ozansKinect::Kinect::~Kinect()
{
pNuiSensor->NuiShutdown();
//pNuiSensor = nullptr; // neden olmuyor ?
}
HRESULT ozansKinect::Kinect::Initialize()
{
INuiSensor* tempNuiSensor;
int iSensorCount = 0;
HRESULT hr = NuiGetSensorCount(&iSensorCount);
if (FAILED(hr))
{
return hr;
}
// Look at each Kinect sensor
for (int i = 0; i < iSensorCount; i++)
{
// Create the sensor so we can check status,
// if we can't create it, move on
hr = NuiCreateSensorByIndex(i, &tempNuiSensor);
if (FAILED(hr))
{
return hr;
}
// Get the status of the sensor, and if connected
// then we can initialize it
hr = tempNuiSensor->NuiStatus();
if (S_OK == hr)
{
pNuiSensor = tempNuiSensor;
break;
}
// This sensor wasn't OK,
// so release it since we're not using it
tempNuiSensor->Release();
}
if (pNuiSensor != NULL)
{
hr = pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON);
if (SUCCEEDED(hr))
{
return hr;
}
}
// Always success for create kinect
return hr;
}
void ozansKinect::Kinect::ProcessSkeleton()
{
// Create skeleton frame
NUI_SKELETON_FRAME skeletonFrame = { 0 };
HRESULT hr = pNuiSensor->NuiSkeletonGetNextFrame(LATECY, &skeletonFrame);
if (FAILED(hr))
{
return;
}
// Smooth skeleton data
//pNuiSensor->NuiTransformSmooth(&skeletonFrame, NULL);
for (int i = 0; i < NUI_SKELETON_COUNT; i++)
{
NUI_SKELETON_TRACKING_STATE trackingState = skeletonFrame.SkeletonData[i].eTrackingState;
if (NUI_SKELETON_TRACKED == trackingState)
{
// We're traking the skeleton, write coordinate
setCoordinate2Sens(skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].x, skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].y);
std::cout << getCoordinateX() << std::endl << getCoordinateY() << std::endl;
if (getCoordinateY() == 0 && getCoordinateX() == 0)
{
setKinectExit(false);
}
// setCoordinate2Sens() BURADAN DEVAM *********************
}
}
return;
}
void ozansKinect::Kinect::setKinectExit(const bool x)
{
kinectWorkingStatus = x;
}
bool ozansKinect::Kinect::getKinectExit() const
{
return kinectWorkingStatus;
}
void ozansKinect::Kinect::setCoordinate2Sens(const double x, const double y)
{
coordinateX = x * 100;
coordinateY = y * 100;
}
void ozansKinect::Kinect::setCoordinate3Sens(const double x, const double y)
{
coordinateX = x * 1000;
coordinateY = y * 1000;
}
int ozansKinect::Kinect::getCoordinateX() const
{
return coordinateX;
}
int ozansKinect::Kinect::getCoordinateY() const
{
return coordinateY;
}
<|endoftext|> |
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Capture.h"
#include "cinder/Log.h"
#include "GridTexture.h"
#include "Landscape.h"
#include "Constants.h"
#ifdef CINDER_COCOA_TOUCH
#include "cinder/MotionManager.h"
#endif
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
struct TouchInfo {
uint32_t id;
vec2 previous;
vec2 position;
};
class GridSpaceApp : public App {
public:
void setup() override;
void touchesBegan( TouchEvent event ) override;
void touchesMoved( TouchEvent event ) override;
void touchesEnded( TouchEvent event ) override;
void pinchStart();
void pinchUpdate();
void pinchEnd();
void update() override;
void draw() override;
void drawSimpleAndroidTestStuff() const;
private:
CaptureRef capture;
CameraPersp camera;
GridTextureRef gridTexture;
Landscape landscape;
bool doDrawDebug = false;
vector<TouchInfo> touches;
ci::vec3 cameraOffset;
};
void GridSpaceApp::setup()
{
CI_LOG_I("Setting up selfie_x_selfie");
#ifdef CINDER_COCOA_TOUCH
MotionManager::enable();
#endif
GLint size;
glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
CI_LOG_I( "Max texture size: " << size );
auto target = vec3( 5, 0, 0 );
camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 1000 );
/*
try {
CI_LOG_I("Attempting to set up camera input.");
auto front_facing_camera = ([] {
auto &devices = Capture::getDevices();
auto first_device = devices.front();
for( auto device : devices ) {
if( device->isFrontFacing() ) {
return device;
}
}
return first_device;
}());
capture = Capture::create( 480, 360, front_facing_camera );
capture->start();
const auto divisions = 8;
const auto size = divisions * capture->getSize();
gridTexture = make_shared<GridTexture>( size.x, size.y, divisions );
}
catch( ci::Exception &exc ) {
CI_LOG_E( "Error using device camera: " << exc.what() );
}
//*/
auto tex_size = vec2( 640, 480 );
gridTexture = make_shared<GridTexture>( tex_size.x, tex_size.y, 8 );
landscape.setup();
}
void GridSpaceApp::touchesBegan( TouchEvent event )
{
CI_LOG_I("Touches began");
console() << "Touches began." << endl;
for( auto &t : event.getTouches() ) {
touches.push_back( { t.getId(), t.getPos(), t.getPos() } );
}
if( touches.size() == 2 ) {
pinchStart();
}
}
void GridSpaceApp::touchesMoved( TouchEvent event )
{
CI_LOG_I("Touches moved");
console() << "Touches moved." << endl;
for( auto &t : event.getTouches() ) {
for( auto &s : touches ) {
if( s.id == t.getId() ) {
s.previous = s.position;
s.position = t.getPos();
}
}
}
if( touches.size() == 2 ) {
pinchUpdate();
}
}
void GridSpaceApp::touchesEnded( TouchEvent event )
{
console() << "Touches ended." << endl;
touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
for( auto &t : event.getTouches() ) {
if (t.getId() == s.id) {
return true;
}
}
return false;
}), touches.end() );
}
void GridSpaceApp::pinchStart()
{
}
void GridSpaceApp::pinchUpdate()
{
console() << "Pinch update." << endl;
auto base = distance(touches.at( 0 ).previous, touches.at( 1 ).previous);
auto current = distance(touches.at( 0 ).position, touches.at( 1 ).position);
auto delta = current - base;
if( isfinite( delta ) )
{
auto ray = camera.getViewDirection();
cameraOffset += delta * ray * 0.01f;
}
}
void GridSpaceApp::update()
{
auto l = length(cameraOffset);
auto maximum = 3.0f;
if( l > maximum ) {
cameraOffset *= (maximum / l);
}
camera.setEyePoint( cameraOffset );
#ifdef CINDER_COCOA_TOUCH
if( MotionManager::isDataAvailable() ) {
auto r = MotionManager::getRotation();
camera.setOrientation( r );
}
#endif
/*
if( capture->checkNewFrame() ) {
gridTexture->update( *capture->getSurface() );
}
*/
}
void GridSpaceApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableDepthRead();
gl::enableDepthWrite();
gl::setMatrices( camera );
landscape.draw( gridTexture->getCurrentIndex() );
drawSimpleAndroidTestStuff();
/*
if( doDrawDebug )
{
if( gridTexture->getTexture() )
{
auto size = vec2(getWindowSize()) * vec2(1.0, 0.5);
gl::ScopedMatrices mat;
gl::setMatricesWindow( app::getWindowSize() );
gl::draw( gridTexture->getTexture(), Rectf( vec2(0), size ) );
gl::translate( size * vec2(0, 1) );
gl::draw( gridTexture->getBlurredTexture(), Rectf( vec2(0), size ) );
}
}
*/
}
void GridSpaceApp::drawSimpleAndroidTestStuff() const
{
gl::ScopedColor color( Color( 1.0f, 0.0f, 1.0f ) );
gl::ScopedMatrices matrices;
gl::drawSphere( vec3( 5, 0, 0 ), 1.0f, -1 );
gl::setMatricesWindow( getWindowSize() );
gl::color( 1.0f, 1.0f, 0.0f );
gl::drawSolidCircle( vec2( 100.0f, 100.0f ), 20.0f );
gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
}
inline void prepareSettings(app::App::Settings *settings)
{
settings->setMultiTouchEnabled();
}
CINDER_APP( GridSpaceApp, RendererGl, &prepareSettings )
<commit_msg>Remove drawing stuff, android crashed...<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Capture.h"
#include "cinder/Log.h"
#include "GridTexture.h"
#include "Landscape.h"
#include "Constants.h"
#ifdef CINDER_COCOA_TOUCH
#include "cinder/MotionManager.h"
#endif
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
struct TouchInfo {
uint32_t id;
vec2 previous;
vec2 position;
};
class GridSpaceApp : public App {
public:
void setup() override;
void touchesBegan( TouchEvent event ) override;
void touchesMoved( TouchEvent event ) override;
void touchesEnded( TouchEvent event ) override;
void pinchStart();
void pinchUpdate();
void pinchEnd();
void update() override;
void draw() override;
void drawSimpleAndroidTestStuff() const;
private:
CaptureRef capture;
CameraPersp camera;
GridTextureRef gridTexture;
Landscape landscape;
bool doDrawDebug = false;
vector<TouchInfo> touches;
ci::vec3 cameraOffset;
};
void GridSpaceApp::setup()
{
CI_LOG_I("Setting up selfie_x_selfie");
#ifdef CINDER_COCOA_TOUCH
MotionManager::enable();
#endif
GLint size;
glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
CI_LOG_I( "Max texture size: " << size );
auto target = vec3( 5, 0, 0 );
camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 1000 );
/*
try {
CI_LOG_I("Attempting to set up camera input.");
auto front_facing_camera = ([] {
auto &devices = Capture::getDevices();
auto first_device = devices.front();
for( auto device : devices ) {
if( device->isFrontFacing() ) {
return device;
}
}
return first_device;
}());
capture = Capture::create( 480, 360, front_facing_camera );
capture->start();
const auto divisions = 8;
const auto size = divisions * capture->getSize();
gridTexture = make_shared<GridTexture>( size.x, size.y, divisions );
}
catch( ci::Exception &exc ) {
CI_LOG_E( "Error using device camera: " << exc.what() );
}
//*/
/*
auto tex_size = vec2( 640, 480 );
gridTexture = make_shared<GridTexture>( tex_size.x, tex_size.y, 8 );
landscape.setup();
*/
}
void GridSpaceApp::touchesBegan( TouchEvent event )
{
CI_LOG_I("Touches began");
console() << "Touches began." << endl;
for( auto &t : event.getTouches() ) {
touches.push_back( { t.getId(), t.getPos(), t.getPos() } );
}
if( touches.size() == 2 ) {
pinchStart();
}
}
void GridSpaceApp::touchesMoved( TouchEvent event )
{
CI_LOG_I("Touches moved");
console() << "Touches moved." << endl;
for( auto &t : event.getTouches() ) {
for( auto &s : touches ) {
if( s.id == t.getId() ) {
s.previous = s.position;
s.position = t.getPos();
}
}
}
if( touches.size() == 2 ) {
pinchUpdate();
}
}
void GridSpaceApp::touchesEnded( TouchEvent event )
{
console() << "Touches ended." << endl;
touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
for( auto &t : event.getTouches() ) {
if (t.getId() == s.id) {
return true;
}
}
return false;
}), touches.end() );
}
void GridSpaceApp::pinchStart()
{
}
void GridSpaceApp::pinchUpdate()
{
console() << "Pinch update." << endl;
auto base = distance(touches.at( 0 ).previous, touches.at( 1 ).previous);
auto current = distance(touches.at( 0 ).position, touches.at( 1 ).position);
auto delta = current - base;
if( isfinite( delta ) )
{
auto ray = camera.getViewDirection();
cameraOffset += delta * ray * 0.01f;
}
}
void GridSpaceApp::update()
{
auto l = length(cameraOffset);
auto maximum = 3.0f;
if( l > maximum ) {
cameraOffset *= (maximum / l);
}
camera.setEyePoint( cameraOffset );
#ifdef CINDER_COCOA_TOUCH
if( MotionManager::isDataAvailable() ) {
auto r = MotionManager::getRotation();
camera.setOrientation( r );
}
#endif
/*
if( capture->checkNewFrame() ) {
gridTexture->update( *capture->getSurface() );
}
*/
}
void GridSpaceApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableDepthRead();
gl::enableDepthWrite();
gl::setMatrices( camera );
/*
gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
landscape.draw( gridTexture->getCurrentIndex() );
*/
drawSimpleAndroidTestStuff();
/*
if( doDrawDebug )
{
if( gridTexture->getTexture() )
{
auto size = vec2(getWindowSize()) * vec2(1.0, 0.5);
gl::ScopedMatrices mat;
gl::setMatricesWindow( app::getWindowSize() );
gl::draw( gridTexture->getTexture(), Rectf( vec2(0), size ) );
gl::translate( size * vec2(0, 1) );
gl::draw( gridTexture->getBlurredTexture(), Rectf( vec2(0), size ) );
}
}
*/
}
void GridSpaceApp::drawSimpleAndroidTestStuff() const
{
gl::ScopedColor color( Color( 1.0f, 0.0f, 1.0f ) );
gl::ScopedMatrices matrices;
gl::drawSphere( vec3( 5, 0, 0 ), 1.0f, -1 );
gl::setMatricesWindow( getWindowSize() );
gl::color( 1.0f, 1.0f, 0.0f );
gl::drawSolidCircle( vec2( 100.0f, 100.0f ), 20.0f );
}
inline void prepareSettings(app::App::Settings *settings)
{
settings->setMultiTouchEnabled();
}
CINDER_APP( GridSpaceApp, RendererGl, &prepareSettings )
<|endoftext|> |
<commit_before>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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>
#include <fstream>
#include <sstream>
#include <typeinfo>
#include <time.h>
#define SEQAN_DEBUG
//#define SEQAN_TEST
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h> // Header under test.
#include "test_embl.h"
#include "test_file.h"
SEQAN_BEGIN_TESTSUITE(test_file)
{
SEQAN_CALL_TEST(test_file_stream);
SEQAN_CALL_TEST(test_file_cstream);
SEQAN_CALL_TEST(test_file_raw);
SEQAN_CALL_TEST(test_file_fasta_crlf);
SEQAN_CALL_TEST(test_file_fasta_lf);
SEQAN_CALL_TEST(test_file_fasta_cr);
SEQAN_CALL_TEST(test_file_fasta_write);
SEQAN_CALL_TEST(test_file_cgviz);
SEQAN_CALL_TEST(test_file_fasta_align);
SEQAN_CALL_TEST(test_file_embl);
SEQAN_CALL_TEST(test_file_genbank);
// SEQAN_CALL_TEST(test_file_reader_iterator);
SEQAN_CALL_TEST(test_file_reader_string);
// SEQAN_CALL_TEST(test_file_reader_string2_fasta);
// SEQAN_CALL_TEST(test_file_reader_string2_embl);
// SEQAN_CALL_TEST(test_file_reader_string2_genbank);
SEQAN_CALL_TEST(test_file_reader_string3);
SEQAN_CALL_TEST(test_file_embl_file);
SEQAN_CALL_TEST(test_file_embl_meta);
}
SEQAN_END_TESTSUITE
<commit_msg>[FIX] Disabling test for writing of CGViz.<commit_after>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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>
#include <fstream>
#include <sstream>
#include <typeinfo>
#include <time.h>
#define SEQAN_DEBUG
//#define SEQAN_TEST
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h> // Header under test.
#include "test_embl.h"
#include "test_file.h"
SEQAN_BEGIN_TESTSUITE(test_file)
{
SEQAN_CALL_TEST(test_file_stream);
SEQAN_CALL_TEST(test_file_cstream);
SEQAN_CALL_TEST(test_file_raw);
SEQAN_CALL_TEST(test_file_fasta_crlf);
SEQAN_CALL_TEST(test_file_fasta_lf);
SEQAN_CALL_TEST(test_file_fasta_cr);
SEQAN_CALL_TEST(test_file_fasta_write);
// TODO(holtgrew): Reading FastaAlign is not portable right now.
//SEQAN_CALL_TEST(test_file_cgviz);
SEQAN_CALL_TEST(test_file_fasta_align);
SEQAN_CALL_TEST(test_file_embl);
SEQAN_CALL_TEST(test_file_genbank);
// SEQAN_CALL_TEST(test_file_reader_iterator);
SEQAN_CALL_TEST(test_file_reader_string);
// SEQAN_CALL_TEST(test_file_reader_string2_fasta);
// SEQAN_CALL_TEST(test_file_reader_string2_embl);
// SEQAN_CALL_TEST(test_file_reader_string2_genbank);
SEQAN_CALL_TEST(test_file_reader_string3);
SEQAN_CALL_TEST(test_file_embl_file);
SEQAN_CALL_TEST(test_file_embl_meta);
}
SEQAN_END_TESTSUITE
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <time.h>
#include "util.h"
#if defined linux
#include <unistd.h> // Microsoft Visual C++ do not has this header
#endif
#if defined WIN32
#include <windows.h> // POSIX-only environment do not has this header
#endif
namespace util{
#if defined linux
void milliSleep(int ms) {
timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000L;
nanosleep(&ts, NULL);
}
#endif
#if defined WIN32
void milliSleep(int ms) {
sleep(ms);
}
#endif
int random(int range) {
return rand() % range;
}
bool operator == (const point a, const point b) {
return a.x == b.x && a.y == b.y;
}
bool operator != (const point a, const point b) {
return !(a == b);
}
point operator - (const point a) {
return point(-a.x, -a.y);
}
point operator + (const point a, const point b) {
return point(a.x + b.x, a.y + b.y);
}
point &operator += (point &a, const point b) {
a.x += b.x;
a.y += b.y;
return a;
}
point operator - (const point a, const point b) {
return a + (-b);
}
}
<commit_msg>util: change #ifdef macro<commit_after>#include <stdlib.h>
#include <time.h>
#include "util.h"
#if defined _POSIX_SOURCE
#include <unistd.h> // Microsoft Visual C++ do not has this header
#endif
#if defined WIN32
#include <windows.h> // POSIX-only environment do not has this header
#endif
namespace util{
#if defined _POSIX_SOURCE
void milliSleep(int ms) {
timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000L;
nanosleep(&ts, NULL);
}
#endif
#if defined WIN32
void milliSleep(int ms) {
sleep(ms);
}
#endif
int random(int range) {
return rand() % range;
}
bool operator == (const point a, const point b) {
return a.x == b.x && a.y == b.y;
}
bool operator != (const point a, const point b) {
return !(a == b);
}
point operator - (const point a) {
return point(-a.x, -a.y);
}
point operator + (const point a, const point b) {
return point(a.x + b.x, a.y + b.y);
}
point &operator += (point &a, const point b) {
a.x += b.x;
a.y += b.y;
return a;
}
point operator - (const point a, const point b) {
return a + (-b);
}
}
<|endoftext|> |
<commit_before>// $Id$
// Category: run
//
// See the class description in the header file.
#include "TGeant4.h"
#include "TG4Messenger.h"
#include "TG4GeometryManager.h"
#include "TG4PhysicsManager.h"
#include "TG4StepManager.h"
#include "TG4VisManager.h"
#include "TG4RunManager.h"
#include "TG4Globals.h"
TGeant4::TGeant4(const char* name, const char* title,
TG4VRunConfiguration* configuration, int argc, char** argv)
: AliMC(name, title),
fVisManager(0)
{
// create run manager
fRunManager = new TG4RunManager(configuration, argc, argv);
// add verbose level
//G4cout << "TG4RunManager has been created." << endl;
// create geometry manager
fGeometryManager = new TG4GeometryManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create physics manager
fPhysicsManager = new TG4PhysicsManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create step manager
fStepManager = new TG4StepManager();
// add verbose level
//G4cout << "TG4StepManager has been created." << endl;
#ifdef G4VIS_USE
// create visualization manager
fVisManager = new TG4VisManager();
fVisManager->Initialize();
#endif
// create messenger
fMessenger =
new TG4Messenger(fGeometryManager, fPhysicsManager, fStepManager);
}
TGeant4::TGeant4(const char* name, const char* title,
TG4VRunConfiguration* configuration)
: AliMC(name, title),
fVisManager(0)
{
// create run manager
fRunManager = new TG4RunManager(configuration);
// add verbose level
//G4cout << "TG4RunManager has been created." << endl;
// create geometry manager
fGeometryManager = new TG4GeometryManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create physics manager
fPhysicsManager = new TG4PhysicsManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create step manager
fStepManager = new TG4StepManager();
// add verbose level
//G4cout << "TG4StepManager has been created." << endl;
#ifdef G4VIS_USE
// create visualization manager
fVisManager = new TG4VisManager();
fVisManager->Initialize();
#endif
// create messenger
fMessenger =
new TG4Messenger(fGeometryManager, fPhysicsManager, fStepManager);
}
TGeant4::TGeant4() {
//
}
TGeant4::TGeant4(const TGeant4& right) {
//
TG4Globals::Exception("TGeant4 is protected from copying.");
}
TGeant4::~TGeant4() {
//
delete fRunManager;
delete fGeometryManager;
delete fPhysicsManager;
delete fStepManager;
// fVisManager is deleted with G4RunManager destructor
delete fMessenger;
}
// operators
TGeant4& TGeant4::operator=(const TGeant4& right)
{
// check assignement to self
if (this == &right) return *this;
TG4Globals::Exception("TGeant4 is protected from assigning.");
return *this;
}
// methods for building/management of geometry
// ------------------------------------------------
void TGeant4::FinishGeometry() {
//
fGeometryManager->Ggclos();
}
void TGeant4::Gfmate(Int_t imat, char *name, Float_t &a, Float_t &z,
Float_t &dens, Float_t &radl, Float_t &absl,
Float_t* ubuf, Int_t& nbuf) {
//
fGeometryManager
->Gfmate(imat, name, a, z, dens, radl, absl, ubuf, nbuf);
}
void TGeant4::Material(Int_t& kmat, const char* name, Float_t a,
Float_t z, Float_t dens, Float_t radl, Float_t absl,
Float_t* buf, Int_t nwbuf) {
//
fGeometryManager
->Material(kmat, name, a, z, dens, radl, absl, buf, nwbuf);
}
void TGeant4::Mixture(Int_t& kmat, const char *name, Float_t *a,
Float_t *z, Float_t dens, Int_t nlmat, Float_t *wmat) {
//
fGeometryManager
->Mixture(kmat, name, a, z, dens, nlmat, wmat);
}
void TGeant4::Medium(Int_t& kmed, const char *name, Int_t nmat,
Int_t isvol, Int_t ifield, Float_t fieldm, Float_t tmaxfd,
Float_t stemax, Float_t deemax, Float_t epsil,
Float_t stmin, Float_t* ubuf, Int_t nbuf) {
//
fGeometryManager
->Medium(kmed, name, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax,
epsil, stmin, ubuf, nbuf);
}
void TGeant4::Matrix(Int_t& krot, Float_t thetaX, Float_t phiX,
Float_t thetaY, Float_t phiY, Float_t thetaZ,
Float_t phiZ) {
//
fGeometryManager
->Matrix(krot, thetaX, phiX, thetaY, phiY, thetaZ, phiZ);
}
void TGeant4::Gstpar(Int_t itmed, const char *param, Float_t parval) {
//
fGeometryManager->Gstpar(itmed, param, parval);
}
void TGeant4::Gsckov(Int_t itmed, Int_t npckov, Float_t *ppckov,
Float_t *absco, Float_t *effic, Float_t *rindex) {
//
fGeometryManager->Gsckov(itmed, npckov, ppckov, absco, effic, rindex);
}
Int_t TGeant4::Gsvolu(const char *name, const char *shape, Int_t nmed,
Float_t *upar, Int_t np) {
//
return fGeometryManager->Gsvolu(name, shape, nmed, upar, np);
}
void TGeant4::Gsdvn(const char *name, const char *mother, Int_t ndiv,
Int_t iaxis) {
//
fGeometryManager->Gsdvn(name, mother, ndiv, iaxis);
}
void TGeant4::Gsdvn2(const char *name, const char *mother, Int_t ndiv,
Int_t iaxis, Float_t c0i, Int_t numed) {
//
fGeometryManager->Gsdvn2(name, mother, ndiv, iaxis, c0i, numed);
}
void TGeant4::Gsdvt(const char *name, const char *mother, Float_t step,
Int_t iaxis, Int_t numed, Int_t ndvmx) {
//
fGeometryManager->Gsdvt(name, mother, step, iaxis, numed, ndvmx);
}
void TGeant4::Gsdvt2(const char *name, const char *mother, Float_t step,
Int_t iaxis, Float_t c0, Int_t numed, Int_t ndvmx) {
//
fGeometryManager->Gsdvt2(name, mother, step, iaxis, c0, numed, ndvmx);
}
void TGeant4::Gsord(const char *name, Int_t iax) {
//
fGeometryManager->Gsord(name, iax);
}
void TGeant4::Gspos(const char *name, Int_t nr, const char *mother,
Float_t x, Float_t y, Float_t z, Int_t irot,
const char *konly) {
//
fGeometryManager->Gspos(name, nr, mother, x, y, z, irot, konly);
}
void TGeant4::Gsposp(const char *name, Int_t nr, const char *mother,
Float_t x, Float_t y, Float_t z, Int_t irot,
const char *konly, Float_t *upar, Int_t np) {
//
fGeometryManager->Gsposp(name, nr, mother, x, y, z, irot, konly, upar, np);
}
void TGeant4::WriteEuclid(const char* fileName, const char* topVol,
Int_t number, Int_t nlevel) {
//
fGeometryManager->WriteEuclid(fileName, topVol, number, nlevel);
}
Int_t TGeant4::VolId(const Text_t* volName) const {
//
return fGeometryManager->VolId(volName);
}
const char* TGeant4::VolName(Int_t id) const {
//
return fGeometryManager->VolName(id);
}
Int_t TGeant4::NofVolumes() const {
//
return fGeometryManager->NofVolumes();
}
// methods for physics management
// ------------------------------------------------
void TGeant4::BuildPhysics() {
//
fPhysicsManager->BuildPhysics();
}
void TGeant4::SetCut(const char* cutName, Float_t cutValue) {
//
fPhysicsManager->SetCut(cutName, cutValue);
}
void TGeant4::SetProcess(const char* flagName, Int_t flagValue) {
//
fPhysicsManager->SetProcess(flagName, flagValue);
}
Float_t TGeant4::Xsec(char* reac, Float_t energy, Int_t part, Int_t mate) {
//
return fPhysicsManager->Xsec(reac, energy, part, mate);
}
Int_t TGeant4::IdFromPDG(Int_t pdgID) const {
//
return fPhysicsManager->IdFromPDG(pdgID);
}
Int_t TGeant4::PDGFromId(Int_t mcID) const {
//
return fPhysicsManager->PDGFromId(mcID);
}
void TGeant4::DefineParticles() {
//
fPhysicsManager->DefineParticles();
}
// methods for step management
// ------------------------------------------------
// inlined (in TGeant4.icc)
void TGeant4::Rndm(Float_t* array, const Int_t size) const {
//
fStepManager->Rndm(array, size);
}
// methods for visualization
// ------------------------------------------------
#ifdef G4VIS_USE
void TGeant4::DrawOneSpec(const char* name) {
//
fVisManager->DrawOneSpec(name);
}
void TGeant4::Gsatt(const char* name, const char* att, Int_t val) {
//
fVisManager->Gsatt(name, att, val);
}
void TGeant4::Gdraw(const char* name, Float_t theta, Float_t phi,
Float_t psi, Float_t u0, Float_t v0,
Float_t ul, Float_t vl) {
//
fVisManager->Gdraw(name, theta, phi, psi, u0, v0, ul, vl);
}
#else
void TGeant4::DrawOneSpec(const char* name) {
//
TG4Globals:: Warning("TGeant4::DrawOneSpec(): no visualization available.");
}
void TGeant4::Gsatt(const char* name, const char* att, Int_t val) {
//
TG4Globals:: Warning("TGeant4::Gsatt(): no visualization available.");
}
void TGeant4::Gdraw(const char* p1, Float_t theta, Float_t phi,
Float_t psi, Float_t u0, Float_t v0,
Float_t ul, Float_t vl) {
//
TG4Globals:: Warning("TGeant4::Gdraw(): no visualization available.");
}
#endif //G4VIS_USE
// methods for run control
// ------------------------------------------------
void TGeant4::Init() {
//
fRunManager->Initialize();
}
void TGeant4::ProcessEvent() {
//
fRunManager->ProcessEvent();
}
void TGeant4::ProcessRun(Int_t nofEvents) {
//
fRunManager->ProcessRun(nofEvents);
}
void TGeant4::StartGeantUI() {
//
fRunManager->StartGeantUI();
}
void TGeant4::StartRootUI() {
//
fRunManager->StartGeantUI();
}
void TGeant4::ProcessGeantMacro(const char* macroName) {
//
fRunManager->ProcessGeantMacro(macroName);
}
void TGeant4::ProcessGeantCommand(const char* command) {
//
fRunManager->ProcessGeantCommand(command);
}
Int_t TGeant4::CurrentEvent() const {
//
return fRunManager->CurrentEvent();
}
// Geant3 specific methods
// !!! need to be transformed to common interface
// ------------------------------------------------
void TGeant4::Gdopt(const char* name, const char* value) {
//
TG4Globals:: Warning("TGeant4::Gdopt(..) is not implemented.");
}
void TGeant4::SetClipBox(const char *name, Float_t xmin, Float_t xmax,
Float_t ymin, Float_t ymax, Float_t zmin, Float_t zmax) {
//
TG4Globals:: Warning("TGeant4::SetClipBox(..) is not implemented.");
}
void TGeant4::DefaultRange() {
//
TG4Globals:: Warning("TGeant4::DefaultRange() is not implemented.");
}
void TGeant4::Gdhead(Int_t isel, const char* name, Float_t chrsiz) {
//
TG4Globals:: Warning("TGeant4::Gdhead(..) is not implemented.");
}
void TGeant4::Gdman(Float_t u, Float_t v, const char* type) {
//
TG4Globals:: Warning("TGeant4::Gdman(..) is not implemented.");
}
void TGeant4::SetColors() {
//
TG4Globals:: Warning("TGeant4::SetColours() is not implemented.");
}
void TGeant4::Gtreve() {
//
TG4Globals:: Warning("TGeant4::Gtreve() is not implemented.");
}
void TGeant4::Gtreve_root() {
//
TG4Globals:: Warning("TGeant4::Gtreve_root() is not implemented.");
}
void TGeant4::Gckmat(Int_t itmed, char* natmed) {
//
TG4Globals:: Warning("TGeant4::Gckmat(..) is not implemented.");
}
void TGeant4::InitLego() {
//
TG4Globals:: Warning("TGeant4::InitLego() is not implemented.");
}
void TGeant4::Gfpart(Int_t ipart, char *name, Int_t& itrtyp,
Float_t& amass, Float_t& charge, Float_t& tlife) {
//
TG4Globals:: Warning("TGeant4::Gfpart(..) is not implemented.");
}
void TGeant4::Gspart(Int_t ipart, const char *name, Int_t itrtyp,
Float_t amass, Float_t charge, Float_t tlife) {
//
TG4Globals:: Warning("TGeant4::Gspart(..) is not implemented.");
}
<commit_msg>method StartRootUI() corrected<commit_after>// $Id$
// Category: run
//
// See the class description in the header file.
#include "TGeant4.h"
#include "TG4Messenger.h"
#include "TG4GeometryManager.h"
#include "TG4PhysicsManager.h"
#include "TG4StepManager.h"
#include "TG4VisManager.h"
#include "TG4RunManager.h"
#include "TG4Globals.h"
TGeant4::TGeant4(const char* name, const char* title,
TG4VRunConfiguration* configuration, int argc, char** argv)
: AliMC(name, title),
fVisManager(0)
{
// create run manager
fRunManager = new TG4RunManager(configuration, argc, argv);
// add verbose level
//G4cout << "TG4RunManager has been created." << endl;
// create geometry manager
fGeometryManager = new TG4GeometryManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create physics manager
fPhysicsManager = new TG4PhysicsManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create step manager
fStepManager = new TG4StepManager();
// add verbose level
//G4cout << "TG4StepManager has been created." << endl;
#ifdef G4VIS_USE
// create visualization manager
fVisManager = new TG4VisManager();
fVisManager->Initialize();
#endif
// create messenger
fMessenger =
new TG4Messenger(fGeometryManager, fPhysicsManager, fStepManager);
}
TGeant4::TGeant4(const char* name, const char* title,
TG4VRunConfiguration* configuration)
: AliMC(name, title),
fVisManager(0)
{
// create run manager
fRunManager = new TG4RunManager(configuration);
// add verbose level
//G4cout << "TG4RunManager has been created." << endl;
// create geometry manager
fGeometryManager = new TG4GeometryManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create physics manager
fPhysicsManager = new TG4PhysicsManager();
// add verbose level
//G4cout << "TG4GeometryManager has been created." << endl;
// create step manager
fStepManager = new TG4StepManager();
// add verbose level
//G4cout << "TG4StepManager has been created." << endl;
#ifdef G4VIS_USE
// create visualization manager
fVisManager = new TG4VisManager();
fVisManager->Initialize();
#endif
// create messenger
fMessenger =
new TG4Messenger(fGeometryManager, fPhysicsManager, fStepManager);
}
TGeant4::TGeant4() {
//
}
TGeant4::TGeant4(const TGeant4& right) {
//
TG4Globals::Exception("TGeant4 is protected from copying.");
}
TGeant4::~TGeant4() {
//
delete fRunManager;
delete fGeometryManager;
delete fPhysicsManager;
delete fStepManager;
// fVisManager is deleted with G4RunManager destructor
delete fMessenger;
}
// operators
TGeant4& TGeant4::operator=(const TGeant4& right)
{
// check assignement to self
if (this == &right) return *this;
TG4Globals::Exception("TGeant4 is protected from assigning.");
return *this;
}
// methods for building/management of geometry
// ------------------------------------------------
void TGeant4::FinishGeometry() {
//
fGeometryManager->Ggclos();
}
void TGeant4::Gfmate(Int_t imat, char *name, Float_t &a, Float_t &z,
Float_t &dens, Float_t &radl, Float_t &absl,
Float_t* ubuf, Int_t& nbuf) {
//
fGeometryManager
->Gfmate(imat, name, a, z, dens, radl, absl, ubuf, nbuf);
}
void TGeant4::Material(Int_t& kmat, const char* name, Float_t a,
Float_t z, Float_t dens, Float_t radl, Float_t absl,
Float_t* buf, Int_t nwbuf) {
//
fGeometryManager
->Material(kmat, name, a, z, dens, radl, absl, buf, nwbuf);
}
void TGeant4::Mixture(Int_t& kmat, const char *name, Float_t *a,
Float_t *z, Float_t dens, Int_t nlmat, Float_t *wmat) {
//
fGeometryManager
->Mixture(kmat, name, a, z, dens, nlmat, wmat);
}
void TGeant4::Medium(Int_t& kmed, const char *name, Int_t nmat,
Int_t isvol, Int_t ifield, Float_t fieldm, Float_t tmaxfd,
Float_t stemax, Float_t deemax, Float_t epsil,
Float_t stmin, Float_t* ubuf, Int_t nbuf) {
//
fGeometryManager
->Medium(kmed, name, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax,
epsil, stmin, ubuf, nbuf);
}
void TGeant4::Matrix(Int_t& krot, Float_t thetaX, Float_t phiX,
Float_t thetaY, Float_t phiY, Float_t thetaZ,
Float_t phiZ) {
//
fGeometryManager
->Matrix(krot, thetaX, phiX, thetaY, phiY, thetaZ, phiZ);
}
void TGeant4::Gstpar(Int_t itmed, const char *param, Float_t parval) {
//
fGeometryManager->Gstpar(itmed, param, parval);
}
void TGeant4::Gsckov(Int_t itmed, Int_t npckov, Float_t *ppckov,
Float_t *absco, Float_t *effic, Float_t *rindex) {
//
fGeometryManager->Gsckov(itmed, npckov, ppckov, absco, effic, rindex);
}
Int_t TGeant4::Gsvolu(const char *name, const char *shape, Int_t nmed,
Float_t *upar, Int_t np) {
//
return fGeometryManager->Gsvolu(name, shape, nmed, upar, np);
}
void TGeant4::Gsdvn(const char *name, const char *mother, Int_t ndiv,
Int_t iaxis) {
//
fGeometryManager->Gsdvn(name, mother, ndiv, iaxis);
}
void TGeant4::Gsdvn2(const char *name, const char *mother, Int_t ndiv,
Int_t iaxis, Float_t c0i, Int_t numed) {
//
fGeometryManager->Gsdvn2(name, mother, ndiv, iaxis, c0i, numed);
}
void TGeant4::Gsdvt(const char *name, const char *mother, Float_t step,
Int_t iaxis, Int_t numed, Int_t ndvmx) {
//
fGeometryManager->Gsdvt(name, mother, step, iaxis, numed, ndvmx);
}
void TGeant4::Gsdvt2(const char *name, const char *mother, Float_t step,
Int_t iaxis, Float_t c0, Int_t numed, Int_t ndvmx) {
//
fGeometryManager->Gsdvt2(name, mother, step, iaxis, c0, numed, ndvmx);
}
void TGeant4::Gsord(const char *name, Int_t iax) {
//
fGeometryManager->Gsord(name, iax);
}
void TGeant4::Gspos(const char *name, Int_t nr, const char *mother,
Float_t x, Float_t y, Float_t z, Int_t irot,
const char *konly) {
//
fGeometryManager->Gspos(name, nr, mother, x, y, z, irot, konly);
}
void TGeant4::Gsposp(const char *name, Int_t nr, const char *mother,
Float_t x, Float_t y, Float_t z, Int_t irot,
const char *konly, Float_t *upar, Int_t np) {
//
fGeometryManager->Gsposp(name, nr, mother, x, y, z, irot, konly, upar, np);
}
void TGeant4::WriteEuclid(const char* fileName, const char* topVol,
Int_t number, Int_t nlevel) {
//
fGeometryManager->WriteEuclid(fileName, topVol, number, nlevel);
}
Int_t TGeant4::VolId(const Text_t* volName) const {
//
return fGeometryManager->VolId(volName);
}
const char* TGeant4::VolName(Int_t id) const {
//
return fGeometryManager->VolName(id);
}
Int_t TGeant4::NofVolumes() const {
//
return fGeometryManager->NofVolumes();
}
// methods for physics management
// ------------------------------------------------
void TGeant4::BuildPhysics() {
//
fPhysicsManager->BuildPhysics();
}
void TGeant4::SetCut(const char* cutName, Float_t cutValue) {
//
fPhysicsManager->SetCut(cutName, cutValue);
}
void TGeant4::SetProcess(const char* flagName, Int_t flagValue) {
//
fPhysicsManager->SetProcess(flagName, flagValue);
}
Float_t TGeant4::Xsec(char* reac, Float_t energy, Int_t part, Int_t mate) {
//
return fPhysicsManager->Xsec(reac, energy, part, mate);
}
Int_t TGeant4::IdFromPDG(Int_t pdgID) const {
//
return fPhysicsManager->IdFromPDG(pdgID);
}
Int_t TGeant4::PDGFromId(Int_t mcID) const {
//
return fPhysicsManager->PDGFromId(mcID);
}
void TGeant4::DefineParticles() {
//
fPhysicsManager->DefineParticles();
}
// methods for step management
// ------------------------------------------------
// inlined (in TGeant4.icc)
void TGeant4::Rndm(Float_t* array, const Int_t size) const {
//
fStepManager->Rndm(array, size);
}
// methods for visualization
// ------------------------------------------------
#ifdef G4VIS_USE
void TGeant4::DrawOneSpec(const char* name) {
//
fVisManager->DrawOneSpec(name);
}
void TGeant4::Gsatt(const char* name, const char* att, Int_t val) {
//
fVisManager->Gsatt(name, att, val);
}
void TGeant4::Gdraw(const char* name, Float_t theta, Float_t phi,
Float_t psi, Float_t u0, Float_t v0,
Float_t ul, Float_t vl) {
//
fVisManager->Gdraw(name, theta, phi, psi, u0, v0, ul, vl);
}
#else
void TGeant4::DrawOneSpec(const char* name) {
//
TG4Globals:: Warning("TGeant4::DrawOneSpec(): no visualization available.");
}
void TGeant4::Gsatt(const char* name, const char* att, Int_t val) {
//
TG4Globals:: Warning("TGeant4::Gsatt(): no visualization available.");
}
void TGeant4::Gdraw(const char* p1, Float_t theta, Float_t phi,
Float_t psi, Float_t u0, Float_t v0,
Float_t ul, Float_t vl) {
//
TG4Globals:: Warning("TGeant4::Gdraw(): no visualization available.");
}
#endif //G4VIS_USE
// methods for run control
// ------------------------------------------------
void TGeant4::Init() {
//
fRunManager->Initialize();
}
void TGeant4::ProcessEvent() {
//
fRunManager->ProcessEvent();
}
void TGeant4::ProcessRun(Int_t nofEvents) {
//
fRunManager->ProcessRun(nofEvents);
}
void TGeant4::StartGeantUI() {
//
fRunManager->StartGeantUI();
}
void TGeant4::StartRootUI() {
//
fRunManager->StartRootUI();
}
void TGeant4::ProcessGeantMacro(const char* macroName) {
//
fRunManager->ProcessGeantMacro(macroName);
}
void TGeant4::ProcessGeantCommand(const char* command) {
//
fRunManager->ProcessGeantCommand(command);
}
Int_t TGeant4::CurrentEvent() const {
//
return fRunManager->CurrentEvent();
}
// Geant3 specific methods
// !!! need to be transformed to common interface
// ------------------------------------------------
void TGeant4::Gdopt(const char* name, const char* value) {
//
TG4Globals:: Warning("TGeant4::Gdopt(..) is not implemented.");
}
void TGeant4::SetClipBox(const char *name, Float_t xmin, Float_t xmax,
Float_t ymin, Float_t ymax, Float_t zmin, Float_t zmax) {
//
TG4Globals:: Warning("TGeant4::SetClipBox(..) is not implemented.");
}
void TGeant4::DefaultRange() {
//
TG4Globals:: Warning("TGeant4::DefaultRange() is not implemented.");
}
void TGeant4::Gdhead(Int_t isel, const char* name, Float_t chrsiz) {
//
TG4Globals:: Warning("TGeant4::Gdhead(..) is not implemented.");
}
void TGeant4::Gdman(Float_t u, Float_t v, const char* type) {
//
TG4Globals:: Warning("TGeant4::Gdman(..) is not implemented.");
}
void TGeant4::SetColors() {
//
TG4Globals:: Warning("TGeant4::SetColours() is not implemented.");
}
void TGeant4::Gtreve() {
//
TG4Globals:: Warning("TGeant4::Gtreve() is not implemented.");
}
void TGeant4::Gtreve_root() {
//
TG4Globals:: Warning("TGeant4::Gtreve_root() is not implemented.");
}
void TGeant4::Gckmat(Int_t itmed, char* natmed) {
//
TG4Globals:: Warning("TGeant4::Gckmat(..) is not implemented.");
}
void TGeant4::InitLego() {
//
TG4Globals:: Warning("TGeant4::InitLego() is not implemented.");
}
void TGeant4::Gfpart(Int_t ipart, char *name, Int_t& itrtyp,
Float_t& amass, Float_t& charge, Float_t& tlife) {
//
TG4Globals:: Warning("TGeant4::Gfpart(..) is not implemented.");
}
void TGeant4::Gspart(Int_t ipart, const char *name, Int_t itrtyp,
Float_t amass, Float_t charge, Float_t tlife) {
//
TG4Globals:: Warning("TGeant4::Gspart(..) is not implemented.");
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResult> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResult> result(new TaskResult());
try {
RefPtr<LocalTaskRef> instance(new LocalTaskRef(app->getTaskInstance(task)));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
run(app.get(), &pipeline);
result->returnResult(
new io::MmappedFile(
File::openFile(instance->output_filename, File::O_READ)));
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::run(
Application* app,
LocalTaskPipeline* pipeline) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto parent_task = taskref;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(
app->getTaskInstance(dep.task_name, dep.params)));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
taskref->running = true;
tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref));
waiting = false;
}
fnord::logInfo(
"fnord.dproc",
"Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4",
(void*) pipeline,
pipeline->tasks.size(),
num_running,
num_waiting,
num_completed);
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logInfo(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task) {
auto cache_key = task->task->cacheKey();
String output_file;
bool cached = false;
if (cache_key.isEmpty()) {
auto tmpid = Random::singleton()->hex128();
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("tmp_$0", tmpid));
} else {
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
if (cache_key.isEmpty() || !FileUtil::exists(output_file)) {
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
fnord::logError("fnord.dproc", e, "error");
}
}
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->output_filename = output_file;
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(RefPtr<Task> _task) :
task(_task),
running(false),
expanded(false),
finished(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<commit_msg>debug print<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResult> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
fnord::logDebug(
"fnord.dproc",
"Running task: $0#$1",
app->name(),
task.task_name());
RefPtr<TaskResult> result(new TaskResult());
try {
RefPtr<LocalTaskRef> instance(new LocalTaskRef(app->getTaskInstance(task)));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
run(app.get(), &pipeline);
result->returnResult(
new io::MmappedFile(
File::openFile(instance->output_filename, File::O_READ)));
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::run(
Application* app,
LocalTaskPipeline* pipeline) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto parent_task = taskref;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(
app->getTaskInstance(dep.task_name, dep.params)));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
taskref->running = true;
tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref));
waiting = false;
}
fnord::logInfo(
"fnord.dproc",
"Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4",
(void*) pipeline,
pipeline->tasks.size(),
num_running,
num_waiting,
num_completed);
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logInfo(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task) {
auto cache_key = task->task->cacheKey();
String output_file;
bool cached = false;
if (cache_key.isEmpty()) {
auto tmpid = Random::singleton()->hex128();
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("tmp_$0", tmpid));
} else {
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
if (cache_key.isEmpty() || !FileUtil::exists(output_file)) {
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
fnord::logError("fnord.dproc", e, "error");
}
}
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->output_filename = output_file;
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(RefPtr<Task> _task) :
task(_task),
running(false),
expanded(false),
finished(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<|endoftext|> |
<commit_before>#include "PlainPrinter.h"
PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
ASTAction<PlainPrinterAction>() {
OutputFile = std::make_shared<std::fstream>();
OutputFile->open(filename, std::fstream::out);
}
PlainPrinterAction::~PlainPrinterAction() {
OutputFile->close();
}
std::fstream &PlainPrinterAction::getStream() {
return *OutputFile;
}
PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }
<commit_msg>Change constructor to set OutputFile.<commit_after>#include "PlainPrinter.h"
PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
ASTAction<PlainPrinterAction>(),
OutputFile(std::make_shared<std::fstream>()) {
OutputFile->open(filename, std::fstream::out);
}
PlainPrinterAction::~PlainPrinterAction() {
OutputFile->close();
}
std::fstream &PlainPrinterAction::getStream() {
return *OutputFile;
}
PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }
<|endoftext|> |
<commit_before>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "VMAssert.h"
#include "VMPI.h"
#ifndef TLS_OUT_OF_INDEXES
#define TLS_OUT_OF_INDEXES (DWORD)0xFFFFFFFF
#endif
bool VMPI_tlsCreate(uintptr_t* tlsId)
{
DWORD id = TlsAlloc();
*tlsId = (uintptr_t)id;
return (id != TLS_OUT_OF_INDEXES);
}
void VMPI_tlsDestroy(uintptr_t tlsId)
{
TlsFree((DWORD)tlsId);
}
bool VMPI_threadCreate(vmpi_thread_t* thread, vmpi_thread_attr_t* attr, vmpi_thread_start_t start_fn, vmpi_thread_arg_t arg)
{
DWORD id;
SIZE_T stackSize = attr == NULL || attr->stackSize == VMPI_threadAttrDefaultStackSize() ? 0 : attr->stackSize;
HANDLE threadHandle = CreateThread(NULL, stackSize, start_fn, arg, 0, &id);
if (threadHandle) {
*thread = id;
CloseHandle(threadHandle);
if (attr != NULL && attr->priority != THREAD_PRIORITY_NORMAL) {
SetThreadPriority(threadHandle, attr->priority);
}
// The SetThreadStackGuarantee API is not available in all versions of Windows we care about,
// so we can't honor any specific guard size request.
return true;
} else {
return false;
}
}
bool VMPI_threadDetach(vmpi_thread_t thread)
{
// Not applicable
(void)thread;
return true;
}
void VMPI_threadSleep(int32_t timeout_millis)
{
Sleep(timeout_millis);
}
#ifdef UNDER_CE
void VMPI_threadJoin(vmpi_thread_t thread)
{
(void)thread;
AvmAssertMsg(false, "Not supported under CE");
}
void VMPI_condVarWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex)
{
(void)condvar;
(void)mutex;
AvmAssertMsg(false, "Not supported under CE");
}
bool VMPI_condVarTimedWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex, int32_t timeout_millis)
{
(void)condvar;
(void)mutex;
(void)timeout_millis;
AvmAssertMsg(false, "Not supported under CE");
return false;
}
void VMPI_condVarBroadcast(vmpi_condvar_t* condvar)
{
(void)condvar;
AvmAssertMsg(false, "Not supported under CE");
}
void VMPI_condVarSignal(vmpi_condvar_t* condvar)
{
(void)condvar;
AvmAssertMsg(false, "Not supported under CE");
}
#else
void VMPI_threadJoin(vmpi_thread_t thread)
{
HANDLE threadHandle = OpenThread(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF, false, thread);
if (threadHandle) {
WaitForSingleObject(threadHandle, INFINITE);
CloseHandle(threadHandle);
}
}
bool VMPI_condVarTimedWaitInternal(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex, int32_t timeout_millis, bool infinite)
{
// We use the same emulation technique as FP.
// Although post-notify scheduling is not exactly fair, the algorithm is simple.
// If we want something fairer then use Alexander Terekhov's 8a algorithm.
// Add the calling thread to the condition variable's list of waiting threads.
// Note that the linked list is implicitly guarded by the mutex paired with the conditional variable.
WaitingThread thisThread;
thisThread.threadID = GetCurrentThreadId();
thisThread.notified = false;
thisThread.next = NULL;
if (condvar->head == NULL) {
condvar->head = &thisThread;
} else {
condvar->tail->next = &thisThread;
}
condvar->tail = &thisThread;
// Unlock the mutex and then sleep until we are notified or timeout.
// Note that there should be *no* lost wakeups between the unlock and the sleep, as all notifies are
// queued as APCs.
LeaveCriticalSection(mutex);
const DWORD rtn = SleepEx(infinite ? INFINITE : timeout_millis, true);
// As per pthread condition variable semantics, we block until we can re-acquire the mutex we released.
EnterCriticalSection(mutex);
if (!thisThread.notified) {
// A spurious or time-out wake-up, so the thread must remove itself from the condvar's wait list.
WaitingThread* waiter = condvar->head;
WaitingThread* prev = NULL;
do {
if (waiter == &thisThread) {
if (prev == NULL) {
condvar->head = waiter->next;
} else {
prev->next = waiter->next;
}
if (waiter->next == NULL) {
condvar->tail = prev;
}
return rtn == 0;
}
prev = waiter;
waiter = waiter->next;
} while(waiter);
assert(!"Current thread not found in list of waiters");
}
return rtn == 0;
}
void VMPI_condVarWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex)
{
VMPI_condVarTimedWaitInternal(condvar, mutex, 0, true);
}
bool VMPI_condVarTimedWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex, int32_t timeout_millis)
{
return VMPI_condVarTimedWaitInternal(condvar, mutex, timeout_millis, false);
}
// A private, dummy callback for the QueueUserAPC implementation of VMPI_condVarBroadcast/Signal
void WINAPI dummyAPC(ULONG_PTR) {
// Nothing to do
}
void VMPI_condVarBroadcast(vmpi_condvar_t* condvar)
{
// Signal the whole list.
// Note that the list is implicitly guarded by the mutex paired with the conditional variable
// (which the calling thread holds).
WaitingThread* waiter = condvar->head;
condvar->head = NULL;
condvar->tail = NULL;
while (waiter != NULL) {
waiter->notified = true;
HANDLE threadHandle = OpenThread(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF, false, waiter->threadID);
// Signal the thread by queuing a dummy APC.
QueueUserAPC(dummyAPC, threadHandle, NULL);
CloseHandle(threadHandle);
waiter = waiter->next;
}
}
void VMPI_condVarSignal(vmpi_condvar_t* condvar)
{
// Signal the head of the list. FIFO looks like it should be fair, but it's not really.
// Note that the list is implicitly guarded by the mutex paired with the conditional variable
// (which the calling thread holds).
WaitingThread* waiter = condvar->head;
if (waiter != NULL) {
waiter->notified = true;
condvar->head = waiter->next;
if (condvar->head == NULL) {
condvar->tail = NULL;
}
HANDLE threadHandle = OpenThread(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF, false, waiter->threadID);
// Signal the thread by queuing a dummy APC.
QueueUserAPC(dummyAPC, threadHandle, NULL);
CloseHandle(threadHandle);
}
}
#endif // UNDER_CE
bool VMPI_threadAttrInit(vmpi_thread_attr_t* attr)
{
attr->stackSize = VMPI_threadAttrDefaultStackSize();
attr->guardSize = VMPI_threadAttrDefaultGuardSize();
attr->priority = THREAD_PRIORITY_NORMAL;
return true;
}
bool VMPI_threadAttrDestroy(vmpi_thread_attr_t* attr)
{
(void)attr;
return true;
}
bool VMPI_threadAttrSetGuardSize(vmpi_thread_attr_t* attr, size_t size)
{
attr->guardSize = size;
return true;
}
bool VMPI_threadAttrSetStackSize(vmpi_thread_attr_t* attr, size_t size)
{
attr->stackSize = size;
return true;
}
void VMPI_threadAttrSetPriorityLow(vmpi_thread_attr_t* attr)
{
attr->priority = THREAD_PRIORITY_BELOW_NORMAL;
}
void VMPI_threadAttrSetPriorityNormal(vmpi_thread_attr_t* attr)
{
attr->priority = THREAD_PRIORITY_NORMAL;
}
void VMPI_threadAttrSetPriorityHigh(vmpi_thread_attr_t* attr)
{
attr->priority = THREAD_PRIORITY_ABOVE_NORMAL;
}
size_t VMPI_threadAttrDefaultGuardSize()
{
// It will be a single page.
// The SetThreadStackGuarantee API isn't available so we can't change it
// from the default.
// http://msdn.microsoft.com/en-us/library/8cxs58a6%28vs.71%29.aspx
return VMPI_getVMPageSize();
}
size_t VMPI_threadAttrDefaultStackSize()
{
// FIXME: bug 609822 Is it possible to implement VMPI_threadAttrDefaultStackSize on win32?
//
// Stack size is set in the linker. The default is 1MB:
// http://msdn.microsoft.com/en-us/library/8cxs58a6%28vs.71%29.aspx
// But can we find this out programmatically? There doesn't appear to be an API:
// http://msdn.microsoft.com/en-us/library/ms686774%28v=VS.85%29.aspx
return 1024 * 1024;
}
<commit_msg>Fix Visual Studio build breakage introduced by fklockii in rev 6452 (r=lhansen)<commit_after>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "VMPI.h"
#include "VMAssert.h"
#ifndef TLS_OUT_OF_INDEXES
#define TLS_OUT_OF_INDEXES (DWORD)0xFFFFFFFF
#endif
bool VMPI_tlsCreate(uintptr_t* tlsId)
{
DWORD id = TlsAlloc();
*tlsId = (uintptr_t)id;
return (id != TLS_OUT_OF_INDEXES);
}
void VMPI_tlsDestroy(uintptr_t tlsId)
{
TlsFree((DWORD)tlsId);
}
bool VMPI_threadCreate(vmpi_thread_t* thread, vmpi_thread_attr_t* attr, vmpi_thread_start_t start_fn, vmpi_thread_arg_t arg)
{
DWORD id;
SIZE_T stackSize = attr == NULL || attr->stackSize == VMPI_threadAttrDefaultStackSize() ? 0 : attr->stackSize;
HANDLE threadHandle = CreateThread(NULL, stackSize, start_fn, arg, 0, &id);
if (threadHandle) {
*thread = id;
CloseHandle(threadHandle);
if (attr != NULL && attr->priority != THREAD_PRIORITY_NORMAL) {
SetThreadPriority(threadHandle, attr->priority);
}
// The SetThreadStackGuarantee API is not available in all versions of Windows we care about,
// so we can't honor any specific guard size request.
return true;
} else {
return false;
}
}
bool VMPI_threadDetach(vmpi_thread_t thread)
{
// Not applicable
(void)thread;
return true;
}
void VMPI_threadSleep(int32_t timeout_millis)
{
Sleep(timeout_millis);
}
#ifdef UNDER_CE
void VMPI_threadJoin(vmpi_thread_t thread)
{
(void)thread;
AvmAssertMsg(false, "Not supported under CE");
}
void VMPI_condVarWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex)
{
(void)condvar;
(void)mutex;
AvmAssertMsg(false, "Not supported under CE");
}
bool VMPI_condVarTimedWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex, int32_t timeout_millis)
{
(void)condvar;
(void)mutex;
(void)timeout_millis;
AvmAssertMsg(false, "Not supported under CE");
return false;
}
void VMPI_condVarBroadcast(vmpi_condvar_t* condvar)
{
(void)condvar;
AvmAssertMsg(false, "Not supported under CE");
}
void VMPI_condVarSignal(vmpi_condvar_t* condvar)
{
(void)condvar;
AvmAssertMsg(false, "Not supported under CE");
}
#else
void VMPI_threadJoin(vmpi_thread_t thread)
{
HANDLE threadHandle = OpenThread(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF, false, thread);
if (threadHandle) {
WaitForSingleObject(threadHandle, INFINITE);
CloseHandle(threadHandle);
}
}
bool VMPI_condVarTimedWaitInternal(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex, int32_t timeout_millis, bool infinite)
{
// We use the same emulation technique as FP.
// Although post-notify scheduling is not exactly fair, the algorithm is simple.
// If we want something fairer then use Alexander Terekhov's 8a algorithm.
// Add the calling thread to the condition variable's list of waiting threads.
// Note that the linked list is implicitly guarded by the mutex paired with the conditional variable.
WaitingThread thisThread;
thisThread.threadID = GetCurrentThreadId();
thisThread.notified = false;
thisThread.next = NULL;
if (condvar->head == NULL) {
condvar->head = &thisThread;
} else {
condvar->tail->next = &thisThread;
}
condvar->tail = &thisThread;
// Unlock the mutex and then sleep until we are notified or timeout.
// Note that there should be *no* lost wakeups between the unlock and the sleep, as all notifies are
// queued as APCs.
LeaveCriticalSection(mutex);
const DWORD rtn = SleepEx(infinite ? INFINITE : timeout_millis, true);
// As per pthread condition variable semantics, we block until we can re-acquire the mutex we released.
EnterCriticalSection(mutex);
if (!thisThread.notified) {
// A spurious or time-out wake-up, so the thread must remove itself from the condvar's wait list.
WaitingThread* waiter = condvar->head;
WaitingThread* prev = NULL;
do {
if (waiter == &thisThread) {
if (prev == NULL) {
condvar->head = waiter->next;
} else {
prev->next = waiter->next;
}
if (waiter->next == NULL) {
condvar->tail = prev;
}
return rtn == 0;
}
prev = waiter;
waiter = waiter->next;
} while(waiter);
assert(!"Current thread not found in list of waiters");
}
return rtn == 0;
}
void VMPI_condVarWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex)
{
VMPI_condVarTimedWaitInternal(condvar, mutex, 0, true);
}
bool VMPI_condVarTimedWait(vmpi_condvar_t* condvar, vmpi_mutex_t* mutex, int32_t timeout_millis)
{
return VMPI_condVarTimedWaitInternal(condvar, mutex, timeout_millis, false);
}
// A private, dummy callback for the QueueUserAPC implementation of VMPI_condVarBroadcast/Signal
void WINAPI dummyAPC(ULONG_PTR) {
// Nothing to do
}
void VMPI_condVarBroadcast(vmpi_condvar_t* condvar)
{
// Signal the whole list.
// Note that the list is implicitly guarded by the mutex paired with the conditional variable
// (which the calling thread holds).
WaitingThread* waiter = condvar->head;
condvar->head = NULL;
condvar->tail = NULL;
while (waiter != NULL) {
waiter->notified = true;
HANDLE threadHandle = OpenThread(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF, false, waiter->threadID);
// Signal the thread by queuing a dummy APC.
QueueUserAPC(dummyAPC, threadHandle, NULL);
CloseHandle(threadHandle);
waiter = waiter->next;
}
}
void VMPI_condVarSignal(vmpi_condvar_t* condvar)
{
// Signal the head of the list. FIFO looks like it should be fair, but it's not really.
// Note that the list is implicitly guarded by the mutex paired with the conditional variable
// (which the calling thread holds).
WaitingThread* waiter = condvar->head;
if (waiter != NULL) {
waiter->notified = true;
condvar->head = waiter->next;
if (condvar->head == NULL) {
condvar->tail = NULL;
}
HANDLE threadHandle = OpenThread(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF, false, waiter->threadID);
// Signal the thread by queuing a dummy APC.
QueueUserAPC(dummyAPC, threadHandle, NULL);
CloseHandle(threadHandle);
}
}
#endif // UNDER_CE
bool VMPI_threadAttrInit(vmpi_thread_attr_t* attr)
{
attr->stackSize = VMPI_threadAttrDefaultStackSize();
attr->guardSize = VMPI_threadAttrDefaultGuardSize();
attr->priority = THREAD_PRIORITY_NORMAL;
return true;
}
bool VMPI_threadAttrDestroy(vmpi_thread_attr_t* attr)
{
(void)attr;
return true;
}
bool VMPI_threadAttrSetGuardSize(vmpi_thread_attr_t* attr, size_t size)
{
attr->guardSize = size;
return true;
}
bool VMPI_threadAttrSetStackSize(vmpi_thread_attr_t* attr, size_t size)
{
attr->stackSize = size;
return true;
}
void VMPI_threadAttrSetPriorityLow(vmpi_thread_attr_t* attr)
{
attr->priority = THREAD_PRIORITY_BELOW_NORMAL;
}
void VMPI_threadAttrSetPriorityNormal(vmpi_thread_attr_t* attr)
{
attr->priority = THREAD_PRIORITY_NORMAL;
}
void VMPI_threadAttrSetPriorityHigh(vmpi_thread_attr_t* attr)
{
attr->priority = THREAD_PRIORITY_ABOVE_NORMAL;
}
size_t VMPI_threadAttrDefaultGuardSize()
{
// It will be a single page.
// The SetThreadStackGuarantee API isn't available so we can't change it
// from the default.
// http://msdn.microsoft.com/en-us/library/8cxs58a6%28vs.71%29.aspx
return VMPI_getVMPageSize();
}
size_t VMPI_threadAttrDefaultStackSize()
{
// FIXME: bug 609822 Is it possible to implement VMPI_threadAttrDefaultStackSize on win32?
//
// Stack size is set in the linker. The default is 1MB:
// http://msdn.microsoft.com/en-us/library/8cxs58a6%28vs.71%29.aspx
// But can we find this out programmatically? There doesn't appear to be an API:
// http://msdn.microsoft.com/en-us/library/ms686774%28v=VS.85%29.aspx
return 1024 * 1024;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016, the Cap authors.
*
* This file is subject to the Modified BSD License and may not be distributed
* without copyright and license information. Please refer to the file LICENSE
* for the text and further information on this license.
*/
#include <cap/electrochemical_impedance_spectroscopy.h>
#include <cap/utils.h>
#include <boost/math/special_functions/sin_pi.hpp>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_halfcomplex.h>
#define REAL(z, i) ((z)[2 * (i)])
#define IMAG(z, i) ((z)[2 * (i) + 1])
#include <iostream>
namespace cap
{
std::vector<std::complex<double>> compute_fft(double const *input,
size_t const n)
{
std::vector<double> data(input, input + n);
gsl_fft_real_radix2_transform(&(data[0]), 1, n);
std::vector<double> unpacked_data(2 * n);
gsl_fft_halfcomplex_radix2_unpack(&(data[0]), &(unpacked_data[0]), 1, n);
std::vector<std::complex<double>> output(n / 2 + 1);
for (size_t k = 0; k < n / 2 + 1; ++k)
output[k] =
std::complex<double>(REAL(unpacked_data, k), IMAG(unpacked_data, k));
return output;
}
std::vector<double> compute_fft_frequencies(size_t const n,
double const frequency)
{
std::vector<double> fft_frequencies(n / 2 + 1);
for (size_t k = 0; k < n / 2 + 1; ++k)
fft_frequencies[k] = k * frequency;
return fft_frequencies;
}
std::vector<double>
compute_signal_to_noise_ratio(std::vector<std::complex<double>> fft_data,
std::vector<int> excited_harmonics,
std::vector<int> unexcited_harmonics)
{
assert(fft_data.size() ==
excited_harmonics.size() + unexcited_harmonics.size() + 1);
double dc_power = std::norm(fft_data[0]);
double ac_power = 0.0;
for (int k : excited_harmonics)
ac_power += std::norm(fft_data[k]);
double noise_power = 0.0;
for (int k : unexcited_harmonics)
noise_power += std::norm(fft_data[k]);
double total_power = dc_power + ac_power + noise_power;
std::ignore = total_power;
// TODO: definition is a bit shaky for multiple frequency
// should compute for each individual excited freq vs nearby unex freq
std::vector<double> ratios;
for (size_t k : excited_harmonics)
{
ratios.emplace_back(std::norm(fft_data[k]) / noise_power);
}
return ratios;
}
std::function<void(std::shared_ptr<cap::EnergyStorageDevice>, double, double)>
get_evolve_one_time_step(
std::shared_ptr<boost::property_tree::ptree const> database)
{
// clang-format off
std::vector<int> const harmonics = cap::to_vector<int>(database->get<std::string>("harmonics"));
std::vector<double> const amplitudes = cap::to_vector<double>(database->get<std::string>("amplitudes"));
std::vector<double> const phases = cap::to_vector<double>(database->get<std::string>("phases"));
// clang-format on
assert(harmonics.size() == amplitudes.size());
assert(harmonics.size() == phases.size());
double const frequency = database->get<double>("frequency");
auto compute_ac_excitation_signal = [frequency, harmonics, amplitudes,
phases](double time)
{
double excitation_signal = 0.0;
for (size_t k = 0; k < harmonics.size(); ++k)
excitation_signal +=
amplitudes[k] *
boost::math::sin_pi(2 * harmonics[k] * frequency * time + phases[k]);
return excitation_signal;
};
std::string const mode = database->get<std::string>("mode");
if (mode.compare("galvanostatic") != 0)
{
return [compute_ac_excitation_signal](
std::shared_ptr<cap::EnergyStorageDevice> device, double time,
double time_step)
{
device->evolve_one_time_step_linear_current(
time_step, compute_ac_excitation_signal(time));
};
}
else if (mode.compare("potentiostatic") != 0)
{
double const dc_voltage = database->get<double>("dc_voltage");
return [dc_voltage, compute_ac_excitation_signal](
std::shared_ptr<cap::EnergyStorageDevice> device, double time,
double time_step)
{
device->evolve_one_time_step_linear_voltage(
time_step, dc_voltage + compute_ac_excitation_signal(time));
};
}
else
{
throw std::runtime_error("invalide mode " + mode + " for EIS measurement");
}
}
std::map<double, std::complex<double>>
measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> device,
std::shared_ptr<boost::property_tree::ptree const> database)
{
std::vector<int> const harmonics =
cap::to_vector<int>(database->get<std::string>("harmonics"));
double const frequency = database->get<double>("frequency");
int const cycles = database->get<int>("cycles");
int const ignore_cycles = database->get<int>("ignore_cycles");
int const steps_per_cycle = database->get<int>("steps_per_cycle");
auto evolve_one_time_step = get_evolve_one_time_step(database);
// apply excitation signal and measure response
std::vector<double> time(cycles * steps_per_cycle);
std::vector<double> current(cycles * steps_per_cycle);
std::vector<double> voltage(cycles * steps_per_cycle);
double const time_step = 1.0 / frequency / steps_per_cycle;
for (int step = 0; step < cycles * steps_per_cycle; ++step)
{
time[step] = (step + 1) * time_step;
evolve_one_time_step(device, time[step], time_step);
device->get_current(current[step]);
device->get_voltage(voltage[step]);
}
// compute discrete fourrier transforms
std::vector<std::complex<double>> fft_current =
compute_fft(&(current[ignore_cycles * steps_per_cycle]),
(cycles - ignore_cycles) * steps_per_cycle);
std::vector<std::complex<double>> fft_voltage =
compute_fft(&(voltage[ignore_cycles * steps_per_cycle]),
(cycles - ignore_cycles) * steps_per_cycle);
std::vector<double> fft_frequencies =
compute_fft_frequencies((cycles - ignore_cycles) * steps_per_cycle,
frequency / (cycles - ignore_cycles));
//
int const n = (cycles - ignore_cycles) * steps_per_cycle;
assert(fft_current.size() == n / 2 + 1);
assert(fft_voltage.size() == n / 2 + 1);
assert(fft_frequencies.size() == n / 2 + 1);
std::vector<int> excited_harmonics;
std::vector<int> unexcited_harmonics;
for (int i = 1; i < n / 2; ++i)
if ((std::find(harmonics.begin(), harmonics.end(),
i / (cycles - ignore_cycles)) != harmonics.end()) &&
(i % (cycles - ignore_cycles) == 0))
excited_harmonics.push_back(i);
else
unexcited_harmonics.push_back(i);
// check signal-to-noise ratio
std::vector<double> current_signal_to_noise_ratio =
compute_signal_to_noise_ratio(fft_current, excited_harmonics,
unexcited_harmonics);
std::vector<double> voltage_signal_to_noise_ratio =
compute_signal_to_noise_ratio(fft_voltage, excited_harmonics,
unexcited_harmonics);
// TODO: do we want to assert something or give a warning if ratio is not good
// enough?
// return complex impedance
std::map<double, std::complex<double>> impedance;
for (int const &k : excited_harmonics)
{
impedance.emplace(fft_frequencies[k], fft_voltage[k] / fft_current[k]);
}
return impedance;
}
std::map<double, std::complex<double>> impedance_spectroscopy(
std::shared_ptr<cap::EnergyStorageDevice> device,
std::shared_ptr<boost::property_tree::ptree const> database)
{
// clang-format off
double const frequency_upper_limit = database->get<double>("frequency_upper_limit");
double const frequency_lower_limit = database->get<double>("frequency_lower_limit");
int const steps_per_decade = database->get<int>("steps_per_decade");
// clang-format on
std::shared_ptr<boost::property_tree::ptree> tmp_database =
std::make_shared<boost::property_tree::ptree>(*database);
std::map<double, std::complex<double>> data;
for (double frequency = frequency_upper_limit;
frequency >= frequency_lower_limit;
frequency /= std::pow(10.0, 1.0 / steps_per_decade))
{
tmp_database->put("frequency", frequency);
auto const impedance = measure_impedance(device, tmp_database);
data.insert(impedance.begin(), impedance.end());
}
return data;
}
} // end namespace cap
<commit_msg>update cpp compute eis<commit_after>/* Copyright (c) 2016, the Cap authors.
*
* This file is subject to the Modified BSD License and may not be distributed
* without copyright and license information. Please refer to the file LICENSE
* for the text and further information on this license.
*/
#include <cap/electrochemical_impedance_spectroscopy.h>
#include <cap/utils.h>
#include <boost/assert.hpp>
#include <boost/math/special_functions/sin_pi.hpp>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_halfcomplex.h>
#define REAL(z, i) ((z)[2 * (i)])
#define IMAG(z, i) ((z)[2 * (i) + 1])
#include <iostream>
namespace cap
{
std::vector<std::complex<double>> compute_fft(double const *input,
size_t const n)
{
std::vector<double> data(input, input + n);
gsl_fft_real_radix2_transform(&(data[0]), 1, n);
std::vector<double> unpacked_data(2 * n);
gsl_fft_halfcomplex_radix2_unpack(&(data[0]), &(unpacked_data[0]), 1, n);
std::vector<std::complex<double>> output(n / 2 + 1);
for (size_t k = 0; k < n / 2 + 1; ++k)
output[k] =
std::complex<double>(REAL(unpacked_data, k), IMAG(unpacked_data, k));
return output;
}
std::vector<double> compute_fft_frequencies(size_t const n,
double const frequency)
{
std::vector<double> fft_frequencies(n / 2 + 1);
for (size_t k = 0; k < n / 2 + 1; ++k)
fft_frequencies[k] = k * frequency;
return fft_frequencies;
}
std::vector<double>
compute_signal_to_noise_ratio(std::vector<std::complex<double>> fft_data,
std::vector<int> excited_harmonics,
std::vector<int> unexcited_harmonics)
{
BOOST_ASSERT(fft_data.size() ==
excited_harmonics.size() + unexcited_harmonics.size() + 1);
double dc_power = std::norm(fft_data[0]);
double ac_power = 0.0;
for (int k : excited_harmonics)
ac_power += std::norm(fft_data[k]);
double noise_power = 0.0;
for (int k : unexcited_harmonics)
noise_power += std::norm(fft_data[k]);
double total_power = dc_power + ac_power + noise_power;
std::ignore = total_power;
// TODO: definition is a bit shaky for multiple frequency
// should compute for each individual excited freq vs nearby unex freq
std::vector<double> ratios;
for (size_t k : excited_harmonics)
{
ratios.emplace_back(std::norm(fft_data[k]) / noise_power);
}
return ratios;
}
std::function<void(std::shared_ptr<cap::EnergyStorageDevice>, double, double)>
get_evolve_one_time_step(
std::shared_ptr<boost::property_tree::ptree const> database)
{
// clang-format off
std::vector<int> const harmonics = cap::to_vector<int>(database->get<std::string>("harmonics"));
std::vector<double> const amplitudes = cap::to_vector<double>(database->get<std::string>("amplitudes"));
std::vector<double> const phases = cap::to_vector<double>(database->get<std::string>("phases"));
// clang-format on
BOOST_ASSERT(harmonics.size() == amplitudes.size());
BOOST_ASSERT(harmonics.size() == phases.size());
double const frequency = database->get<double>("frequency");
auto compute_ac_excitation_signal = [frequency, harmonics, amplitudes,
phases](double time)
{
double excitation_signal = 0.0;
for (size_t k = 0; k < harmonics.size(); ++k)
excitation_signal +=
amplitudes[k] *
boost::math::sin_pi(2 * harmonics[k] * frequency * time + phases[k]);
return excitation_signal;
};
std::string const mode = database->get<std::string>("mode");
if (mode.compare("galvanostatic") != 0)
{
return [compute_ac_excitation_signal](
std::shared_ptr<cap::EnergyStorageDevice> device, double time,
double time_step)
{
device->evolve_one_time_step_linear_current(
time_step, compute_ac_excitation_signal(time));
};
}
else if (mode.compare("potentiostatic") != 0)
{
double const dc_voltage = database->get<double>("dc_voltage");
return [dc_voltage, compute_ac_excitation_signal](
std::shared_ptr<cap::EnergyStorageDevice> device, double time,
double time_step)
{
device->evolve_one_time_step_linear_voltage(
time_step, dc_voltage + compute_ac_excitation_signal(time));
};
}
else
{
throw std::runtime_error("invalide mode " + mode + " for EIS measurement");
}
}
std::map<double, std::complex<double>>
measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> device,
std::shared_ptr<boost::property_tree::ptree const> database)
{
std::vector<int> const harmonics =
cap::to_vector<int>(database->get<std::string>("harmonics"));
double const frequency = database->get<double>("frequency");
int const cycles = database->get<int>("cycles");
int const ignore_cycles = database->get<int>("ignore_cycles");
int const steps_per_cycle = database->get<int>("steps_per_cycle");
auto evolve_one_time_step = get_evolve_one_time_step(database);
// apply excitation signal and measure response
std::vector<double> time(cycles * steps_per_cycle);
std::vector<double> current(cycles * steps_per_cycle);
std::vector<double> voltage(cycles * steps_per_cycle);
double const time_step = 1.0 / frequency / steps_per_cycle;
for (int step = 0; step < cycles * steps_per_cycle; ++step)
{
time[step] = (step + 1) * time_step;
evolve_one_time_step(device, time[step], time_step);
device->get_current(current[step]);
device->get_voltage(voltage[step]);
}
// compute discrete fourrier transforms
std::vector<std::complex<double>> fft_current =
compute_fft(&(current[ignore_cycles * steps_per_cycle]),
(cycles - ignore_cycles) * steps_per_cycle);
std::vector<std::complex<double>> fft_voltage =
compute_fft(&(voltage[ignore_cycles * steps_per_cycle]),
(cycles - ignore_cycles) * steps_per_cycle);
std::vector<double> fft_frequencies =
compute_fft_frequencies((cycles - ignore_cycles) * steps_per_cycle,
frequency / (cycles - ignore_cycles));
//
int const n = (cycles - ignore_cycles) * steps_per_cycle;
BOOST_ASSERT(fft_current.size() == static_cast<size_t>(n / 2 + 1));
BOOST_ASSERT(fft_voltage.size() == static_cast<size_t>(n / 2 + 1));
BOOST_ASSERT(fft_frequencies.size() == static_cast<size_t>(n / 2 + 1));
std::vector<int> excited_harmonics;
std::vector<int> unexcited_harmonics;
for (int i = 1; i <= n / 2; ++i)
if ((std::find(harmonics.begin(), harmonics.end(),
i / (cycles - ignore_cycles)) != harmonics.end()) &&
(i % (cycles - ignore_cycles) == 0))
excited_harmonics.push_back(i);
else
unexcited_harmonics.push_back(i);
// check signal-to-noise ratio
std::vector<double> current_signal_to_noise_ratio =
compute_signal_to_noise_ratio(fft_current, excited_harmonics,
unexcited_harmonics);
std::vector<double> voltage_signal_to_noise_ratio =
compute_signal_to_noise_ratio(fft_voltage, excited_harmonics,
unexcited_harmonics);
// TODO: do we want to assert something or give a warning if ratio is not good
// enough?
// return complex impedance
std::map<double, std::complex<double>> impedance;
for (int const &k : excited_harmonics)
{
impedance.emplace(fft_frequencies[k], fft_voltage[k] / fft_current[k]);
}
return impedance;
}
std::map<double, std::complex<double>> impedance_spectroscopy(
std::shared_ptr<cap::EnergyStorageDevice> device,
std::shared_ptr<boost::property_tree::ptree const> database)
{
// clang-format off
double const frequency_upper_limit = database->get<double>("frequency_upper_limit");
double const frequency_lower_limit = database->get<double>("frequency_lower_limit");
int const steps_per_decade = database->get<int>("steps_per_decade");
// clang-format on
std::shared_ptr<boost::property_tree::ptree> tmp_database =
std::make_shared<boost::property_tree::ptree>(*database);
std::map<double, std::complex<double>> data;
for (double frequency = frequency_upper_limit;
frequency >= frequency_lower_limit;
frequency /= std::pow(10.0, 1.0 / steps_per_decade))
{
tmp_database->put("frequency", frequency);
auto const impedance = measure_impedance(device, tmp_database);
data.insert(impedance.begin(), impedance.end());
}
return data;
}
} // end namespace cap
<|endoftext|> |
<commit_before>#include "Golem.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1App.h"
#include "p2Defs.h"
#include "j1Scene.h"
#include "j1Input.h"
#include "j1Item.h"
#include "j1Collision.h"
#include "j1Player.h"
#include "j1EntityElementsScene.h"
Golem::Golem()
{
}
Golem::~Golem()
{
}
bool Golem::Awake(pugi::xml_node &conf, uint id)
{
name = conf.attribute("name").as_string("");
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("name").as_int(0);
speed = conf.attribute("name").as_int(0);
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
mode_stone = conf.attribute("mode_stone").as_bool(false);
position = iPoint(conf.attribute("pos_x").as_int(0), conf.attribute("pos_y").as_int(0));
return true;
}
bool Golem::Start()
{
state = STATIC;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 14;
gamestate = TIMETOPLAY;
movable = true;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 14, 14 }, COLLIDER_POKEMON, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
reset_run = true;
//Modify Meta
iPoint temp = App->map->WorldToMap(position.x, position.y);
App->map->EditCost(temp.x, temp.y, App->map->data.tilesets[1]->firstgid + 1);
App->map->EditCost(temp.x - 1, temp.y, App->map->data.tilesets[1]->firstgid + 1);
App->map->EditCost(temp.x, temp.y - 1, App->map->data.tilesets[1]->firstgid + 1);
App->map->EditCost(temp.x - 1, temp.y - 1, App->map->data.tilesets[1]->firstgid + 1);
//Get the animations
animation = *App->anim_manager->GetAnimStruct(5); //id 5 = Golem
// Test for Vertical Slice /// TODO MED-> read stats from XML
radar = 40;
attack_speed = 1;
chase_speed = 1;
return true;
}
bool Golem::Update()
{
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
switch (state)
{
case IDLE:
{
CheckPlayerPos();
Idle();
break;
}
/*case WALKING:
{
CheckPlayerPos();
Walking();
break;
}*/
case CHASING:
{
CheckPlayerPos();
Chase();
break;
}
case ATTACKING:
{
Attack();
break;
}
case HIT:
{
Hit();
break;
}
case STATIC:
{
break;
}
/* This case shoul be added, it reffers when abandoning rock stage */
case AWAKENING:
{
if (mode_stone)
{
mode_stone = false;
timetoplay = SDL_GetTicks();
}
if (mode_stone == false && SDL_GetTicks() - timetoplay > 500)
{
state = IDLE;
}
break;
}
case DYING:
{
Death();
break;
}
default:
{
break;
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Golem::Draw()
{
BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow)
//App->anim_manager->Drawing_Manager(state, direction, position, 6);
int id;
switch (state)
{
case IDLE:
id = 0;
break;
/*case WALKING:
id = 1;
break;*/
case CHASING:
id = 1;
break;
case ATTACKING:
id = 2;
break;
case STATIC:
id = 3;
break;
case AWAKENING:
id = 4;
break;
case HIT:
id = 5;
break;
case DYING:
id = 5;
break;
default:
break;
}
if (direction == UP)
{
anim_rect = animation.anim[id].North_action.GetCurrentFrame();
pivot = animation.anim[id].North_action.GetCurrentOffset();
}
else if (direction == DOWN)
{
anim_rect = animation.anim[id].South_action.GetCurrentFrame();
pivot = animation.anim[id].South_action.GetCurrentOffset();
}
else if (direction == LEFT)
{
anim_rect = animation.anim[id].West_action.GetCurrentFrame();
pivot = animation.anim[id].West_action.GetCurrentOffset();
}
else if (direction == RIGHT)
{
anim_rect = animation.anim[id].East_action.GetCurrentFrame();
pivot = animation.anim[id].East_action.GetCurrentOffset();
}
//DRAW
App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect);
}
bool Golem::CleanUp()
{
return true;
}
void Golem::AddItem(Item* item)
{
item_inside = item;
item->canBlit = false;
}
void Golem::Drop_item()
{
item_inside->canBlit = true;
item_inside->position.x = position.x;
item_inside->position.y = position.y;
item_inside = NULL;
}
bool Golem::CheckPlayerPos()
{
int distance_player = App->scene->player->position.DistanceTo(position);
if (distance_player <= radar && App->scene->player->invincible_timer.ReadSec() >= 1)
{
state = CHASING;
}
else
{
state = IDLE;
}
return true;
}
bool Golem::Idle()
{
if (movable)
{
if (change_dir.ReadSec() > 2)
{
change_dir.Start();
int direc_select = rand() % 4 + 1;
if (direc_select == 1)
{
direction = UP;
}
else if (direc_select == 2)
{
direction = DOWN;
}
else if (direc_select == 3)
{
direction = LEFT;
}
else if (direc_select == 4)
{
direction = RIGHT;
}
}
}
return true;
}
/*bool Golem::Walking()
{
walking = false;
if (reset_distance)
{
distance = rand() % 60 + 20;
dis_moved = 0;
reset_distance = false;
}
Move();
if (dis_moved >= distance)
{
walking = false;
reset_run = true;
}
if (walking == false)
{
state = IDLE;
}
else
{
state = WALKING;
}
return true;
}*/
bool Golem::Move()
{
if (direction == LEFT)
{
//App->map->MovementCost(position.x - speed, position.y, LEFT)
if (App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= speed;
dis_moved++;
}
else
{
//Function to change direction
dis_moved++;
}
walking = true;
}
if (direction == RIGHT)
{
//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == UP)
{
//App->map->MovementCost(position.x, position.y - speed, UP)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == DOWN)
{
//App->map->MovementCost(position.x, position.y + (speed + height), DOWN)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
return true;
}
bool Golem::Chase()
{
if(App->scene->player->invincible_timer.ReadSec() > 1)
{
int distance_player = App->scene->player->position.DistanceTo(position);
if (distance_player <= radar)
{
iPoint player_pos = App->map->WorldToMap(App->scene->player->position.x, App->scene->player->position.y);
GoTo(player_pos, chase_speed);
Orientate();
state = CHASING;
}
else
{
state = IDLE;
}
}
return true;
}
bool Golem::Hit()
{
if(hp <= 0)
{
state = DYING;
return true;
}
if (knockback_time.ReadSec() >= 0.2)
{
state = IDLE;
return true;
}
if (hurt_timer.ReadSec() >= 0.2)
{
state = IDLE;
return true;
}
if (dir_hit == UP)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - 1, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= 1;
}
}
else if (dir_hit == DOWN)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + 1, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += 1;
}
}
else if (dir_hit == LEFT)
{
if (App->map->MovementCost(collision_feet->rect.x - 1, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= 1;
}
}
else if (dir_hit == RIGHT)
{
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + 1, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += 1;
}
}
return true;
}
bool Golem::Attack()
{
if (animation.anim[state].East_action.Finished() ||
animation.anim[state].West_action.Finished() ||
animation.anim[state].North_action.Finished() ||
animation.anim[state].South_action.Finished())
{
state = IDLE;
}
return true;
}
bool Golem::Death()
{
if (App->scene->player->bombmanager != nullptr)
{
iPoint pos;
pos.create(position.x - offset_x, position.y - offset_y);
App->scene->items.push_back(App->entity_elements->CreateItem(2, pos));
}
App->entity_elements->DeletePokemon(this);
return true;
}
void Golem::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_feet && c2->type == COLLIDER_BOMB)
{
if (state == STATIC)
{
state = AWAKENING;
iPoint temp = App->map->WorldToMap(position.x, position.y);
App->map->EditCost(temp.x, temp.y, 0);
App->map->EditCost(temp.x - 1, temp.y, 0);
App->map->EditCost(temp.x, temp.y - 1, 0);
App->map->EditCost(temp.x - 1, temp.y - 1, 0);
}
}
if(c1 == collision_feet && c2 == App->scene->player->GetCollisionAttack() && state != HIT && state != STATIC)
{
knockback_time.Start();
animation.anim[5].ResetAnimations();
hurt_timer.Start();
dir_hit = c2->callback->direction;
state = HIT;
hp--;
}
/*if (c1 == collision_feet && c2->type == COLLIDER_PLAYER && c2->callback->state != HIT)
{
if (c2->callback->state != HOOKTHROWN && state != HIT)
{
state = ATTACKING;
animation.anim[state].ResetAnimations();
Orientate();
}
}*/
}
}<commit_msg>Golem modified<commit_after>#include "Golem.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1App.h"
#include "p2Defs.h"
#include "j1Scene.h"
#include "j1Input.h"
#include "j1Item.h"
#include "j1Collision.h"
#include "j1Player.h"
#include "j1EntityElementsScene.h"
Golem::Golem()
{
}
Golem::~Golem()
{
}
bool Golem::Awake(pugi::xml_node &conf, uint id)
{
name = conf.attribute("name").as_string("");
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("name").as_int(0);
speed = conf.attribute("name").as_int(0);
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
mode_stone = conf.attribute("mode_stone").as_bool(false);
position = iPoint(conf.attribute("pos_x").as_int(0), conf.attribute("pos_y").as_int(0));
return true;
}
bool Golem::Start()
{
state = STATIC;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 14;
gamestate = TIMETOPLAY;
movable = true;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 14, 14 }, COLLIDER_POKEMON, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
reset_run = true;
//Modify Meta
iPoint temp = App->map->WorldToMap(position.x, position.y);
App->map->EditCost(temp.x, temp.y, App->map->data.tilesets[1]->firstgid + 1);
App->map->EditCost(temp.x - 1, temp.y, App->map->data.tilesets[1]->firstgid + 1);
App->map->EditCost(temp.x, temp.y - 1, App->map->data.tilesets[1]->firstgid + 1);
App->map->EditCost(temp.x - 1, temp.y - 1, App->map->data.tilesets[1]->firstgid + 1);
//Get the animations
animation = *App->anim_manager->GetAnimStruct(5); //id 5 = Golem
// Test for Vertical Slice /// TODO MED-> read stats from XML
radar = 40;
attack_speed = 1;
chase_speed = 1;
return true;
}
bool Golem::Update()
{
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
switch (state)
{
case IDLE:
{
CheckPlayerPos();
Idle();
break;
}
/*case WALKING:
{
CheckPlayerPos();
Walking();
break;
}*/
case CHASING:
{
CheckPlayerPos();
Chase();
break;
}
case ATTACKING:
{
Attack();
break;
}
case HIT:
{
Hit();
break;
}
case STATIC:
{
break;
}
/* This case shoul be added, it reffers when abandoning rock stage */
case AWAKENING:
{
if (mode_stone)
{
mode_stone = false;
timetoplay = SDL_GetTicks();
}
if (mode_stone == false && SDL_GetTicks() - timetoplay > 500)
{
state = IDLE;
}
break;
}
case DYING:
{
Death();
break;
}
default:
{
break;
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Golem::Draw()
{
BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow)
//App->anim_manager->Drawing_Manager(state, direction, position, 6);
int id;
switch (state)
{
case IDLE:
id = 0;
break;
/*case WALKING:
id = 1;
break;*/
case CHASING:
id = 1;
break;
case ATTACKING:
id = 2;
break;
case STATIC:
id = 3;
break;
case AWAKENING:
id = 4;
break;
case HIT:
id = 5;
break;
case DYING:
id = 5;
break;
default:
break;
}
if (direction == UP)
{
anim_rect = animation.anim[id].North_action.GetCurrentFrame();
pivot = animation.anim[id].North_action.GetCurrentOffset();
}
else if (direction == DOWN)
{
anim_rect = animation.anim[id].South_action.GetCurrentFrame();
pivot = animation.anim[id].South_action.GetCurrentOffset();
}
else if (direction == LEFT)
{
anim_rect = animation.anim[id].West_action.GetCurrentFrame();
pivot = animation.anim[id].West_action.GetCurrentOffset();
}
else if (direction == RIGHT)
{
anim_rect = animation.anim[id].East_action.GetCurrentFrame();
pivot = animation.anim[id].East_action.GetCurrentOffset();
}
//DRAW
App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect);
}
bool Golem::CleanUp()
{
return true;
}
void Golem::AddItem(Item* item)
{
item_inside = item;
item->canBlit = false;
}
void Golem::Drop_item()
{
item_inside->canBlit = true;
item_inside->position.x = position.x;
item_inside->position.y = position.y;
item_inside = NULL;
}
bool Golem::CheckPlayerPos()
{
int distance_player = App->scene->player->position.DistanceTo(position);
if (distance_player <= radar && App->scene->player->invincible_timer.ReadSec() >= 1)
{
state = CHASING;
}
else
{
state = IDLE;
}
return true;
}
bool Golem::Idle()
{
if (movable)
{
if (change_dir.ReadSec() > 2)
{
change_dir.Start();
int direc_select = rand() % 4 + 1;
if (direc_select == 1)
{
direction = UP;
}
else if (direc_select == 2)
{
direction = DOWN;
}
else if (direc_select == 3)
{
direction = LEFT;
}
else if (direc_select == 4)
{
direction = RIGHT;
}
}
}
return true;
}
/*bool Golem::Walking()
{
walking = false;
if (reset_distance)
{
distance = rand() % 60 + 20;
dis_moved = 0;
reset_distance = false;
}
Move();
if (dis_moved >= distance)
{
walking = false;
reset_run = true;
}
if (walking == false)
{
state = IDLE;
}
else
{
state = WALKING;
}
return true;
}*/
bool Golem::Move()
{
if (direction == LEFT)
{
//App->map->MovementCost(position.x - speed, position.y, LEFT)
if (App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= speed;
dis_moved++;
}
else
{
//Function to change direction
dis_moved++;
}
walking = true;
}
if (direction == RIGHT)
{
//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == UP)
{
//App->map->MovementCost(position.x, position.y - speed, UP)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == DOWN)
{
//App->map->MovementCost(position.x, position.y + (speed + height), DOWN)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
return true;
}
bool Golem::Chase()
{
if(App->scene->player->invincible_timer.ReadSec() > 1)
{
int distance_player = App->scene->player->position.DistanceTo(position);
if (distance_player <= radar)
{
iPoint player_pos = App->map->WorldToMap(App->scene->player->position.x, App->scene->player->position.y);
GoTo(player_pos, chase_speed);
Orientate();
state = CHASING;
}
else
{
state = IDLE;
}
}
return true;
}
bool Golem::Hit()
{
if(hp <= 0)
{
state = DYING;
return true;
}
if (knockback_time.ReadSec() >= 0.2)
{
state = IDLE;
return true;
}
if (hurt_timer.ReadSec() >= 0.2)
{
state = IDLE;
return true;
}
if (dir_hit == UP)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - 1, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= 1;
}
}
else if (dir_hit == DOWN)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + 1, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += 1;
}
}
else if (dir_hit == LEFT)
{
if (App->map->MovementCost(collision_feet->rect.x - 1, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= 1;
}
}
else if (dir_hit == RIGHT)
{
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + 1, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += 1;
}
}
return true;
}
bool Golem::Attack()
{
if (animation.anim[state].East_action.Finished() ||
animation.anim[state].West_action.Finished() ||
animation.anim[state].North_action.Finished() ||
animation.anim[state].South_action.Finished())
{
state = IDLE;
}
return true;
}
bool Golem::Death()
{
if (App->scene->player->bombmanager != nullptr)
{
iPoint pos;
pos.create(position.x - offset_x, position.y - offset_y);
App->scene->items.push_back(App->entity_elements->CreateItem(2, pos));
}
App->entity_elements->DeletePokemon(this);
return true;
}
void Golem::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_feet && c2->type == COLLIDER_BOMB)
{
if (state == STATIC)
{
state = AWAKENING;
iPoint temp = App->map->WorldToMap(position.x, position.y);
App->map->EditCost(temp.x, temp.y, 0);
App->map->EditCost(temp.x - 1, temp.y, 0);
App->map->EditCost(temp.x, temp.y - 1, 0);
App->map->EditCost(temp.x - 1, temp.y - 1, 0);
}
}
if(c1 == collision_feet && c2 == App->scene->player->GetCollisionAttack() && state != HIT && state != STATIC// &&
/*c2->callback->state != HIT && c2->callback->state != HOOKTHROWN*/)
{
knockback_time.Start();
animation.anim[5].ResetAnimations();
hurt_timer.Start();
dir_hit = c2->callback->direction;
state = HIT;
hp--;
}
/*
if (c1 == collision_feet && c2->type == COLLIDER_PLAYER && c2->callback->state != HIT)
{
if (c2->callback->state != HOOKTHROWN && state != HIT)
{
state = ATTACKING;
animation.anim[state].ResetAnimations();
Orientate();
}
}
*/
}
}<|endoftext|> |
<commit_before>#include "clockUtils/sockets/TcpSocket.h"
#include "clockUtils/errors.h"
#include <WinSock2.h>
#include <thread>
#include <chrono>
namespace clockUtils {
namespace sockets {
int TcpSocket::_counter = 0;
std::mutex TcpSocket::_lock;
TcpSocket::TcpSocket() : _sock(-1), _status(SocketStatus::INACTIVE), _buffer() {
_lock.lock();
if (_counter == 0) {
WSADATA wsa;
WSAStartup(MAKEWORD(2, 0), &wsa);
}
_counter++;
_lock.unlock();
_worker = new std::thread([this]() {
while (!_terminate) {
_todoLock.lock();
while(_todo.size() > 0) {
_todoLock.unlock();
writePacket(const_cast<const unsigned char *>(&_todo.front()[0]), _todo.front().size());
_todoLock.lock();
_todo.pop();
}
_todoLock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
}
TcpSocket::~TcpSocket() {
_terminate = true;
_worker->join();
delete _worker;
close();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
_lock.lock();
if (_counter == 1) {
WSACleanup();
}
_counter++;
_lock.unlock();
}
void TcpSocket::close() {
if (_sock != -1) {
shutdown(_sock, SD_BOTH);
closesocket(_sock);
_sock = -1;
_status = SocketStatus::INACTIVE;
}
}
ClockError TcpSocket::getLastError() {
int error = WSAGetLastError();
if (error == WSAEADDRINUSE) {
return ClockError::ADDRESS_INUSE;
} else if (error == WSA_INVALID_PARAMETER) {
return ClockError::INVALID_USAGE;
} else if (error == WSA_INVALID_HANDLE) {
return ClockError::INVALID_USAGE;
} else if (error == WSA_OPERATION_ABORTED) {
return ClockError::NOT_READY;
} else if (error == WSAEINTR) {
return ClockError::NOT_READY;
} else if (error == WSAEBADF) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEACCES) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEFAULT) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEINVAL) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEWOULDBLOCK) {
return ClockError::IN_PROGRESS;
} else if (error == WSAEINPROGRESS) {
return ClockError::IN_PROGRESS;
} else if (error == WSAEALREADY) {
return ClockError::NOT_READY;
} else if (error == WSAENOTSOCK) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEDESTADDRREQ) {
return ClockError::INVALID_IP;
} else if (error == WSAEADDRNOTAVAIL) {
return ClockError::INVALID_PORT;
} else if (error == WSAENETDOWN) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAENETUNREACH) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAENETUNREACH) {
return ClockError::NOT_READY;
} else if (error == WSAECONNRESET) {
return ClockError::NOT_READY;
} else if (error == WSAEISCONN) {
return ClockError::INVALID_USAGE;
} else if (error == WSAENOTCONN) {
return ClockError::INVALID_USAGE;
} else if (error == WSAESHUTDOWN) {
return ClockError::INVALID_USAGE;
} else if (error == WSAETIMEDOUT) {
return ClockError::TIMEOUT;
} else if (error == WSAECONNREFUSED) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAEHOSTDOWN) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAEHOSTUNREACH) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSASYSNOTREADY) {
return ClockError::NOT_READY;
} else if (error == WSAECONNABORTED) {
return ClockError::NOT_CONNECTED;
}
return ClockError::UNKNOWN;
}
} /* namespace sockets */
} /* namespace clockUtils */
<commit_msg>CU-21 (sockets) fixed TcpSocket's asyn write on Windows<commit_after>#include "clockUtils/sockets/TcpSocket.h"
#include <chrono>
#include <thread>
#include "clockUtils/errors.h"
#include <WinSock2.h>
namespace clockUtils {
namespace sockets {
int TcpSocket::_counter = 0;
std::mutex TcpSocket::_lock;
TcpSocket::TcpSocket() : _sock(-1), _status(SocketStatus::INACTIVE), _todoLock(), _todo(), _buffer(), _terminate(false), _worker(nullptr) {
_lock.lock();
if (_counter == 0) {
WSADATA wsa;
WSAStartup(MAKEWORD(2, 0), &wsa);
}
_counter++;
_lock.unlock();
_worker = new std::thread([this]() {
while (!_terminate) {
_todoLock.lock();
while(_todo.size() > 0) {
_todoLock.unlock();
writePacket(const_cast<const unsigned char *>(&_todo.front()[0]), _todo.front().size());
_todoLock.lock();
_todo.pop();
}
_todoLock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
}
TcpSocket::~TcpSocket() {
_terminate = true;
_worker->join();
delete _worker;
close();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
_lock.lock();
if (_counter == 1) {
WSACleanup();
}
_counter++;
_lock.unlock();
}
void TcpSocket::close() {
if (_sock != -1) {
shutdown(_sock, SD_BOTH);
closesocket(_sock);
_sock = -1;
_status = SocketStatus::INACTIVE;
}
}
ClockError TcpSocket::getLastError() {
int error = WSAGetLastError();
if (error == WSAEADDRINUSE) {
return ClockError::ADDRESS_INUSE;
} else if (error == WSA_INVALID_PARAMETER) {
return ClockError::INVALID_USAGE;
} else if (error == WSA_INVALID_HANDLE) {
return ClockError::INVALID_USAGE;
} else if (error == WSA_OPERATION_ABORTED) {
return ClockError::NOT_READY;
} else if (error == WSAEINTR) {
return ClockError::NOT_READY;
} else if (error == WSAEBADF) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEACCES) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEFAULT) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEINVAL) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEWOULDBLOCK) {
return ClockError::IN_PROGRESS;
} else if (error == WSAEINPROGRESS) {
return ClockError::IN_PROGRESS;
} else if (error == WSAEALREADY) {
return ClockError::NOT_READY;
} else if (error == WSAENOTSOCK) {
return ClockError::INVALID_USAGE;
} else if (error == WSAEDESTADDRREQ) {
return ClockError::INVALID_IP;
} else if (error == WSAEADDRNOTAVAIL) {
return ClockError::INVALID_PORT;
} else if (error == WSAENETDOWN) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAENETUNREACH) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAENETUNREACH) {
return ClockError::NOT_READY;
} else if (error == WSAECONNRESET) {
return ClockError::NOT_READY;
} else if (error == WSAEISCONN) {
return ClockError::INVALID_USAGE;
} else if (error == WSAENOTCONN) {
return ClockError::INVALID_USAGE;
} else if (error == WSAESHUTDOWN) {
return ClockError::INVALID_USAGE;
} else if (error == WSAETIMEDOUT) {
return ClockError::TIMEOUT;
} else if (error == WSAECONNREFUSED) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAEHOSTDOWN) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSAEHOSTUNREACH) {
return ClockError::CONNECTION_FAILED;
} else if (error == WSASYSNOTREADY) {
return ClockError::NOT_READY;
} else if (error == WSAECONNABORTED) {
return ClockError::NOT_CONNECTED;
}
return ClockError::UNKNOWN;
}
} /* namespace sockets */
} /* namespace clockUtils */
<|endoftext|> |
<commit_before>#include "PipeThrottler.h"
#include "Server.h"
#include "Interface/Mutex.h"
PipeThrottler::PipeThrottler(size_t bps)
: throttle_bps(bps), curr_bytes(0), lastresettime(0)
{
mutex=Server->createMutex();
}
PipeThrottler::~PipeThrottler(void)
{
Server->destroy(mutex);
}
bool PipeThrottler::addBytes(size_t new_bytes, bool wait)
{
IScopedLock lock(mutex);
if(throttle_bps==0) return true;
int64 ctime=Server->getTimeMS();
if(ctime-lastresettime>1000)
{
lastresettime=ctime;
curr_bytes=0;
}
curr_bytes+=new_bytes;
int64 passed_time=ctime-lastresettime;
if(passed_time>0)
{
size_t bps=(size_t)(((_i64)curr_bytes*1000)/passed_time);
if(bps>throttle_bps)
{
size_t maxRateTime=(size_t)(((_i64)curr_bytes*1000)/throttle_bps);
unsigned int sleepTime=(unsigned int)(maxRateTime-passed_time);
if(sleepTime>0)
{
if(wait)
{
Server->wait(sleepTime);
if(Server->getTimeMS()-lastresettime>1000)
{
curr_bytes=0;
lastresettime=Server->getTimeMS();
}
}
return false;
}
}
}
else if(curr_bytes>=throttle_bps)
{
if(wait)
{
Server->wait(1000);
}
curr_bytes=0;
lastresettime=Server->getTimeMS();
return false;
}
return true;
}
void PipeThrottler::changeThrottleLimit(size_t bps)
{
IScopedLock lock(mutex);
throttle_bps=bps;
}<commit_msg>Debug logging for throttling<commit_after>#include "PipeThrottler.h"
#include "Server.h"
#include "Interface/Mutex.h"
#include "stringtools.h"
#define DLOG(x) x
PipeThrottler::PipeThrottler(size_t bps)
: throttle_bps(bps), curr_bytes(0), lastresettime(0)
{
mutex=Server->createMutex();
}
PipeThrottler::~PipeThrottler(void)
{
Server->destroy(mutex);
}
bool PipeThrottler::addBytes(size_t new_bytes, bool wait)
{
IScopedLock lock(mutex);
if(throttle_bps==0) return true;
int64 ctime=Server->getTimeMS();
if(ctime-lastresettime>1000)
{
lastresettime=ctime;
curr_bytes=0;
}
curr_bytes+=new_bytes;
int64 passed_time=ctime-lastresettime;
if(passed_time>0)
{
size_t bps=(size_t)(((_i64)curr_bytes*1000)/passed_time);
if(bps>throttle_bps)
{
size_t maxRateTime=(size_t)(((_i64)curr_bytes*1000)/throttle_bps);
unsigned int sleepTime=(unsigned int)(maxRateTime-passed_time);
if(sleepTime>0)
{
if(wait)
{
DLOG(Server->Log("Throttler: Sleeping for " + nconvert(sleepTime)+ "ms", LL_DEBUG));
Server->wait(sleepTime);
if(Server->getTimeMS()-lastresettime>1000)
{
curr_bytes=0;
lastresettime=Server->getTimeMS();
}
}
return false;
}
}
}
else if(curr_bytes>=throttle_bps)
{
if(wait)
{
DLOG(Server->Log("Throttler: Sleeping for " + nconvert(1000)+ "ms", LL_DEBUG));
Server->wait(1000);
}
curr_bytes=0;
lastresettime=Server->getTimeMS();
return false;
}
return true;
}
void PipeThrottler::changeThrottleLimit(size_t bps)
{
IScopedLock lock(mutex);
throttle_bps=bps;
}<|endoftext|> |
<commit_before>#include "ImagePyramid.hpp"
#include <openslide/openslide.h>
#include <tiffio.h>
#include <FAST/Utility.hpp>
#include <FAST/Data/Image.hpp>
#include <FAST/Data/Access/ImagePyramidAccess.hpp>
#include <utility>
#ifdef WIN32
#include <winbase.h>
#else
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace fast {
int ImagePyramid::m_counter = 0;
ImagePyramid::ImagePyramid(int width, int height, int channels, int patchWidth, int patchHeight) {
if(channels <= 0 || channels > 4)
throw Exception("Nr of channels must be between 1 and 4");
// Determine how many levels
int currentLevel = 0;
int currentWidth = width;
int currentHeight = height;
m_channels = channels;
#ifdef WIN32
m_tiffPath = "C:/windows/temp/fast_image_pyramid_" + std::to_string(m_counter) + ".tiff";
#else
m_tiffPath = "/tmp/fast_image_pyramid_" + std::to_string(m_counter) + ".tiff";
#endif
TIFFSetErrorHandler([](const char* module, const char* fmt, va_list ap) {
auto str = make_uninitialized_unique<char[]>(512);
sprintf(str.get(), fmt, ap);
Reporter::warning() << "TIFF: " << module << ": " << str.get() << Reporter::end();
});
TIFFSetWarningHandler([](const char* module, const char* fmt, va_list ap) {
auto str = make_uninitialized_unique<char[]>(512);
sprintf(str.get(), fmt, ap);
Reporter::warning() << "TIFF: " << module << ": " << str.get() << Reporter::end();
});
m_tiffHandle = TIFFOpen(m_tiffPath.c_str(), "w8");
auto tiff = m_tiffHandle;
m_counter += 1;
ImageCompression compression = ImageCompression::LZW;
uint photometric = PHOTOMETRIC_RGB;
uint bitsPerSample = 8;
uint samplesPerPixel = 3; // RGBA image pyramid is converted to RGB with getPatchAsImage
if(channels == 1) {
photometric = PHOTOMETRIC_MINISBLACK; // Photometric mask causes crash..
samplesPerPixel = 1;
}
while(true) {
currentWidth = width / std::pow(2, currentLevel);
currentHeight = height / std::pow(2, currentLevel);
if(currentWidth < 4096 && currentHeight < 4096) // IMPORTANT: This should be the same as in PatchStitcher.
break;
reportInfo() << "Processing level " << currentLevel << reportEnd();
std::size_t bytes = (std::size_t)currentWidth * currentHeight * m_channels * sizeof(char);
// Get total size of image
float sizeInMB = (float)bytes / (1024 * 1024);
reportInfo() << "WSI level size: " << currentWidth << ", " << currentHeight << ", " << m_channels << reportEnd();
reportInfo() << "WSI level size: " << sizeInMB << " MBs" << reportEnd();
ImagePyramidLevel levelData;
levelData.width = currentWidth;
levelData.height = currentHeight;
levelData.tileWidth = patchWidth;
levelData.tileHeight = patchHeight;
levelData.tilesX = std::ceil((float)levelData.width / levelData.tileWidth);
levelData.tilesY = std::ceil((float)levelData.height / levelData.tileHeight);
// Write base tags
TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, bitsPerSample);
TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);
TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
if(currentLevel > 0) {
// All levels except highest res level should have this tag?
TIFFSetField(tiff, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);
}
switch(compression) {
case ImageCompression::RAW:
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
case ImageCompression::LZW:
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
break;
case ImageCompression::JPEG:
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
break;
case ImageCompression::JPEG2000:
// TODO NOT IMPLEMENTED
throw NotImplementedException();
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JP2000);
break;
}
TIFFSetField(tiff, TIFFTAG_TILEWIDTH, levelData.tileWidth);
TIFFSetField(tiff, TIFFTAG_TILELENGTH, levelData.tileHeight);
TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, levelData.width);
TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, levelData.height);
m_levels.push_back(levelData);
// TODO need to initialize somehow?
// We need to write the first tile for some reason... or we will get an error saying it is missing required
// TileOffsets
auto data = std::make_unique<uchar[]>(levelData.tileWidth*levelData.tileHeight*samplesPerPixel); // Is initialized to zeros
TIFFWriteTile(tiff, data.get(), 0, 0, 0, 0);
/*
// TODO Do we really need to inititalize all tiles? This takes time..
for(int y = 0; y < levelData.tilesY; ++y) {
for(int x = 0; x < levelData.tilesX; ++x) {
TIFFWriteTile(tiff, data.get(), x*levelData.tileWidth, y*levelData.tileHeight, 0, 0);
}
}*/
// END
reportInfo() << "Done creating level " << currentLevel << reportEnd();
++currentLevel;
TIFFWriteDirectory(m_tiffHandle);
}
mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));
m_initialized = true;
m_pyramidFullyInitialized = false;
m_counter += 1;
}
ImagePyramid::ImagePyramid(openslide_t *fileHandle, std::vector<ImagePyramidLevel> levels) {
m_fileHandle = fileHandle;
m_levels = std::move(levels);
m_channels = 4;
for(int i = 0; i < m_levels.size(); ++i) {
m_levels[i].tilesX = std::ceil((float)m_levels[i].width / m_levels[i].tileWidth);
m_levels[i].tilesY = std::ceil((float)m_levels[i].height / m_levels[i].tileHeight);
}
mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));
m_initialized = true;
m_pyramidFullyInitialized = true;
m_counter += 1;
}
ImagePyramid::ImagePyramid() {
m_initialized = false;
m_pyramidFullyInitialized = false;
}
ImagePyramidLevel ImagePyramid::getLevelInfo(int level) {
/*if(!m_initialized)
throw Exception("ImagePyramid has not been initialized.");*/ // TODO why does this fail?
if(level < 0) // Negative level means last level (lowest resolution)
level = getNrOfLevels()-1;
if(level < 0 || level > m_levels.size()-1)
throw Exception("Level " + std::to_string(level) + " doesn't exist in ImagePyramid. Pyramid has " + std::to_string(m_levels.size()) + " levels");
return m_levels[level];
}
int ImagePyramid::getNrOfLevels() {
return m_levels.size();
}
int ImagePyramid::getLevelWidth(int level) {
return getLevelInfo(level).width;
}
int ImagePyramid::getLevelHeight(int level) {
return getLevelInfo(level).height;
}
int ImagePyramid::getLevelTileWidth(int level) {
return getLevelInfo(level).tileWidth;
}
int ImagePyramid::getLevelTileHeight(int level) {
return getLevelInfo(level).tileHeight;
}
int ImagePyramid::getLevelTilesX(int level) {
return getLevelInfo(level).tilesX;
}
int ImagePyramid::getLevelTilesY(int level) {
return getLevelInfo(level).tilesY;
}
int ImagePyramid::getFullWidth() {
return getLevelInfo(0).width;
}
int ImagePyramid::getFullHeight() {
return getLevelInfo(0).height;
}
void ImagePyramid::free(ExecutionDevice::pointer device) {
freeAll();
}
void ImagePyramid::freeAll() {
if(m_fileHandle != nullptr) {
m_levels.clear();
openslide_close(m_fileHandle);
} else if(m_tiffHandle != nullptr) {
m_levels.clear();
TIFFClose(m_tiffHandle);
} else {
for(auto& item : m_levels) {
if(item.memoryMapped) {
#ifdef WIN32
UnmapViewOfFile(item.data);
CloseHandle(item.fileHandle);
#else
munmap(item.data, item.width*item.height*m_channels);
close(item.fileHandle);
#endif
} else {
delete[] item.data;
}
}
m_levels.clear();
}
m_initialized = false;
m_fileHandle = nullptr;
}
ImagePyramid::~ImagePyramid() {
freeAll();
}
int ImagePyramid::getNrOfChannels() const {
return m_channels;
}
ImagePyramidAccess::pointer ImagePyramid::getAccess(accessType type) {
if(!m_initialized)
throw Exception("ImagePyramid has not been initialized.");
blockIfBeingWrittenTo();
if(type == ACCESS_READ_WRITE) {
blockIfBeingAccessed();
std::unique_lock<std::mutex> lock(mDataIsBeingWrittenToMutex);
mDataIsBeingWrittenTo = true;
}
//updateHostData();
if(type == ACCESS_READ_WRITE) {
//setAllDataToOutOfDate();
updateModifiedTimestamp();
}
//mHostDataIsUpToDate = true;
{
std::unique_lock<std::mutex> lock(mDataIsBeingAccessedMutex);
mDataIsBeingAccessed = true;
}
return std::make_unique<ImagePyramidAccess>(m_levels, m_fileHandle, m_tiffHandle, std::static_pointer_cast<ImagePyramid>(mPtr.lock()), type == ACCESS_READ_WRITE, m_initializedPatchList);
}
void ImagePyramid::setDirtyPatch(int level, int patchIdX, int patchIdY) {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
const std::string tileString =
std::to_string(level) + "_" + std::to_string(patchIdX) + "_" + std::to_string(patchIdY);
m_dirtyPatches.insert(tileString);
}
std::unordered_set<std::string> ImagePyramid::getDirtyPatches() {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
return m_dirtyPatches;
}
bool ImagePyramid::isDirtyPatch(const std::string& tileID) {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
return m_dirtyPatches.count(tileID);
}
void ImagePyramid::clearDirtyPatches(std::set<std::string> patches) {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
for(auto&& patch : patches)
m_dirtyPatches.erase(patch);
}
void ImagePyramid::setSpacing(Vector3f spacing) {
m_spacing = spacing;
if(m_tiffHandle != nullptr) {
// Write spacing to TIFF file
if(spacing.x() != 1 && spacing.y() != 1) { // Spacing == 1 means not set.
auto access = getAccess(ACCESS_READ_WRITE); // Ensure we have exclusive access to TIFF
for(int level = 0; level < getNrOfLevels(); ++level) {
TIFFSetDirectory(m_tiffHandle, level);
TIFFSetField(m_tiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER);
float scaleX = (float)getFullWidth() / getLevelWidth(level);
float scaleY = (float)getFullHeight() / getLevelHeight(level);
TIFFSetField(m_tiffHandle, TIFFTAG_XRESOLUTION,
1.0f / (spacing.x() / 10.0f) * scaleX); // Convert to cm, and adjust for level
TIFFSetField(m_tiffHandle, TIFFTAG_YRESOLUTION,
1.0f / (spacing.y() / 10.0f) * scaleY); // Convert to cm, and adjust for level
TIFFRewriteDirectory(m_tiffHandle); // Write changes
}
}
}
}
Vector3f ImagePyramid::getSpacing() const {
return m_spacing;
}
ImagePyramid::ImagePyramid(TIFF *fileHandle, std::vector<ImagePyramidLevel> levels, int channels) {
if(channels <= 0 || channels > 4)
throw Exception("Nr of channels must be between 1 and 4 in ImagePyramid when importing from TIFF");
m_tiffHandle = fileHandle;
m_levels = levels;
m_channels = channels;
for(int i = 0; i < m_levels.size(); ++i) {
m_levels[i].tilesX = std::ceil((float)m_levels[i].width / m_levels[i].tileWidth);
m_levels[i].tilesY = std::ceil((float)m_levels[i].height / m_levels[i].tileHeight);
}
// Get spacing from TIFF
float spacingX;
float spacingY;
TIFFSetDirectory(fileHandle, 0);
int resX = TIFFGetField(fileHandle, TIFFTAG_XRESOLUTION, &spacingX);
int resY = TIFFGetField(fileHandle, TIFFTAG_YRESOLUTION, &spacingY);
if(resX == 1 && resY == 1) {
// Convert from cm
spacingX = 1.0f/(spacingX/10.0f);
spacingY = 1.0f/(spacingY/10.0f);
reportInfo() << "Spacing from TIFF was" << spacingX << " " << spacingY << reportEnd();
m_spacing = Vector3f(spacingX, spacingY, 1.0f);
}
mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));
m_initialized = true;
m_pyramidFullyInitialized = true;
m_counter += 1;
}
bool ImagePyramid::isBGRA() const {
return m_fileHandle != nullptr;
}
bool ImagePyramid::usesTIFF() const {
return m_tiffHandle != nullptr;
}
std::string ImagePyramid::getTIFFPath() const {
return m_tiffPath;
}
bool ImagePyramid::usesOpenSlide() const {
return m_fileHandle != nullptr;
}
bool ImagePyramid::isPyramidFullyInitialized() const {
return m_pyramidFullyInitialized;
}
}
<commit_msg>Always create level 0 in ImagePyramid even if it is very small<commit_after>#include "ImagePyramid.hpp"
#include <openslide/openslide.h>
#include <tiffio.h>
#include <FAST/Utility.hpp>
#include <FAST/Data/Image.hpp>
#include <FAST/Data/Access/ImagePyramidAccess.hpp>
#include <utility>
#ifdef WIN32
#include <winbase.h>
#else
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace fast {
int ImagePyramid::m_counter = 0;
ImagePyramid::ImagePyramid(int width, int height, int channels, int patchWidth, int patchHeight) {
if(channels <= 0 || channels > 4)
throw Exception("Nr of channels must be between 1 and 4");
// Determine how many levels
int currentLevel = 0;
int currentWidth = width;
int currentHeight = height;
m_channels = channels;
#ifdef WIN32
m_tiffPath = "C:/windows/temp/fast_image_pyramid_" + std::to_string(m_counter) + ".tiff";
#else
m_tiffPath = "/tmp/fast_image_pyramid_" + std::to_string(m_counter) + ".tiff";
#endif
TIFFSetErrorHandler([](const char* module, const char* fmt, va_list ap) {
auto str = make_uninitialized_unique<char[]>(512);
sprintf(str.get(), fmt, ap);
Reporter::warning() << "TIFF: " << module << ": " << str.get() << Reporter::end();
});
TIFFSetWarningHandler([](const char* module, const char* fmt, va_list ap) {
auto str = make_uninitialized_unique<char[]>(512);
sprintf(str.get(), fmt, ap);
Reporter::warning() << "TIFF: " << module << ": " << str.get() << Reporter::end();
});
m_tiffHandle = TIFFOpen(m_tiffPath.c_str(), "w8");
auto tiff = m_tiffHandle;
m_counter += 1;
ImageCompression compression = ImageCompression::LZW;
uint photometric = PHOTOMETRIC_RGB;
uint bitsPerSample = 8;
uint samplesPerPixel = 3; // RGBA image pyramid is converted to RGB with getPatchAsImage
if(channels == 1) {
photometric = PHOTOMETRIC_MINISBLACK; // Photometric mask causes crash..
samplesPerPixel = 1;
}
while(true) {
currentWidth = width / std::pow(2, currentLevel);
currentHeight = height / std::pow(2, currentLevel);
if(currentLevel > 0 && (currentWidth < 4096 && currentHeight < 4096)) // IMPORTANT: This should be the same as in PatchStitcher.
break;
reportInfo() << "Processing level " << currentLevel << reportEnd();
std::size_t bytes = (std::size_t)currentWidth * currentHeight * m_channels * sizeof(char);
// Get total size of image
float sizeInMB = (float)bytes / (1024 * 1024);
reportInfo() << "WSI level size: " << currentWidth << ", " << currentHeight << ", " << m_channels << reportEnd();
reportInfo() << "WSI level size: " << sizeInMB << " MBs" << reportEnd();
ImagePyramidLevel levelData;
levelData.width = currentWidth;
levelData.height = currentHeight;
levelData.tileWidth = patchWidth;
levelData.tileHeight = patchHeight;
levelData.tilesX = std::ceil((float)levelData.width / levelData.tileWidth);
levelData.tilesY = std::ceil((float)levelData.height / levelData.tileHeight);
// Write base tags
TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, bitsPerSample);
TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);
TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
if(currentLevel > 0) {
// All levels except highest res level should have this tag?
TIFFSetField(tiff, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);
}
switch(compression) {
case ImageCompression::RAW:
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
case ImageCompression::LZW:
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
break;
case ImageCompression::JPEG:
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
break;
case ImageCompression::JPEG2000:
// TODO NOT IMPLEMENTED
throw NotImplementedException();
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JP2000);
break;
}
TIFFSetField(tiff, TIFFTAG_TILEWIDTH, levelData.tileWidth);
TIFFSetField(tiff, TIFFTAG_TILELENGTH, levelData.tileHeight);
TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, levelData.width);
TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, levelData.height);
m_levels.push_back(levelData);
// TODO need to initialize somehow?
// We need to write the first tile for some reason... or we will get an error saying it is missing required
// TileOffsets
auto data = std::make_unique<uchar[]>(levelData.tileWidth*levelData.tileHeight*samplesPerPixel); // Is initialized to zeros
TIFFWriteTile(tiff, data.get(), 0, 0, 0, 0);
/*
// TODO Do we really need to inititalize all tiles? This takes time..
for(int y = 0; y < levelData.tilesY; ++y) {
for(int x = 0; x < levelData.tilesX; ++x) {
TIFFWriteTile(tiff, data.get(), x*levelData.tileWidth, y*levelData.tileHeight, 0, 0);
}
}*/
// END
reportInfo() << "Done creating level " << currentLevel << reportEnd();
++currentLevel;
TIFFWriteDirectory(m_tiffHandle);
}
mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));
m_initialized = true;
m_pyramidFullyInitialized = false;
m_counter += 1;
}
ImagePyramid::ImagePyramid(openslide_t *fileHandle, std::vector<ImagePyramidLevel> levels) {
m_fileHandle = fileHandle;
m_levels = std::move(levels);
m_channels = 4;
for(int i = 0; i < m_levels.size(); ++i) {
m_levels[i].tilesX = std::ceil((float)m_levels[i].width / m_levels[i].tileWidth);
m_levels[i].tilesY = std::ceil((float)m_levels[i].height / m_levels[i].tileHeight);
}
mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));
m_initialized = true;
m_pyramidFullyInitialized = true;
m_counter += 1;
}
ImagePyramid::ImagePyramid() {
m_initialized = false;
m_pyramidFullyInitialized = false;
}
ImagePyramidLevel ImagePyramid::getLevelInfo(int level) {
/*if(!m_initialized)
throw Exception("ImagePyramid has not been initialized.");*/ // TODO why does this fail?
if(level < 0) // Negative level means last level (lowest resolution)
level = getNrOfLevels()-1;
if(level < 0 || level > m_levels.size()-1)
throw Exception("Level " + std::to_string(level) + " doesn't exist in ImagePyramid. Pyramid has " + std::to_string(m_levels.size()) + " levels");
return m_levels[level];
}
int ImagePyramid::getNrOfLevels() {
return m_levels.size();
}
int ImagePyramid::getLevelWidth(int level) {
return getLevelInfo(level).width;
}
int ImagePyramid::getLevelHeight(int level) {
return getLevelInfo(level).height;
}
int ImagePyramid::getLevelTileWidth(int level) {
return getLevelInfo(level).tileWidth;
}
int ImagePyramid::getLevelTileHeight(int level) {
return getLevelInfo(level).tileHeight;
}
int ImagePyramid::getLevelTilesX(int level) {
return getLevelInfo(level).tilesX;
}
int ImagePyramid::getLevelTilesY(int level) {
return getLevelInfo(level).tilesY;
}
int ImagePyramid::getFullWidth() {
return getLevelInfo(0).width;
}
int ImagePyramid::getFullHeight() {
return getLevelInfo(0).height;
}
void ImagePyramid::free(ExecutionDevice::pointer device) {
freeAll();
}
void ImagePyramid::freeAll() {
if(m_fileHandle != nullptr) {
m_levels.clear();
openslide_close(m_fileHandle);
} else if(m_tiffHandle != nullptr) {
m_levels.clear();
TIFFClose(m_tiffHandle);
} else {
for(auto& item : m_levels) {
if(item.memoryMapped) {
#ifdef WIN32
UnmapViewOfFile(item.data);
CloseHandle(item.fileHandle);
#else
munmap(item.data, item.width*item.height*m_channels);
close(item.fileHandle);
#endif
} else {
delete[] item.data;
}
}
m_levels.clear();
}
m_initialized = false;
m_fileHandle = nullptr;
}
ImagePyramid::~ImagePyramid() {
freeAll();
}
int ImagePyramid::getNrOfChannels() const {
return m_channels;
}
ImagePyramidAccess::pointer ImagePyramid::getAccess(accessType type) {
if(!m_initialized)
throw Exception("ImagePyramid has not been initialized.");
blockIfBeingWrittenTo();
if(type == ACCESS_READ_WRITE) {
blockIfBeingAccessed();
std::unique_lock<std::mutex> lock(mDataIsBeingWrittenToMutex);
mDataIsBeingWrittenTo = true;
}
//updateHostData();
if(type == ACCESS_READ_WRITE) {
//setAllDataToOutOfDate();
updateModifiedTimestamp();
}
//mHostDataIsUpToDate = true;
{
std::unique_lock<std::mutex> lock(mDataIsBeingAccessedMutex);
mDataIsBeingAccessed = true;
}
return std::make_unique<ImagePyramidAccess>(m_levels, m_fileHandle, m_tiffHandle, std::static_pointer_cast<ImagePyramid>(mPtr.lock()), type == ACCESS_READ_WRITE, m_initializedPatchList);
}
void ImagePyramid::setDirtyPatch(int level, int patchIdX, int patchIdY) {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
const std::string tileString =
std::to_string(level) + "_" + std::to_string(patchIdX) + "_" + std::to_string(patchIdY);
m_dirtyPatches.insert(tileString);
}
std::unordered_set<std::string> ImagePyramid::getDirtyPatches() {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
return m_dirtyPatches;
}
bool ImagePyramid::isDirtyPatch(const std::string& tileID) {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
return m_dirtyPatches.count(tileID);
}
void ImagePyramid::clearDirtyPatches(std::set<std::string> patches) {
std::lock_guard<std::mutex> lock(m_dirtyPatchMutex);
for(auto&& patch : patches)
m_dirtyPatches.erase(patch);
}
void ImagePyramid::setSpacing(Vector3f spacing) {
m_spacing = spacing;
if(m_tiffHandle != nullptr) {
// Write spacing to TIFF file
if(spacing.x() != 1 && spacing.y() != 1) { // Spacing == 1 means not set.
auto access = getAccess(ACCESS_READ_WRITE); // Ensure we have exclusive access to TIFF
for(int level = 0; level < getNrOfLevels(); ++level) {
TIFFSetDirectory(m_tiffHandle, level);
TIFFSetField(m_tiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER);
float scaleX = (float)getFullWidth() / getLevelWidth(level);
float scaleY = (float)getFullHeight() / getLevelHeight(level);
TIFFSetField(m_tiffHandle, TIFFTAG_XRESOLUTION,
1.0f / (spacing.x() / 10.0f) * scaleX); // Convert to cm, and adjust for level
TIFFSetField(m_tiffHandle, TIFFTAG_YRESOLUTION,
1.0f / (spacing.y() / 10.0f) * scaleY); // Convert to cm, and adjust for level
TIFFRewriteDirectory(m_tiffHandle); // Write changes
}
}
}
}
Vector3f ImagePyramid::getSpacing() const {
return m_spacing;
}
ImagePyramid::ImagePyramid(TIFF *fileHandle, std::vector<ImagePyramidLevel> levels, int channels) {
if(channels <= 0 || channels > 4)
throw Exception("Nr of channels must be between 1 and 4 in ImagePyramid when importing from TIFF");
m_tiffHandle = fileHandle;
m_levels = levels;
m_channels = channels;
for(int i = 0; i < m_levels.size(); ++i) {
m_levels[i].tilesX = std::ceil((float)m_levels[i].width / m_levels[i].tileWidth);
m_levels[i].tilesY = std::ceil((float)m_levels[i].height / m_levels[i].tileHeight);
}
// Get spacing from TIFF
float spacingX;
float spacingY;
TIFFSetDirectory(fileHandle, 0);
int resX = TIFFGetField(fileHandle, TIFFTAG_XRESOLUTION, &spacingX);
int resY = TIFFGetField(fileHandle, TIFFTAG_YRESOLUTION, &spacingY);
if(resX == 1 && resY == 1) {
// Convert from cm
spacingX = 1.0f/(spacingX/10.0f);
spacingY = 1.0f/(spacingY/10.0f);
reportInfo() << "Spacing from TIFF was" << spacingX << " " << spacingY << reportEnd();
m_spacing = Vector3f(spacingX, spacingY, 1.0f);
}
mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));
m_initialized = true;
m_pyramidFullyInitialized = true;
m_counter += 1;
}
bool ImagePyramid::isBGRA() const {
return m_fileHandle != nullptr;
}
bool ImagePyramid::usesTIFF() const {
return m_tiffHandle != nullptr;
}
std::string ImagePyramid::getTIFFPath() const {
return m_tiffPath;
}
bool ImagePyramid::usesOpenSlide() const {
return m_fileHandle != nullptr;
}
bool ImagePyramid::isPyramidFullyInitialized() const {
return m_pyramidFullyInitialized;
}
}
<|endoftext|> |
<commit_before>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $
// Author: Rene Brun 17/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TCanvas.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
// go via the interpreter???
// if (gProof) gProof->Interrupt(TProof::kHardInterrupt);
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Printf("\n *** Break *** keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
gApplication->HandleTermInput();
return kTRUE;
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo)
PrintLogo();
// Everybody expects iostream to be available, so load it...
#ifndef WIN32
ProcessLine("#include <iostream>");
#endif
// The following libs are also useful to have,
// make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon));
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
gSystem->AddSignalHandler(ih);
SetSignalHandler(ih);
TTermInputHandler *th = new TTermInputHandler(0);
gSystem->AddFileHandler(th);
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt())
Terminate(0);
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *",root_version,root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
#ifdef R__UNIX
if (!strcmp(gVirtualX->GetName(), "X11TTF"))
Printf("\nFreeType Engine v1.1 used to render TrueType fonts.");
#endif
#ifdef _REENTRANT
#ifdef R__UNIX
else
#endif
printf("\n");
Printf("Compiled with thread support.");
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt, fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
const char *op = fDefaultPrompt;
if (strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op;
}
//______________________________________________________________________________
void TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
if (gROOT->Timer()) timer.Start();
Gl_histadd(line);
char *s = line;
while (s && *s == ' ') s++; // strip-off leading blanks
s[strlen(s)-1] = '\0'; // strip also '\n' off
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++;
ProcessLine(s);
if (strstr(s,".reset") != s)
gInterpreter->EndOfLineAction();
if (gROOT->Timer()) timer.Print();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<commit_msg>Correct FreeType message<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.2 2000/05/31 18:43:50 rdm Exp $
// Author: Rene Brun 17/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TCanvas.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
// go via the interpreter???
// if (gProof) gProof->Interrupt(TProof::kHardInterrupt);
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Printf("\n *** Break *** keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
gApplication->HandleTermInput();
return kTRUE;
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo)
PrintLogo();
// Everybody expects iostream to be available, so load it...
#ifndef WIN32
ProcessLine("#include <iostream>");
#endif
// The following libs are also useful to have,
// make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon));
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
gSystem->AddSignalHandler(ih);
SetSignalHandler(ih);
TTermInputHandler *th = new TTermInputHandler(0);
gSystem->AddFileHandler(th);
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt())
Terminate(0);
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *",root_version,root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
#ifdef R__UNIX
if (!strcmp(gVirtualX->GetName(), "X11TTF"))
Printf("\nFreeType Engine v1.x used to render TrueType fonts.");
#endif
#ifdef _REENTRANT
#ifdef R__UNIX
else
#endif
printf("\n");
Printf("Compiled with thread support.");
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt, fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
const char *op = fDefaultPrompt;
if (strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op;
}
//______________________________________________________________________________
void TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
if (gROOT->Timer()) timer.Start();
Gl_histadd(line);
char *s = line;
while (s && *s == ' ') s++; // strip-off leading blanks
s[strlen(s)-1] = '\0'; // strip also '\n' off
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++;
ProcessLine(s);
if (strstr(s,".reset") != s)
gInterpreter->EndOfLineAction();
if (gROOT->Timer()) timer.Print();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<|endoftext|> |
<commit_before>#include "AConfig.h"
#if(HAS_STD_LIGHTS)
// Includes
#include <Arduino.h>
#include "CLights.h"
#include "CPin.h"
#include "NConfigManager.h"
#include "NModuleManager.h"
#include "NCommManager.h"
// One of these will have the correct pin defined for the lights
#if(HAS_STD_CAPE)
#include "CCape.h"
#endif
#if(HAS_OROV_CONTROLLERBOARD_25)
#include "CControllerBoard.h"
#endif
namespace
{
CPin light( "light", LIGHTS_PIN, CPin::kAnalog, CPin::kOutput );
}
void CLights::Initialize()
{
NConfigManager::m_capabilityBitmask |= ( 1 << LIGHTS_CAPABLE );
light.Reset();
light.Write( 0 );
}
void CLights::Update( CCommand& commandIn )
{
// Check for messages
if( !NCommManager::m_isCommandAvailable )
{
return;
}
// Handle messages
if( commandIn.Equals( "ligt" ) )
{
// 0 - 255
float percentValue = ( float )commandIn.m_arguments[1] / 100.0f; //0 - 255
int value = (int)( 255.0f * percentValue );
light.Write( value );
// LIGT - Light toggle
Serial.print( F( "LIGT:" ) );
Serial.print( value );
Serial.print( ';' );
// LIGP - Light percentage
Serial.print( F( "LIGP:" ) );
Serial.print( percentValue );
Serial.println( ';' );
}
}
#endif
<commit_msg>Updated 2x light code for new mapping feature<commit_after>#include "AConfig.h"
#if(HAS_STD_LIGHTS)
// Includes
#include <Arduino.h>
#include "CLights.h"
#include "CPin.h"
#include "NConfigManager.h"
#include "NModuleManager.h"
#include "NCommManager.h"
// One of these will have the correct pin defined for the lights
#if(HAS_STD_CAPE)
#include "CCape.h"
#endif
#if(HAS_OROV_CONTROLLERBOARD_25)
#include "CControllerBoard.h"
#endif
namespace
{
CPin light( "light", LIGHTS_PIN, CPin::kAnalog, CPin::kOutput );
}
void CLights::Initialize()
{
NConfigManager::m_capabilityBitmask |= ( 1 << LIGHTS_CAPABLE );
light.Reset();
light.Write( 0 );
}
void CLights::Update( CCommand& commandIn )
{
// Check for messages
if( !NCommManager::m_isCommandAvailable )
{
return;
}
// Handle messages
if( commandIn.Equals( "ligt" ) )
{
// Should be between 0-255, with 255 being full brightness
int value = commandIn.m_arguments[1];
// Bounds corrections
if( value < 0 )
{
value = 0;
}
if( value > 255 )
{
value = 255;
}
light.Write( value );
Serial.print( F( "LIGT:" ) );
Serial.print( value );
Serial.print( ';' );
}
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <time.h> // for nanosleep
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
using std::cin;
using std::cout;
using std::endl;
using std::ofstream;
using std::string;
#define MIN_GRAB_VALUE 0.82
/* Globals */
double g_leftmost_position = 0;
double g_rightmost_position = 0;
/// OSVR context
osvr::clientkit::ClientContext g_context("LagerCalibrator");
/// Pointer to the current tracker structures
osvr::clientkit::Interface g_left_tracker;
osvr::clientkit::Interface g_right_tracker;
/// Pointer to the current button structures
osvr::clientkit::Interface g_left_button;
osvr::clientkit::Interface g_right_button;
/// Pointer to the current grab structures
osvr::clientkit::Interface g_left_grab;
osvr::clientkit::Interface g_right_grab;
/// Boolean to determine whether we should save movement positions
bool save_positions = false;
/// Boolean to keep track of the button (or grab) release
bool button_released = false;
/**
* Prints a welcome banner for the LaGeR Calibrator.
*/
void PrintWelcomeBanner() {
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| LAGER CALIBRATOR |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
}
/**
* Prints the options menu for the LaGeR Calibrator.
*/
void PrintOptionsMenu() {
cout << "Please choose an option:" << endl;
cout << endl;
cout << "1. Calibrate sensor" << endl;
cout << endl;
cout << "2. Quit" << endl;
cout << endl;
cout << "Choice: ";
}
/**
* Callback that handles changes to the sensor positions.
*/
void HandleTrackerChange(void *user_data,
const OSVR_TimeValue *time_value,
const OSVR_PositionReport *cur_report) {
if (save_positions) {
double current_position = cur_report->xyz.data[0];
if (current_position < g_leftmost_position) {
g_leftmost_position = current_position;
} else if (current_position > g_rightmost_position) {
g_rightmost_position = current_position;
}
}
}
/**
* Callback that handles changes to a sensor button states.
*/
void HandleButtonChange(void *user_data, const OSVR_TimeValue *time_value,
const OSVR_ButtonReport *cur_report) {
bool previously_saved_positions = save_positions;
save_positions = cur_report->state ? true : false;
if (previously_saved_positions && !save_positions) {
button_released = true;
}
}
/**
* Callback that handles changes to a sensor grab state.
*/
void HandleGrabChange(void *user_data, const OSVR_TimeValue *time_value,
const OSVR_AnalogReport *cur_report) {
bool previously_saved_positions = save_positions;
save_positions = (cur_report->state > MIN_GRAB_VALUE) ? true : false;
if (previously_saved_positions && !save_positions) {
button_released = true;
}
}
void InitializeTrackers() {
// Initialize the tracker handlers
g_left_tracker = g_context.getInterface("/me/hands/left");
g_right_tracker = g_context.getInterface("/me/hands/right");
g_left_tracker.registerCallback(&HandleTrackerChange, NULL);
g_right_tracker.registerCallback(&HandleTrackerChange, NULL);
// Initialize the button and grab handlers
g_left_button = g_context.getInterface("/controller/left/1");
g_right_button = g_context.getInterface("/controller/right/1");
g_left_button.registerCallback(&HandleButtonChange, NULL);
g_right_button.registerCallback(&HandleButtonChange, NULL);
g_left_grab = g_context.getInterface("/controller/left/trigger");
g_right_grab = g_context.getInterface("/controller/right/trigger");
g_left_grab.registerCallback(&HandleGrabChange, NULL);
g_right_grab.registerCallback(&HandleGrabChange, NULL);
}
/**
* Writes the scale factor to a file to be used by liblager_convert
*/
void WriteScaleToFile(double scale) {
ofstream sensor_scale_file;
sensor_scale_file.open("/tmp/sensor_scale.cfg", std::ofstream::out | std::ofstream::trunc);
if (!sensor_scale_file.is_open()) {
cout << "Error writing to sensor scale file!" << endl;
return;
}
sensor_scale_file << scale << endl;
}
/**
* Calibrates a sensor by recording the leftmost and rightmost position values
* and saving a scaling factor accordingly.
*/
void CalibrateSensor() {
cout << "Move your sensor as far left as you will comfortably use it, then"
" hold its button (or grab it) while you move it as far right as you will"
" comfortably use it." << endl << std::flush;
InitializeTrackers();
struct timespec sleep_interval = { 0, 10000000 }; // 10 ms
while (true) {
// Request an update from the sensor context
g_context.update();
if (button_released) {
break;
}
// Sleep so we don't take up 100% of CPU
nanosleep(&sleep_interval, NULL);
}
cout << "Range: " << g_leftmost_position << " - " << g_rightmost_position << endl;
double scale = 0.001 * (g_rightmost_position - g_leftmost_position);
cout << "Scale: " << scale << endl;
WriteScaleToFile(scale);
}
/**
* The main loop of the LaGeR Calibrator.
*/
int main(int argc, const char *argv[]) {
string input;
std::string::size_type sz; // alias of size_t
bool quit = false;
PrintWelcomeBanner();
do{
PrintOptionsMenu();
getline(cin, input);
switch (atoi(input.c_str())) {
case 1:
cout << endl;
CalibrateSensor();
cout << endl;
break;
case 2:
quit = true;
break;
}
} while(!quit);
exit(0);
}
<commit_msg>Calibrator: Remove left grab detection<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <time.h> // for nanosleep
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
using std::cin;
using std::cout;
using std::endl;
using std::ofstream;
using std::string;
#define MIN_GRAB_VALUE 0.82
/* Globals */
double g_leftmost_position = 0;
double g_rightmost_position = 0;
/// OSVR context
osvr::clientkit::ClientContext g_context("LagerCalibrator");
/// Pointer to the current tracker structures
osvr::clientkit::Interface g_left_tracker;
osvr::clientkit::Interface g_right_tracker;
/// Pointer to the current button structures
osvr::clientkit::Interface g_left_button;
osvr::clientkit::Interface g_right_button;
/// Pointer to the current grab structures
osvr::clientkit::Interface g_left_grab;
osvr::clientkit::Interface g_right_grab;
/// Boolean to determine whether we should save movement positions
bool save_positions = false;
/// Boolean to keep track of the button (or grab) release
bool button_released = false;
/**
* Prints a welcome banner for the LaGeR Calibrator.
*/
void PrintWelcomeBanner() {
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| LAGER CALIBRATOR |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
}
/**
* Prints the options menu for the LaGeR Calibrator.
*/
void PrintOptionsMenu() {
cout << "Please choose an option:" << endl;
cout << endl;
cout << "1. Calibrate sensor" << endl;
cout << endl;
cout << "2. Quit" << endl;
cout << endl;
cout << "Choice: ";
}
/**
* Callback that handles changes to the sensor positions.
*/
void HandleTrackerChange(void *user_data,
const OSVR_TimeValue *time_value,
const OSVR_PositionReport *cur_report) {
if (save_positions) {
double current_position = cur_report->xyz.data[0];
if (current_position < g_leftmost_position) {
g_leftmost_position = current_position;
} else if (current_position > g_rightmost_position) {
g_rightmost_position = current_position;
}
}
}
/**
* Callback that handles changes to a sensor button states.
*/
void HandleButtonChange(void *user_data, const OSVR_TimeValue *time_value,
const OSVR_ButtonReport *cur_report) {
bool previously_saved_positions = save_positions;
save_positions = cur_report->state ? true : false;
if (previously_saved_positions && !save_positions) {
button_released = true;
}
}
/**
* Callback that handles changes to a sensor grab state.
*/
void HandleGrabChange(void *user_data, const OSVR_TimeValue *time_value,
const OSVR_AnalogReport *cur_report) {
bool previously_saved_positions = save_positions;
save_positions = (cur_report->state > MIN_GRAB_VALUE) ? true : false;
if (previously_saved_positions && !save_positions) {
button_released = true;
}
}
void InitializeTrackers() {
// Initialize the tracker handlers
g_left_tracker = g_context.getInterface("/me/hands/left");
g_right_tracker = g_context.getInterface("/me/hands/right");
g_left_tracker.registerCallback(&HandleTrackerChange, NULL);
g_right_tracker.registerCallback(&HandleTrackerChange, NULL);
// Initialize the button and grab handlers
g_left_button = g_context.getInterface("/controller/left/1");
g_right_button = g_context.getInterface("/controller/right/1");
g_left_button.registerCallback(&HandleButtonChange, NULL);
g_right_button.registerCallback(&HandleButtonChange, NULL);
//g_left_grab = g_context.getInterface("/controller/left/trigger");
g_right_grab = g_context.getInterface("/controller/right/trigger");
//g_left_grab.registerCallback(&HandleGrabChange, NULL);
g_right_grab.registerCallback(&HandleGrabChange, NULL);
}
/**
* Writes the scale factor to a file to be used by liblager_convert
*/
void WriteScaleToFile(double scale) {
ofstream sensor_scale_file;
sensor_scale_file.open("/tmp/sensor_scale.cfg", std::ofstream::out | std::ofstream::trunc);
if (!sensor_scale_file.is_open()) {
cout << "Error writing to sensor scale file!" << endl;
return;
}
sensor_scale_file << scale << endl;
}
/**
* Calibrates a sensor by recording the leftmost and rightmost position values
* and saving a scaling factor accordingly.
*/
void CalibrateSensor() {
cout << "Move your sensor as far left as you will comfortably use it, then"
" hold its button (or grab it) while you move it as far right as you will"
" comfortably use it." << endl << std::flush;
InitializeTrackers();
struct timespec sleep_interval = { 0, 10000000 }; // 10 ms
while (true) {
// Request an update from the sensor context
g_context.update();
if (button_released) {
break;
}
// Sleep so we don't take up 100% of CPU
nanosleep(&sleep_interval, NULL);
}
cout << "Range: " << g_leftmost_position << " - " << g_rightmost_position << endl;
double scale = 0.001 * (g_rightmost_position - g_leftmost_position);
cout << "Scale: " << scale << endl;
WriteScaleToFile(scale);
}
/**
* The main loop of the LaGeR Calibrator.
*/
int main(int argc, const char *argv[]) {
string input;
std::string::size_type sz; // alias of size_t
bool quit = false;
PrintWelcomeBanner();
do{
PrintOptionsMenu();
getline(cin, input);
switch (atoi(input.c_str())) {
case 1:
cout << endl;
CalibrateSensor();
cout << endl;
break;
case 2:
quit = true;
break;
}
} while(!quit);
exit(0);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, squirreldb. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <vector>
#include <iostream>
#include <string>
#include <sofa/pbrpc/pbrpc.h>
#include "src/proto/squirrel_rpc.pb.h"
int count = 0;
int failed = 0;
int thread_num = 4;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct PutArgs {
Squirrel::SquirrelServer_Stub* stub;
std::string key;
std::string value;
bool is_delete;
};
void PutCallback(sofa::pbrpc::RpcController* cntl,
Squirrel::PutRequest* request,
Squirrel::PutResponse* response) {
if (cntl->Failed()) {
//SLOG(ERROR, "rpc failed: %s", cntl->ErrorText().c_str());
pthread_mutex_lock(&mutex);
failed += 1;
pthread_mutex_unlock(&mutex);
} else {
pthread_mutex_lock(&mutex);
count += 1;
pthread_mutex_unlock(&mutex);
}
delete cntl;
delete request;
delete response;
}
void GetCallback(sofa::pbrpc::RpcController* cntl,
Squirrel::GetRequest* request,
Squirrel::GetResponse* response) {
if (cntl->Failed()) {
SLOG(ERROR, "rpc failed: %s", cntl->ErrorText().c_str());
}
if (response->status() == 0) {
SLOG(INFO, "value: %s", response->value().c_str());
} else {
pthread_mutex_lock(&mutex);
count += 1;
pthread_mutex_unlock(&mutex);
}
delete cntl;
delete request;
delete response;
}
void* Put(void* args) {
PutArgs* put_args = static_cast<PutArgs*>(args);
for (int i = 0; ; ++i) {
Squirrel::PutRequest* request = new Squirrel::PutRequest();
request->set_key(put_args->key);
request->set_value(put_args->value);
request->set_is_delete(put_args->is_delete);
Squirrel::PutResponse* response = new Squirrel::PutResponse();
sofa::pbrpc::RpcController* cntl = new sofa::pbrpc::RpcController();
cntl->SetTimeout(3000);
google::protobuf::Closure* done = sofa::pbrpc::NewClosure(&PutCallback, cntl, request, response);
put_args->stub->Put(cntl, request, response, done);
}
}
void Get(Squirrel::SquirrelServer_Stub* stub, std::string key) {
Squirrel::GetRequest* request = new Squirrel::GetRequest();
request->set_key(key);
Squirrel::GetResponse* response = new Squirrel::GetResponse();
sofa::pbrpc::RpcController* cntl = new sofa::pbrpc::RpcController();
cntl->SetTimeout(3000);
google::protobuf::Closure* done = sofa::pbrpc::NewClosure(&GetCallback, cntl, request, response);
stub->Get(cntl, request, response, done);
}
int main(int argc, char * argv[]) {
if (argc < 3) {
std::cout << "Invalid argument number: " << argc << std::endl;
return 1;
}
// rpc init
SOFA_PBRPC_SET_LOG_LEVEL(INFO);
sofa::pbrpc::RpcClientOptions options;
options.work_thread_num = 8;
options.callback_thread_num = 8;
options.max_pending_buffer_size = 4;
sofa::pbrpc::RpcClient rpc_client(options);
sofa::pbrpc::RpcChannel rpc_channel(&rpc_client, "st01-spi-session1.st01.baidu.com:11221");
Squirrel::SquirrelServer_Stub stub(&rpc_channel);
std::string op = argv[1];
std::string key = argv[2];
std::string value;
struct timeval tv_start;
gettimeofday(&tv_start, NULL);
std::vector<pthread_t> threads;
pthread_mutex_init(&mutex, NULL);
if (op == "put") {
value = argv[3];
std::cout << op << " : " << key << "--" << value << std::endl;
for (int i = 0; i < thread_num; ++i) {
pthread_t ntid;
PutArgs args;
args.stub = &stub;
args.key = key;
args.value = value;
args.is_delete = false;
int err = pthread_create(&ntid, NULL, Put, static_cast<void*>(&args));
if (err != 0) {
// SLOG(ERROR, "create thread failed: %s", strerror(err));
} else {
std::cout << "started thread #" << i << std::endl;
threads.push_back(ntid);
}
}
} else {
std::cout << op << " : " << key << std::endl;
Get(&stub, key);
}
while (true) {
pthread_mutex_lock(&mutex);
std::cout << "Qps=" << count << " failed=" << failed << std::endl;
count = 0;
failed = 0;
pthread_mutex_unlock(&mutex);
sleep(1);
}
for (int i = 0; i < thread_num; ++i) {
pthread_join(threads[i], NULL);
}
std::cout << "joined" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>mock pending buffer<commit_after>// Copyright (c) 2015, squirreldb. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <vector>
#include <iostream>
#include <string>
#include <sofa/pbrpc/pbrpc.h>
#include "src/proto/squirrel_rpc.pb.h"
int count = 0;
int failed = 0;
int thread_num = 4;
int pending = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct PutArgs {
Squirrel::SquirrelServer_Stub* stub;
std::string key;
std::string value;
bool is_delete;
};
void PutCallback(sofa::pbrpc::RpcController* cntl,
Squirrel::PutRequest* request,
Squirrel::PutResponse* response) {
if (cntl->Failed()) {
//SLOG(ERROR, "rpc failed: %s", cntl->ErrorText().c_str());
pthread_mutex_lock(&mutex);
failed += 1;
pthread_mutex_unlock(&mutex);
} else {
pthread_mutex_lock(&mutex);
count += 1;
pending -= 1;
pthread_mutex_unlock(&mutex);
}
delete cntl;
delete request;
delete response;
}
void GetCallback(sofa::pbrpc::RpcController* cntl,
Squirrel::GetRequest* request,
Squirrel::GetResponse* response) {
if (cntl->Failed()) {
SLOG(ERROR, "rpc failed: %s", cntl->ErrorText().c_str());
}
if (response->status() == 0) {
SLOG(INFO, "value: %s", response->value().c_str());
} else {
pthread_mutex_lock(&mutex);
count += 1;
pthread_mutex_unlock(&mutex);
}
delete cntl;
delete request;
delete response;
}
void* Put(void* args) {
PutArgs* put_args = static_cast<PutArgs*>(args);
while (true) {
pthread_mutex_lock(&mutex);
if (pending > 1000) {
usleep(1);
}
pthread_mutex_unlock(&mutex);
Squirrel::PutRequest* request = new Squirrel::PutRequest();
request->set_key(put_args->key);
request->set_value(put_args->value);
request->set_is_delete(put_args->is_delete);
Squirrel::PutResponse* response = new Squirrel::PutResponse();
sofa::pbrpc::RpcController* cntl = new sofa::pbrpc::RpcController();
cntl->SetTimeout(3000);
google::protobuf::Closure* done = sofa::pbrpc::NewClosure(&PutCallback, cntl, request, response);
put_args->stub->Put(cntl, request, response, done);
pending += 1;
}
}
void Get(Squirrel::SquirrelServer_Stub* stub, std::string key) {
Squirrel::GetRequest* request = new Squirrel::GetRequest();
request->set_key(key);
Squirrel::GetResponse* response = new Squirrel::GetResponse();
sofa::pbrpc::RpcController* cntl = new sofa::pbrpc::RpcController();
cntl->SetTimeout(3000);
google::protobuf::Closure* done = sofa::pbrpc::NewClosure(&GetCallback, cntl, request, response);
stub->Get(cntl, request, response, done);
}
int main(int argc, char * argv[]) {
if (argc < 3) {
std::cout << "Invalid argument number: " << argc << std::endl;
return 1;
}
// rpc init
SOFA_PBRPC_SET_LOG_LEVEL(INFO);
sofa::pbrpc::RpcClientOptions options;
options.work_thread_num = 8;
options.callback_thread_num = 8;
options.max_pending_buffer_size = 4;
sofa::pbrpc::RpcClient rpc_client(options);
sofa::pbrpc::RpcChannel rpc_channel(&rpc_client, "st01-spi-session1.st01.baidu.com:11221");
Squirrel::SquirrelServer_Stub stub(&rpc_channel);
std::string op = argv[1];
std::string key = argv[2];
std::string value;
struct timeval tv_start, tv_end;
gettimeofday(&tv_start, NULL);
std::vector<pthread_t> threads;
pthread_mutex_init(&mutex, NULL);
if (op == "put") {
value = argv[3];
std::cout << op << " : " << key << "--" << value << std::endl;
for (int i = 0; i < thread_num; ++i) {
pthread_t ntid;
PutArgs args;
args.stub = &stub;
args.key = key;
args.value = value;
args.is_delete = false;
int err = pthread_create(&ntid, NULL, Put, static_cast<void*>(&args));
if (err != 0) {
// SLOG(ERROR, "create thread failed: %s", strerror(err));
} else {
std::cout << "started thread #" << i << std::endl;
threads.push_back(ntid);
}
}
} else {
std::cout << op << " : " << key << std::endl;
Get(&stub, key);
}
while (true) {
gettimeofday(&tv_end, NULL);
long start = tv_start.tv_sec * 1000000 + tv_start.tv_usec;
long end = tv_end.tv_sec * 1000000 + tv_end.tv_usec;
double interval = (end - start) / double(1000000);
std::cout << "interval = " << interval << std::endl;
pthread_mutex_lock(&mutex);
std::cout << "Qps=" << double(count) / interval
<< "\tfailed=" << double(failed) / interval
<< "\tpending=" << double(pending) / interval
<< "\tinterval=" << interval << std::endl;
count = 0;
failed = 0;
pthread_mutex_unlock(&mutex);
tv_start = tv_end;
sleep(1);
}
for (int i = 0; i < thread_num; ++i) {
pthread_join(threads[i], NULL);
}
std::cout << "joined" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <Eigen/Dense>
#include "RRTPlanner.hpp"
#include "motion/TrapezoidalMotion.hpp"
#include <Constants.hpp>
#include <Utils.hpp>
using namespace std;
using namespace Planning;
Geometry2d::Point Planning::randomPoint()
{
float x = Field_Dimensions::Current_Dimensions.FloorWidth() * (drand48() - 0.5f);
float y = Field_Dimensions::Current_Dimensions.FloorLength() * drand48() - Field_Dimensions::Current_Dimensions.Border();
return Geometry2d::Point(x, y);
}
RRTPlanner::RRTPlanner()
{
_maxIterations = 100;
}
Planning::InterpolatedPath* RRTPlanner::run(
const Geometry2d::Point &start,
const float angle,
const Geometry2d::Point &vel,
const MotionConstraints &motionConstraints,
const Geometry2d::CompositeShape *obstacles)
{
Planning::InterpolatedPath *path = new Planning::InterpolatedPath();
Geometry2d::Point goal = *motionConstraints.targetPos;
_motionConstraints = motionConstraints;
vi = vel;
_obstacles = obstacles;
// Simple case: no path
if (start == goal)
{
path->points.push_back(start);
path->times.push_back(0);
path->vels.push_back(Geometry2d::Point(0,0));
return path;
}
/// Locate a non blocked goal point
Geometry2d::Point newGoal = goal;
if (obstacles && obstacles->hit(goal))
{
FixedStepTree goalTree;
goalTree.init(goal, obstacles);
goalTree.step = .1f;
// The starting point is in an obstacle
// extend the tree until we find an unobstructed point
for (int i= 0 ; i< 100 ; ++i)
{
Geometry2d::Point r = randomPoint();
//extend to a random point
Tree::Point* newPoint = goalTree.extend(r);
//if the new point is not blocked
//it becomes the new goal
if (newPoint && newPoint->hit.empty())
{
newGoal = newPoint->pos;
break;
}
}
/// see if the new goal is better than old one
/// must be at least a robot radius better else the move isn't worth it
const float oldDist = _bestGoal.distTo(goal);
const float newDist = newGoal.distTo(goal) + Robot_Radius;
if (newDist < oldDist || obstacles->hit(_bestGoal))
{
_bestGoal = newGoal;
}
}
else
{
_bestGoal = goal;
}
/// simple case of direct shot
/*
if (!obstacles->hit(Geometry2d::Segment(start, _bestGoal)))
{
path.points.push_back(start);
path.points.push_back(_bestGoal);
_bestPath = path;
return;
}
*/
_fixedStepTree0.init(start, obstacles);
_fixedStepTree1.init(_bestGoal, obstacles);
_fixedStepTree0.step = _fixedStepTree1.step = .15f;
/// run global position best path search
Tree* ta = &_fixedStepTree0;
Tree* tb = &_fixedStepTree1;
for (unsigned int i=0 ; i<_maxIterations; ++i)
{
Geometry2d::Point r = randomPoint();
Tree::Point* newPoint = ta->extend(r);
if (newPoint)
{
//try to connect the other tree to this point
if (tb->connect(newPoint->pos))
{
//trees connected
//done with global path finding
//the path is from start to goal
//makePath will handle the rest
break;
}
}
swap(ta, tb);
}
//see if we found a better global path
*path = makePath();
if (path->points.empty())
{
// FIXME: without these two lines, an empty path is returned which causes errors down the line.
path->points.push_back(start);
path->times.push_back(0);
path->vels.push_back(Geometry2d::Point(0,0));
}
return path;
}
Planning::InterpolatedPath update(
Planning::InterpolatedPath &origionalPath,
const float angle,
const Geometry2d::Point& vel,
const MotionConstraints &motionConstraints,
const Geometry2d::CompositeShape* obstacles)
{
return InterpolatedPath();
}
Planning::InterpolatedPath RRTPlanner::makePath()
{
Planning::InterpolatedPath newPath;
Tree::Point* p0 = _fixedStepTree0.last();
Tree::Point* p1 = _fixedStepTree1.last();
//sanity check
if (!p0 || !p1 || p0->pos != p1->pos)
{
return newPath;
}
// extract path from RRTs
_fixedStepTree0.addPath(newPath, p0);//add the start tree first...normal order (aka from root to p0)
_fixedStepTree1.addPath(newPath, p1, true);//add the goal tree in reverse (aka p1 to root)
optimize(newPath, _obstacles, _motionConstraints, vi);
//TODO evaluate the old path based on the closest segment
//and the distance to the endpoint of that segment
//Otherwise, a new path will always be shorter than the old given we traveled some
/// Conditions to use new path
/// 1. old path is empty
/// 2. goal changed
/// 3. start changed -- maybe (Roman)
/// 3. new path is better
/// 4. old path not valid (hits obstacles)
return newPath;
}
void RRTPlanner::optimize(Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi)
{
unsigned int start = 0;
if (path.empty())
{
// Nothing to do
return;
}
vector<Geometry2d::Point> pts;
pts.reserve(path.points.size());
// Copy all points that won't be optimized
vector<Geometry2d::Point>::const_iterator begin = path.points.begin();
pts.insert(pts.end(), begin, begin + start);
// The set of obstacles the starting point was inside of
std::set<shared_ptr<Geometry2d::Shape> > hit;
again:
obstacles->hit(path.points[start], hit);
pts.push_back(path.points[start]);
// [start, start + 1] is guaranteed not to have a collision because it's already in the path.
for (unsigned int end = start + 2; end < path.points.size(); ++end)
{
std::set<shared_ptr<Geometry2d::Shape> > newHit;
obstacles->hit(Geometry2d::Segment(path.points[start], path.points[end]), newHit);
try
{
set_difference(newHit.begin(), newHit.end(), hit.begin(), hit.end(), ExceptionIterator<std::shared_ptr<Geometry2d::Shape>>());
} catch (exception& e)
{
start = end - 1;
goto again;
}
}
// Done with the path
pts.push_back(path.points.back());
path.points = pts;
cubicBezier(path, obstacles, motionConstraints, vi);
}
Geometry2d::Point pow(Geometry2d::Point &p1, float i)
{
return Geometry2d::Point(pow(p1.x, i), pow(p1.y, i));
}
using namespace Eigen;
float getTime(Planning::InterpolatedPath &path, int index, const MotionConstraints &motionConstraints, float startSpeed, float endSpeed) {
return Trapezoidal::getTime(path.length(0,index), path.length(), motionConstraints.maxSpeed, motionConstraints.maxAcceleration, startSpeed, endSpeed);
}
//TODO: Use targeted end velocity
void RRTPlanner::cubicBezier (Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi)
{
int length = path.points.size();
int curvesNum = length-1;
if (curvesNum <= 0) {
//TODO
return;
}
//TODO: Get the actual values
Geometry2d::Point vf(0,0);
vector<double> pointsX(length);
vector<double> pointsY(length);
vector<double> ks(length-1);
vector<double> ks2(length-1);
for (int i=0; i<length; i++) {
pointsX[i] = path.points[i].x;
pointsY[i] = path.points[i].y;
}
float startSpeed = 0;
float endSpeed = motionConstraints.endSpeed;
for (int i=0; i<curvesNum; i++) {
ks[i] = 1.0/(getTime(path, i+1, motionConstraints, startSpeed, endSpeed)-getTime(path, i, motionConstraints, startSpeed, endSpeed));
ks2[i] = ks[i]*ks[i];
}
VectorXd solutionX = cubicBezierCalc(vi.x, vf.x, pointsX, ks, ks2);
VectorXd solutionY = cubicBezierCalc(vi.y, vf.y, pointsY, ks, ks2);
Geometry2d::Point p0, p1, p2, p3;
vector<Geometry2d::Point> pts;
vector<Geometry2d::Point> vels;
vector<float> times;
const int interpolations = 10;
double time=0;
for (int i=0; i<curvesNum; i++) // access by reference to avoid copying
{
p0 = path.points[i];
p3 = path.points[i+1];
p1 = Geometry2d::Point(solutionX(i*2),solutionY(i*2));
p2 = Geometry2d::Point(solutionX(i*2 + 1),solutionY(i*2 + 1));
for (int j=0; j<interpolations; j++)
{
double k = ks[i];
float t = (((float)j / (float)(interpolations)));
Geometry2d::Point temp = pow(1.0-t, 3) * p0 + 3.0* pow(1.0-t, 2)*t*p1 + 3*(1.0-t)*pow(t, 2)*p2
+ pow(t, 3)*p3;
pts.push_back(temp);
t = ((float)j / (float)(interpolations))/k;
//3 k (-(A (-1 + k t)^2) + k t (2 C - 3 C k t + D k t) + B (1 - 4 k t + 3 k^2 t^2))
temp = 3*k*(-(p0*pow(-1 + k*t ,2)) + k*t*(2*p2 - 3*p2*k*t + p3*k*t) + p1*(1 - 4*k*t + 3*pow(k,2)*pow(t,2)));
vels.push_back(temp);
times.push_back(time + t);
}
time+= 1.0/ks[i];
}
pts.push_back(path.points[length-1]);
vels.push_back(vf);
times.push_back(time);
path.points = pts;
path.vels = vels;
path.times = times;
}
VectorXd RRTPlanner::cubicBezierCalc (double vi, double vf, vector<double> &points,
vector<double> &ks, vector<double> &ks2)
{
int curvesNum = points.size() - 1;
if (curvesNum == 1)
{
VectorXd vector(2);
vector[0] = vi/(3.0*ks[0]) + points[0];
vector[1] = points[curvesNum] - vf/(3*ks[curvesNum-1]);
return vector;
}
else {
int matrixSize = curvesNum*2;
MatrixXd equations = MatrixXd::Zero(matrixSize, matrixSize);
VectorXd answer(matrixSize);
equations(0,0) = 1;
answer(0) = vi/(3.0*ks[0]) + points[0];
equations(1,matrixSize-1) = 1;
answer(1) = points[curvesNum] - vf/(3*ks[curvesNum-1]);
int i = 2;
for (int n=0; n<curvesNum-1; n++)
{
equations(i, n*2 + 1) = ks[n];
equations(i, n*2 + 2) = ks[n+1];
answer(i) = (ks[n] + ks[n+1]) * points[n + 1];
i++;
}
for (int n=0; n<curvesNum-1; n++)
{
equations(i, n*2) = ks2[n];
equations(i, n*2 + 1) = -2*ks2[n];
equations(i, n*2 + 2) = 2*ks2[n+1];
equations(i, n*2 + 3) = -ks2[n+1];
answer(i) = points[n + 1] * (ks2[n+1] - ks2[n]);
i++;
}
ColPivHouseholderQR<MatrixXd> solver(equations);
VectorXd solution = solver.solve(answer);
return solution;
}
}
<commit_msg>Remove unused update function<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <Eigen/Dense>
#include "RRTPlanner.hpp"
#include "motion/TrapezoidalMotion.hpp"
#include <Constants.hpp>
#include <Utils.hpp>
using namespace std;
using namespace Planning;
Geometry2d::Point Planning::randomPoint()
{
float x = Field_Dimensions::Current_Dimensions.FloorWidth() * (drand48() - 0.5f);
float y = Field_Dimensions::Current_Dimensions.FloorLength() * drand48() - Field_Dimensions::Current_Dimensions.Border();
return Geometry2d::Point(x, y);
}
RRTPlanner::RRTPlanner()
{
_maxIterations = 100;
}
Planning::InterpolatedPath* RRTPlanner::run(
const Geometry2d::Point &start,
const float angle,
const Geometry2d::Point &vel,
const MotionConstraints &motionConstraints,
const Geometry2d::CompositeShape *obstacles)
{
Planning::InterpolatedPath *path = new Planning::InterpolatedPath();
Geometry2d::Point goal = *motionConstraints.targetPos;
_motionConstraints = motionConstraints;
vi = vel;
_obstacles = obstacles;
// Simple case: no path
if (start == goal)
{
path->points.push_back(start);
path->times.push_back(0);
path->vels.push_back(Geometry2d::Point(0,0));
return path;
}
/// Locate a non blocked goal point
Geometry2d::Point newGoal = goal;
if (obstacles && obstacles->hit(goal))
{
FixedStepTree goalTree;
goalTree.init(goal, obstacles);
goalTree.step = .1f;
// The starting point is in an obstacle
// extend the tree until we find an unobstructed point
for (int i= 0 ; i< 100 ; ++i)
{
Geometry2d::Point r = randomPoint();
//extend to a random point
Tree::Point* newPoint = goalTree.extend(r);
//if the new point is not blocked
//it becomes the new goal
if (newPoint && newPoint->hit.empty())
{
newGoal = newPoint->pos;
break;
}
}
/// see if the new goal is better than old one
/// must be at least a robot radius better else the move isn't worth it
const float oldDist = _bestGoal.distTo(goal);
const float newDist = newGoal.distTo(goal) + Robot_Radius;
if (newDist < oldDist || obstacles->hit(_bestGoal))
{
_bestGoal = newGoal;
}
}
else
{
_bestGoal = goal;
}
/// simple case of direct shot
/*
if (!obstacles->hit(Geometry2d::Segment(start, _bestGoal)))
{
path.points.push_back(start);
path.points.push_back(_bestGoal);
_bestPath = path;
return;
}
*/
_fixedStepTree0.init(start, obstacles);
_fixedStepTree1.init(_bestGoal, obstacles);
_fixedStepTree0.step = _fixedStepTree1.step = .15f;
/// run global position best path search
Tree* ta = &_fixedStepTree0;
Tree* tb = &_fixedStepTree1;
for (unsigned int i=0 ; i<_maxIterations; ++i)
{
Geometry2d::Point r = randomPoint();
Tree::Point* newPoint = ta->extend(r);
if (newPoint)
{
//try to connect the other tree to this point
if (tb->connect(newPoint->pos))
{
//trees connected
//done with global path finding
//the path is from start to goal
//makePath will handle the rest
break;
}
}
swap(ta, tb);
}
//see if we found a better global path
*path = makePath();
if (path->points.empty())
{
// FIXME: without these two lines, an empty path is returned which causes errors down the line.
path->points.push_back(start);
path->times.push_back(0);
path->vels.push_back(Geometry2d::Point(0,0));
}
return path;
}
Planning::InterpolatedPath RRTPlanner::makePath()
{
Planning::InterpolatedPath newPath;
Tree::Point* p0 = _fixedStepTree0.last();
Tree::Point* p1 = _fixedStepTree1.last();
//sanity check
if (!p0 || !p1 || p0->pos != p1->pos)
{
return newPath;
}
// extract path from RRTs
_fixedStepTree0.addPath(newPath, p0);//add the start tree first...normal order (aka from root to p0)
_fixedStepTree1.addPath(newPath, p1, true);//add the goal tree in reverse (aka p1 to root)
optimize(newPath, _obstacles, _motionConstraints, vi);
//TODO evaluate the old path based on the closest segment
//and the distance to the endpoint of that segment
//Otherwise, a new path will always be shorter than the old given we traveled some
/// Conditions to use new path
/// 1. old path is empty
/// 2. goal changed
/// 3. start changed -- maybe (Roman)
/// 3. new path is better
/// 4. old path not valid (hits obstacles)
return newPath;
}
void RRTPlanner::optimize(Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi)
{
unsigned int start = 0;
if (path.empty())
{
// Nothing to do
return;
}
vector<Geometry2d::Point> pts;
pts.reserve(path.points.size());
// Copy all points that won't be optimized
vector<Geometry2d::Point>::const_iterator begin = path.points.begin();
pts.insert(pts.end(), begin, begin + start);
// The set of obstacles the starting point was inside of
std::set<shared_ptr<Geometry2d::Shape> > hit;
again:
obstacles->hit(path.points[start], hit);
pts.push_back(path.points[start]);
// [start, start + 1] is guaranteed not to have a collision because it's already in the path.
for (unsigned int end = start + 2; end < path.points.size(); ++end)
{
std::set<shared_ptr<Geometry2d::Shape> > newHit;
obstacles->hit(Geometry2d::Segment(path.points[start], path.points[end]), newHit);
try
{
set_difference(newHit.begin(), newHit.end(), hit.begin(), hit.end(), ExceptionIterator<std::shared_ptr<Geometry2d::Shape>>());
} catch (exception& e)
{
start = end - 1;
goto again;
}
}
// Done with the path
pts.push_back(path.points.back());
path.points = pts;
cubicBezier(path, obstacles, motionConstraints, vi);
}
Geometry2d::Point pow(Geometry2d::Point &p1, float i)
{
return Geometry2d::Point(pow(p1.x, i), pow(p1.y, i));
}
using namespace Eigen;
float getTime(Planning::InterpolatedPath &path, int index, const MotionConstraints &motionConstraints, float startSpeed, float endSpeed) {
return Trapezoidal::getTime(path.length(0,index), path.length(), motionConstraints.maxSpeed, motionConstraints.maxAcceleration, startSpeed, endSpeed);
}
//TODO: Use targeted end velocity
void RRTPlanner::cubicBezier (Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi)
{
int length = path.points.size();
int curvesNum = length-1;
if (curvesNum <= 0) {
//TODO
return;
}
//TODO: Get the actual values
Geometry2d::Point vf(0,0);
vector<double> pointsX(length);
vector<double> pointsY(length);
vector<double> ks(length-1);
vector<double> ks2(length-1);
for (int i=0; i<length; i++) {
pointsX[i] = path.points[i].x;
pointsY[i] = path.points[i].y;
}
float startSpeed = 0;
float endSpeed = motionConstraints.endSpeed;
for (int i=0; i<curvesNum; i++) {
ks[i] = 1.0/(getTime(path, i+1, motionConstraints, startSpeed, endSpeed)-getTime(path, i, motionConstraints, startSpeed, endSpeed));
ks2[i] = ks[i]*ks[i];
}
VectorXd solutionX = cubicBezierCalc(vi.x, vf.x, pointsX, ks, ks2);
VectorXd solutionY = cubicBezierCalc(vi.y, vf.y, pointsY, ks, ks2);
Geometry2d::Point p0, p1, p2, p3;
vector<Geometry2d::Point> pts;
vector<Geometry2d::Point> vels;
vector<float> times;
const int interpolations = 10;
double time=0;
for (int i=0; i<curvesNum; i++) // access by reference to avoid copying
{
p0 = path.points[i];
p3 = path.points[i+1];
p1 = Geometry2d::Point(solutionX(i*2),solutionY(i*2));
p2 = Geometry2d::Point(solutionX(i*2 + 1),solutionY(i*2 + 1));
for (int j=0; j<interpolations; j++)
{
double k = ks[i];
float t = (((float)j / (float)(interpolations)));
Geometry2d::Point temp = pow(1.0-t, 3) * p0 + 3.0* pow(1.0-t, 2)*t*p1 + 3*(1.0-t)*pow(t, 2)*p2
+ pow(t, 3)*p3;
pts.push_back(temp);
t = ((float)j / (float)(interpolations))/k;
//3 k (-(A (-1 + k t)^2) + k t (2 C - 3 C k t + D k t) + B (1 - 4 k t + 3 k^2 t^2))
temp = 3*k*(-(p0*pow(-1 + k*t ,2)) + k*t*(2*p2 - 3*p2*k*t + p3*k*t) + p1*(1 - 4*k*t + 3*pow(k,2)*pow(t,2)));
vels.push_back(temp);
times.push_back(time + t);
}
time+= 1.0/ks[i];
}
pts.push_back(path.points[length-1]);
vels.push_back(vf);
times.push_back(time);
path.points = pts;
path.vels = vels;
path.times = times;
}
VectorXd RRTPlanner::cubicBezierCalc (double vi, double vf, vector<double> &points,
vector<double> &ks, vector<double> &ks2)
{
int curvesNum = points.size() - 1;
if (curvesNum == 1)
{
VectorXd vector(2);
vector[0] = vi/(3.0*ks[0]) + points[0];
vector[1] = points[curvesNum] - vf/(3*ks[curvesNum-1]);
return vector;
}
else {
int matrixSize = curvesNum*2;
MatrixXd equations = MatrixXd::Zero(matrixSize, matrixSize);
VectorXd answer(matrixSize);
equations(0,0) = 1;
answer(0) = vi/(3.0*ks[0]) + points[0];
equations(1,matrixSize-1) = 1;
answer(1) = points[curvesNum] - vf/(3*ks[curvesNum-1]);
int i = 2;
for (int n=0; n<curvesNum-1; n++)
{
equations(i, n*2 + 1) = ks[n];
equations(i, n*2 + 2) = ks[n+1];
answer(i) = (ks[n] + ks[n+1]) * points[n + 1];
i++;
}
for (int n=0; n<curvesNum-1; n++)
{
equations(i, n*2) = ks2[n];
equations(i, n*2 + 1) = -2*ks2[n];
equations(i, n*2 + 2) = 2*ks2[n+1];
equations(i, n*2 + 3) = -ks2[n+1];
answer(i) = points[n + 1] * (ks2[n+1] - ks2[n]);
i++;
}
ColPivHouseholderQR<MatrixXd> solver(equations);
VectorXd solution = solver.solve(answer);
return solution;
}
}
<|endoftext|> |
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Miodrag Milanovic <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "jsonwrite.h"
#include <assert.h>
#include <fstream>
#include <iostream>
#include <iterator>
#include <log.h>
#include <map>
#include <string>
#include "nextpnr.h"
#include "version.h"
NEXTPNR_NAMESPACE_BEGIN
namespace JsonWriter {
std::string get_string(std::string str)
{
std::string newstr = "\"";
for (char c : str) {
if (c == '\\')
newstr += c;
newstr += c;
}
return newstr + "\"";
}
std::string get_name(IdString name, Context *ctx) { return get_string(name.c_str(ctx)); }
void write_parameter_value(std::ostream &f, const Property &value)
{
if (value.size() == 32 && value.is_fully_def()) {
f << stringf("%d", value.as_int64());
} else {
f << get_string(value.to_string());
}
}
void write_parameters(std::ostream &f, Context *ctx, const std::unordered_map<IdString, Property> ¶meters,
bool for_module = false)
{
bool first = true;
for (auto ¶m : parameters) {
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first, ctx).c_str());
write_parameter_value(f, param.second);
first = false;
}
}
void write_module(std::ostream &f, Context *ctx)
{
auto val = ctx->attrs.find(ctx->id("module"));
if (val != ctx->attrs.end())
f << stringf(" %s: {\n", get_string(val->second.as_string()).c_str());
else
f << stringf(" %s: {\n", get_string("top").c_str());
f << stringf(" \"settings\": {");
write_parameters(f, ctx, ctx->settings, true);
f << stringf("\n },\n");
f << stringf(" \"attributes\": {");
write_parameters(f, ctx, ctx->attrs, true);
f << stringf("\n },\n");
f << stringf(" \"ports\": {");
bool first = true;
for (auto &pair : ctx->ports) {
auto &c = pair.second;
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s: {\n", get_name(c.name, ctx).c_str());
f << stringf(" \"direction\": \"%s\",\n",
c.type == PORT_IN ? "input" : c.type == PORT_INOUT ? "inout" : "output");
f << stringf(" \"bits\": [ %d ]\n", pair.first.index);
f << stringf(" }");
first = false;
}
f << stringf("\n },\n");
f << stringf(" \"cells\": {");
first = true;
for (auto &pair : ctx->cells) {
auto &c = pair.second;
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s: {\n", get_name(c->name, ctx).c_str());
f << stringf(" \"hide_name\": %s,\n", c->name.c_str(ctx)[0] == '$' ? "1" : "0");
f << stringf(" \"type\": %s,\n", get_name(c->type, ctx).c_str());
f << stringf(" \"parameters\": {");
write_parameters(f, ctx, c->params);
f << stringf("\n },\n");
f << stringf(" \"attributes\": {");
write_parameters(f, ctx, c->attrs);
f << stringf("\n },\n");
f << stringf(" \"port_directions\": {");
bool first2 = true;
for (auto &conn : c->ports) {
auto &p = conn.second;
std::string direction = (p.type == PORT_IN) ? "input" : (p.type == PORT_OUT) ? "output" : "inout";
f << stringf("%s\n", first2 ? "" : ",");
f << stringf(" %s: \"%s\"", get_name(conn.first, ctx).c_str(), direction.c_str());
first2 = false;
}
f << stringf("\n },\n");
f << stringf(" \"connections\": {");
first2 = true;
for (auto &conn : c->ports) {
auto &p = conn.second;
f << stringf("%s\n", first2 ? "" : ",");
if (p.net)
f << stringf(" %s: [ %d ]", get_name(conn.first, ctx).c_str(), p.net->name.index);
else
f << stringf(" %s: [ ]", get_name(conn.first, ctx).c_str());
first2 = false;
}
f << stringf("\n }\n");
f << stringf(" }");
first = false;
}
f << stringf("\n },\n");
f << stringf(" \"netnames\": {");
first = true;
for (auto &pair : ctx->nets) {
auto &w = pair.second;
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s: {\n", get_name(w->name, ctx).c_str());
f << stringf(" \"hide_name\": %s,\n", w->name.c_str(ctx)[0] == '$' ? "1" : "0");
f << stringf(" \"bits\": [ %d ] ,\n", pair.first.index);
f << stringf(" \"attributes\": {");
write_parameters(f, ctx, w->attrs);
f << stringf("\n }\n");
f << stringf(" }");
first = false;
}
f << stringf("\n }\n");
f << stringf(" }");
}
void write_context(std::ostream &f, Context *ctx)
{
f << stringf("{\n");
f << stringf(" \"creator\": %s,\n",
get_string("Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")").c_str());
f << stringf(" \"modules\": {\n");
write_module(f, ctx);
f << stringf("\n }");
f << stringf("\n}\n");
}
}; // End Namespace JsonWriter
bool write_json_file(std::ostream &f, std::string &filename, Context *ctx)
{
try {
using namespace JsonWriter;
if (!f)
log_error("failed to open JSON file.\n");
write_context(f, ctx);
log_break();
return true;
} catch (log_execution_error_exception) {
return false;
}
}
NEXTPNR_NAMESPACE_END
<commit_msg>json: Group bus ports in backend<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Miodrag Milanovic <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "jsonwrite.h"
#include <assert.h>
#include <fstream>
#include <iostream>
#include <iterator>
#include <log.h>
#include <map>
#include <string>
#include "nextpnr.h"
#include "version.h"
NEXTPNR_NAMESPACE_BEGIN
namespace JsonWriter {
std::string get_string(std::string str)
{
std::string newstr = "\"";
for (char c : str) {
if (c == '\\')
newstr += c;
newstr += c;
}
return newstr + "\"";
}
std::string get_name(IdString name, Context *ctx) { return get_string(name.c_str(ctx)); }
void write_parameter_value(std::ostream &f, const Property &value)
{
if (value.size() == 32 && value.is_fully_def()) {
f << stringf("%d", value.as_int64());
} else {
f << get_string(value.to_string());
}
}
void write_parameters(std::ostream &f, Context *ctx, const std::unordered_map<IdString, Property> ¶meters,
bool for_module = false)
{
bool first = true;
for (auto ¶m : parameters) {
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first, ctx).c_str());
write_parameter_value(f, param.second);
first = false;
}
}
struct PortGroup
{
std::string name;
std::vector<int> bits;
PortType dir;
};
std::vector<PortGroup> group_ports(Context *ctx)
{
std::vector<PortGroup> groups;
std::unordered_map<std::string, size_t> base_to_group;
for (auto &pair : ctx->ports) {
std::string name = pair.second.name.str(ctx);
if ((name.back() != ']') || (name.find('[') == std::string::npos)) {
groups.push_back({name, {pair.first.index}, pair.second.type});
} else {
int off1 = int(name.find_last_of('['));
std::string basename = name.substr(0, off1);
int index = std::stoi(name.substr(off1 + 1, name.size() - (off1 + 2)));
if (!base_to_group.count(basename)) {
base_to_group[basename] = groups.size();
groups.push_back({basename, std::vector<int>(index + 1, -1), pair.second.type});
}
auto &grp = groups.at(base_to_group[basename]);
if (int(grp.bits.size()) <= index)
grp.bits.resize(index + 1, -1);
NPNR_ASSERT(grp.bits.at(index) == -1);
grp.bits.at(index) = pair.first.index;
}
}
return groups;
};
std::string format_port_bits(const PortGroup &port)
{
std::stringstream s;
s << "[ ";
bool first = true;
for (auto bit : port.bits) {
if (!first)
s << ", ";
if (bit == -1)
s << "\"x\"";
else
s << bit;
first = false;
}
s << " ]";
return s.str();
}
void write_module(std::ostream &f, Context *ctx)
{
auto val = ctx->attrs.find(ctx->id("module"));
if (val != ctx->attrs.end())
f << stringf(" %s: {\n", get_string(val->second.as_string()).c_str());
else
f << stringf(" %s: {\n", get_string("top").c_str());
f << stringf(" \"settings\": {");
write_parameters(f, ctx, ctx->settings, true);
f << stringf("\n },\n");
f << stringf(" \"attributes\": {");
write_parameters(f, ctx, ctx->attrs, true);
f << stringf("\n },\n");
f << stringf(" \"ports\": {");
auto ports = group_ports(ctx);
bool first = true;
for (auto &port : ports) {
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s: {\n", get_string(port.name).c_str());
f << stringf(" \"direction\": \"%s\",\n",
port.dir == PORT_IN ? "input" : port.dir == PORT_INOUT ? "inout" : "output");
f << stringf(" \"bits\": %s\n", format_port_bits(port).c_str());
f << stringf(" }");
first = false;
}
f << stringf("\n },\n");
f << stringf(" \"cells\": {");
first = true;
for (auto &pair : ctx->cells) {
auto &c = pair.second;
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s: {\n", get_name(c->name, ctx).c_str());
f << stringf(" \"hide_name\": %s,\n", c->name.c_str(ctx)[0] == '$' ? "1" : "0");
f << stringf(" \"type\": %s,\n", get_name(c->type, ctx).c_str());
f << stringf(" \"parameters\": {");
write_parameters(f, ctx, c->params);
f << stringf("\n },\n");
f << stringf(" \"attributes\": {");
write_parameters(f, ctx, c->attrs);
f << stringf("\n },\n");
f << stringf(" \"port_directions\": {");
bool first2 = true;
for (auto &conn : c->ports) {
auto &p = conn.second;
std::string direction = (p.type == PORT_IN) ? "input" : (p.type == PORT_OUT) ? "output" : "inout";
f << stringf("%s\n", first2 ? "" : ",");
f << stringf(" %s: \"%s\"", get_name(conn.first, ctx).c_str(), direction.c_str());
first2 = false;
}
f << stringf("\n },\n");
f << stringf(" \"connections\": {");
first2 = true;
for (auto &conn : c->ports) {
auto &p = conn.second;
f << stringf("%s\n", first2 ? "" : ",");
if (p.net)
f << stringf(" %s: [ %d ]", get_name(conn.first, ctx).c_str(), p.net->name.index);
else
f << stringf(" %s: [ ]", get_name(conn.first, ctx).c_str());
first2 = false;
}
f << stringf("\n }\n");
f << stringf(" }");
first = false;
}
f << stringf("\n },\n");
f << stringf(" \"netnames\": {");
first = true;
for (auto &pair : ctx->nets) {
auto &w = pair.second;
f << stringf("%s\n", first ? "" : ",");
f << stringf(" %s: {\n", get_name(w->name, ctx).c_str());
f << stringf(" \"hide_name\": %s,\n", w->name.c_str(ctx)[0] == '$' ? "1" : "0");
f << stringf(" \"bits\": [ %d ] ,\n", pair.first.index);
f << stringf(" \"attributes\": {");
write_parameters(f, ctx, w->attrs);
f << stringf("\n }\n");
f << stringf(" }");
first = false;
}
f << stringf("\n }\n");
f << stringf(" }");
}
void write_context(std::ostream &f, Context *ctx)
{
f << stringf("{\n");
f << stringf(" \"creator\": %s,\n",
get_string("Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")").c_str());
f << stringf(" \"modules\": {\n");
write_module(f, ctx);
f << stringf("\n }");
f << stringf("\n}\n");
}
}; // End Namespace JsonWriter
bool write_json_file(std::ostream &f, std::string &filename, Context *ctx)
{
try {
using namespace JsonWriter;
if (!f)
log_error("failed to open JSON file.\n");
write_context(f, ctx);
log_break();
return true;
} catch (log_execution_error_exception) {
return false;
}
}
NEXTPNR_NAMESPACE_END
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <unistd.h>
#include <stx/exception.h>
#include <stx/uri.h>
#include <stx/protobuf/msg.h>
#include <stx/csv/CSVInputStream.h>
#include <common/ConfigDirectory.h>
using namespace stx;
namespace cm {
ConfigDirectory::ConfigDirectory(
const String& path,
const InetAddr master_addr) :
master_addr_(master_addr),
watcher_running_(false) {
mdb::MDBOptions mdb_opts;
mdb_opts.data_filename = "cdb.db",
mdb_opts.lock_filename = "cdb.db.lck";
mdb_opts.duplicate_keys = false;
db_ = mdb::MDB::open(path, mdb_opts);
listCustomers([this] (const CustomerConfig& cfg) {
customers_.emplace(cfg.customer(), new CustomerConfigRef(cfg));
});
sync();
}
RefPtr<CustomerConfigRef> ConfigDirectory::configFor(
const String& customer_key) const {
std::unique_lock<std::mutex> lk(mutex_);
auto iter = customers_.find(customer_key);
if (iter == customers_.end()) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
return iter->second;
}
void ConfigDirectory::listCustomers(
Function<void (const CustomerConfig& cfg)> fn) const {
auto prefix = "cfg~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<CustomerConfig>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onCustomerConfigChange(
Function<void (const CustomerConfig& cfg)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_customer_change_.emplace_back(fn);
}
void ConfigDirectory::updateTableDefinition(const TableDefinition& table) {
if (!StringUtil::isShellSafe(table.table_name())) {
RAISEF(
kIllegalArgumentError,
"invalid table name: '$0'",
table.table_name());
}
if (!table.has_schema_name() && !table.has_schema_inline()) {
RAISEF(
kIllegalArgumentError,
"can't update table without a schema: '$0'",
table.table_name());
}
auto buf = msg::encode(table);
RAISE(kNotYetImplementedError);
}
void ConfigDirectory::listTableDefinitions(
Function<void (const TableDefinition& table)> fn) const {
auto prefix = "tbl~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<TableDefinition>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onTableDefinitionChange(
Function<void (const TableDefinition& tbl)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_table_change_.emplace_back(fn);
}
void ConfigDirectory::sync() {
auto master_heads = fetchMasterHeads();
Set<String> needs_update;
{
auto txn = db_->startTransaction(true);
txn->autoAbort();
for (const auto& head : master_heads) {
auto db_key = StringUtil::format("head~$0", head.first);
auto vstr = StringUtil::toString(head.second);
auto lastver = txn->get(db_key);
if (lastver.isEmpty() || lastver.get().toString() != vstr) {
needs_update.emplace(head.first);
}
}
txn->abort();
}
for (const auto& obj : needs_update) {
syncObject(obj);
}
}
void ConfigDirectory::syncObject(const String& obj) {
logDebug("analyticsd", "Syncing config object '$0' from master", obj);
static const String kCustomerPrefix = "customers/";
if (StringUtil::beginsWith(obj, kCustomerPrefix)) {
syncCustomerConfig(obj.substr(kCustomerPrefix.size()));
}
static const String kTablesPrefix = "tables/";
if (StringUtil::beginsWith(obj, kTablesPrefix)) {
syncTableDefinitions(obj.substr(kTablesPrefix.size()));
}
}
void ConfigDirectory::syncCustomerConfig(const String& customer) {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/fetch_customer_config?customer=$1",
master_addr_.hostAndPort(),
URI::urlEncode(customer)));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
commitCustomerConfig(msg::decode<CustomerConfig>(res.body()));
}
void ConfigDirectory::commitCustomerConfig(const CustomerConfig& config) {
auto db_key = StringUtil::format("cfg~$0", config.customer());
auto hkey = StringUtil::format("head~customers/$0", config.customer());
auto buf = msg::encode(config);
auto vstr = StringUtil::toString(config.version());
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
auto last_version = 0;
auto last_version_str = txn->get(hkey);
if (!last_version_str.isEmpty()) {
last_version = std::stoull(last_version_str.get().toString());
}
if (last_version >= config.version()) {
logDebug("cdb", "refusing to commit outdated version");
return;
}
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->update(hkey.data(), hkey.size(), vstr.data(), vstr.size());
txn->commit();
customers_.emplace(config.customer(), new CustomerConfigRef(config));
for (const auto& cb : on_customer_change_) {
cb(config);
}
}
void ConfigDirectory::syncTableDefinitions(const String& customer) {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/fetch_table_definitions?customer=$1",
master_addr_.hostAndPort(),
URI::urlEncode(customer)));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
auto tables = msg::decode<TableDefinitionList>(res.body());
for (const auto& tbl : tables.tables()) {
commitTableDefinition(tbl);
}
auto hkey = StringUtil::format("head~tables/$0", customer);
auto vstr = StringUtil::toString(tables.version());
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->update(hkey.data(), hkey.size(), vstr.data(), vstr.size());
txn->commit();
}
void ConfigDirectory::commitTableDefinition(const TableDefinition& tbl) {
auto db_key = StringUtil::format(
"tbl~$0~$1",
tbl.customer(),
tbl.table_name());
auto buf = msg::encode(tbl);
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
auto last_version = 0;
auto last_td = txn->get(db_key);
if (!last_td.isEmpty()) {
last_version = msg::decode<TableDefinition>(last_td.get()).version();
}
if (last_version >= tbl.version()) {
logDebug("cdb", "refusing to commit outdated version");
return;
}
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->commit();
for (const auto& cb : on_table_change_) {
cb(tbl);
}
}
HashMap<String, uint64_t> ConfigDirectory::fetchMasterHeads() const {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/heads",
master_addr_.hostAndPort()));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
DefaultCSVInputStream csv(BufferInputStream::fromBuffer(&res.body()), '=');
HashMap<String, uint64_t> heads;
Vector<String> row;
while (csv.readNextRow(&row)) {
if (row.size() != 2) {
RAISE(kRuntimeError, "invalid response");
}
heads[row[0]] = std::stoull(row[1]);
}
return heads;
}
void ConfigDirectory::startWatcher() {
watcher_running_ = true;
watcher_thread_ = std::thread([this] {
while (watcher_running_.load()) {
try {
sync();
} catch (const StandardException& e) {
logCritical("analyticsd", e, "error during master sync");
}
usleep(500000);
}
});
}
void ConfigDirectory::stopWatcher() {
if (!watcher_running_) {
return;
}
watcher_running_ = false;
watcher_thread_.join();
}
} // namespace cm
<commit_msg>ConfigDirectory::updateTableDefinition impl<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <unistd.h>
#include <stx/exception.h>
#include <stx/uri.h>
#include <stx/protobuf/msg.h>
#include <stx/csv/CSVInputStream.h>
#include <common/ConfigDirectory.h>
using namespace stx;
namespace cm {
ConfigDirectory::ConfigDirectory(
const String& path,
const InetAddr master_addr) :
master_addr_(master_addr),
watcher_running_(false) {
mdb::MDBOptions mdb_opts;
mdb_opts.data_filename = "cdb.db",
mdb_opts.lock_filename = "cdb.db.lck";
mdb_opts.duplicate_keys = false;
db_ = mdb::MDB::open(path, mdb_opts);
listCustomers([this] (const CustomerConfig& cfg) {
customers_.emplace(cfg.customer(), new CustomerConfigRef(cfg));
});
sync();
}
RefPtr<CustomerConfigRef> ConfigDirectory::configFor(
const String& customer_key) const {
std::unique_lock<std::mutex> lk(mutex_);
auto iter = customers_.find(customer_key);
if (iter == customers_.end()) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
return iter->second;
}
void ConfigDirectory::listCustomers(
Function<void (const CustomerConfig& cfg)> fn) const {
auto prefix = "cfg~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<CustomerConfig>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onCustomerConfigChange(
Function<void (const CustomerConfig& cfg)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_customer_change_.emplace_back(fn);
}
void ConfigDirectory::updateTableDefinition(const TableDefinition& table) {
if (!StringUtil::isShellSafe(table.table_name())) {
RAISEF(
kIllegalArgumentError,
"invalid table name: '$0'",
table.table_name());
}
if (!table.has_schema_name() && !table.has_schema_inline()) {
RAISEF(
kIllegalArgumentError,
"can't update table without a schema: '$0'",
table.table_name());
}
auto body = msg::encode(table);
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/update_table_definition",
master_addr_.hostAndPort()));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkPost(uri, *body));
if (res.statusCode() != 201) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
commitTableDefinition(msg::decode<TableDefinition>(res.body()));
}
void ConfigDirectory::listTableDefinitions(
Function<void (const TableDefinition& table)> fn) const {
auto prefix = "tbl~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<TableDefinition>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onTableDefinitionChange(
Function<void (const TableDefinition& tbl)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_table_change_.emplace_back(fn);
}
void ConfigDirectory::sync() {
auto master_heads = fetchMasterHeads();
Set<String> needs_update;
{
auto txn = db_->startTransaction(true);
txn->autoAbort();
for (const auto& head : master_heads) {
auto db_key = StringUtil::format("head~$0", head.first);
auto vstr = StringUtil::toString(head.second);
auto lastver = txn->get(db_key);
if (lastver.isEmpty() || lastver.get().toString() != vstr) {
needs_update.emplace(head.first);
}
}
txn->abort();
}
for (const auto& obj : needs_update) {
syncObject(obj);
}
}
void ConfigDirectory::syncObject(const String& obj) {
logDebug("analyticsd", "Syncing config object '$0' from master", obj);
static const String kCustomerPrefix = "customers/";
if (StringUtil::beginsWith(obj, kCustomerPrefix)) {
syncCustomerConfig(obj.substr(kCustomerPrefix.size()));
}
static const String kTablesPrefix = "tables/";
if (StringUtil::beginsWith(obj, kTablesPrefix)) {
syncTableDefinitions(obj.substr(kTablesPrefix.size()));
}
}
void ConfigDirectory::syncCustomerConfig(const String& customer) {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/fetch_customer_config?customer=$1",
master_addr_.hostAndPort(),
URI::urlEncode(customer)));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
commitCustomerConfig(msg::decode<CustomerConfig>(res.body()));
}
void ConfigDirectory::commitCustomerConfig(const CustomerConfig& config) {
auto db_key = StringUtil::format("cfg~$0", config.customer());
auto hkey = StringUtil::format("head~customers/$0", config.customer());
auto buf = msg::encode(config);
auto vstr = StringUtil::toString(config.version());
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
auto last_version = 0;
auto last_version_str = txn->get(hkey);
if (!last_version_str.isEmpty()) {
last_version = std::stoull(last_version_str.get().toString());
}
if (last_version >= config.version()) {
logDebug("cdb", "refusing to commit outdated version");
return;
}
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->update(hkey.data(), hkey.size(), vstr.data(), vstr.size());
txn->commit();
customers_.emplace(config.customer(), new CustomerConfigRef(config));
for (const auto& cb : on_customer_change_) {
cb(config);
}
}
void ConfigDirectory::syncTableDefinitions(const String& customer) {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/fetch_table_definitions?customer=$1",
master_addr_.hostAndPort(),
URI::urlEncode(customer)));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
auto tables = msg::decode<TableDefinitionList>(res.body());
for (const auto& tbl : tables.tables()) {
commitTableDefinition(tbl);
}
auto hkey = StringUtil::format("head~tables/$0", customer);
auto vstr = StringUtil::toString(tables.version());
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->update(hkey.data(), hkey.size(), vstr.data(), vstr.size());
txn->commit();
}
void ConfigDirectory::commitTableDefinition(const TableDefinition& tbl) {
auto db_key = StringUtil::format(
"tbl~$0~$1",
tbl.customer(),
tbl.table_name());
auto buf = msg::encode(tbl);
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
auto last_version = 0;
auto last_td = txn->get(db_key);
if (!last_td.isEmpty()) {
last_version = msg::decode<TableDefinition>(last_td.get()).version();
}
if (last_version >= tbl.version()) {
logDebug("cdb", "refusing to commit outdated version");
return;
}
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->commit();
for (const auto& cb : on_table_change_) {
cb(tbl);
}
}
HashMap<String, uint64_t> ConfigDirectory::fetchMasterHeads() const {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/heads",
master_addr_.hostAndPort()));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
DefaultCSVInputStream csv(BufferInputStream::fromBuffer(&res.body()), '=');
HashMap<String, uint64_t> heads;
Vector<String> row;
while (csv.readNextRow(&row)) {
if (row.size() != 2) {
RAISE(kRuntimeError, "invalid response");
}
heads[row[0]] = std::stoull(row[1]);
}
return heads;
}
void ConfigDirectory::startWatcher() {
watcher_running_ = true;
watcher_thread_ = std::thread([this] {
while (watcher_running_.load()) {
try {
sync();
} catch (const StandardException& e) {
logCritical("analyticsd", e, "error during master sync");
}
usleep(500000);
}
});
}
void ConfigDirectory::stopWatcher() {
if (!watcher_running_) {
return;
}
watcher_running_ = false;
watcher_thread_.join();
}
} // namespace cm
<|endoftext|> |
<commit_before>#include <dlfcn.h>
#include "loader.h"
BVS::Loader::Loader(Control& control, const Info& info)
: control(control),
logger("Loader"),
info(info),
modules(Control::modules)
{
}
BVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread, const std::string& poolName)
{
/* algorithm:
* SEPARATE id(library).options
* CHECK for duplicate ids
* LOAD the library and CHECK errors
* LINK and execute register function, CHECK errors
* SAVE metadata
* MOVE connectors to metadata
* START (un/)threaded module
*/
std::string id;
std::string library;
std::string options;
// search for '.' in id and separate id and options
size_t separator = moduleTraits.find_first_of('.');
if (separator!=std::string::npos)
{
id = moduleTraits.substr(0, separator);
options = moduleTraits.substr(separator+1, std::string::npos);
}
else
id = moduleTraits;
// search for '(' in id and separate if necessary
separator = id.find_first_of('(');
if (separator!=std::string::npos)
{
library = id.substr(separator+1, std::string::npos);
library.erase(library.length()-1);
id = id.erase(separator, std::string::npos);
}
else
library = id;
// search for duplicate id in modules
if (modules.find(id)!=modules.end())
{
LOG(0, "Duplicate id for module: " << id);
LOG(0, "If you try to load a module more than once, use unique ids and the id(library).options syntax!");
exit(-1);
}
// load library
LibHandle dlib = loadLibrary(id, library);
// look for bvsRegisterModule in loaded lib, check for errors and execute register function
typedef void (*bvsRegisterModule_t)(const std::string& id, const Info& info);
bvsRegisterModule_t bvsRegisterModule;
*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule");
// check for errors
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "Loading function bvsRegisterModule() in '" << library << "' resulted in: " << dlerr);
exit(-1);
}
// register
bvsRegisterModule(id, info);
LOG(2, "Loading '" << id << "' successfull!");
// load library and save handle, library name and option string for later use
modules[id]->dlib = dlib;
modules[id]->library = library;
modules[id]->options = options;
// move connectors from temporary to metadata
modules[id]->connectors = std::move(ConnectorDataCollector::connectors);
// let control handle module start
modules[id]->asThread = asThread;
modules[id]->poolName = poolName;
control.startModule(id);
return *this;
}
BVS::Loader& BVS::Loader::unload(const std::string& id)
{
/* algorithm:
* CHECK thread, signal exit
* DISCONNECT connectors
* DELETE module instance and connectors
* CHECK library handle
* PURGE module and its metadata
* CLOSE library
* CHECK errors
*/
// wait for thread to join, first check if it is still running
if (modules[id]->asThread == true)
{
if (modules[id]->thread.joinable())
{
modules[id]->flag = ControlFlag::QUIT;
control.notifyThreads();
LOG(3, "Waiting for '" << id << "' to join!");
modules[id]->thread.join();
}
}
// disconnect connectors
for (auto& it: modules)
{
for (auto& con: it.second->connectors)
{
if (con.second->type==ConnectorType::INPUT) continue;
// find and reset all inputs connected to output
for (auto& mods: modules)
{
for (auto& modCon: mods.second->connectors)
{
if (con.second->pointer==modCon.second->pointer)
{
modCon.second->pointer = nullptr;
modCon.second->active = false;
modCon.second->mutex = nullptr;
}
}
}
}
}
unloadLibrary(id, true);
return *this;
}
BVS::Loader& BVS::Loader::unloadAll()
{
while (!modules.empty()) unload(modules.begin()->first);
return *this;
}
BVS::Loader& BVS::Loader::connectAllModules(const bool connectorTypeMatching)
{
for (auto& it: modules) connectModule(it.second->id, connectorTypeMatching);
return *this;
}
BVS::Loader& BVS::Loader::connectModule(const std::string& id, const bool connectorTypeMatching)
{
/* algorithm:
* WHILE option string not empty
* SEPARATE selection
* CHECK input and output
* CHECK input typeid hash == output typeid hash
* CONNECT
* DONE
*/
ModuleData* module = modules[id].get();
std::string options = module->options;
std::string selection;
std::string input;
std::string targetModule;
std::string targetOutput;
size_t separator;
size_t separator2;
while (!options.empty())
{
// get input name and selection
separator = options.find_first_of('(');
separator2 = options.find_first_of(')');
selection = options.substr(0, separator2+1);
if (separator!=std::string::npos)
{
input = options.substr(0, separator);
targetModule= options.substr(separator+1, separator2-separator-1);
}
else
{
LOG(0, "No input selection found: " << selection);
exit(1);
}
// remove parsed part
options.erase(0, separator2+1);
if (options[0] == '.') options.erase(options.begin());
// search for '.' in selection and separate module and output
separator = targetModule.find_first_of('.');
if (separator!=std::string::npos)
{
targetOutput = targetModule.substr(separator+1, std::string::npos);
targetModule = targetModule.substr(0, separator);
}
else
{
LOG(0, "No module output selected: " << module->id << "." << selection);
exit(1);
}
// check input and output
checkModuleInput(module, input);
checkModuleOutput(module, targetModule, targetOutput);
// check input typeid hash == output typeid hash
if (connectorTypeMatching && module->connectors[input]->typeIDHash != modules[targetModule]->connectors[targetOutput]->typeIDHash)
{
LOG(0, "Selected input and output connector template instantiations are of different type: "
<< module->id << "." << selection << " -> "
<< module->connectors[input]->typeIDName << " != " << modules[targetModule]->connectors[targetOutput]->typeIDName);
exit(1);
}
// connect
module->connectors[input]->pointer = modules[targetModule]->connectors[targetOutput]->pointer;
module->connectors[input]->mutex = modules[targetModule]->connectors[targetOutput]->mutex;
LOG(3, "Connected: " << module->id << "." << module->connectors[input]->id << " <- " << modules[targetModule]->id << "." << modules[targetModule]->connectors[targetOutput]->id);
}
return *this;
}
BVS::Loader& BVS::Loader::hotSwapModule(const std::string& id)
{
#ifdef BVS_MODULE_HOTSWAP
// TODO NEXT wait for thread to and pools
if (modules[id]->asThread || !modules[id]->poolName.empty())
control.waitUntilInactive(id);
unloadLibrary(id, false);
//HOTSWAP
LibHandle dlib = loadLibrary(id, modules[id]->library);
// look for bvsRegisterModule in loaded lib, check for errors and execute register function
typedef void (*bvsHotSwapModule_t)(const std::string& id, BVS::Module* module);
bvsHotSwapModule_t bvsHotSwapModule;
*reinterpret_cast<void**>(&bvsHotSwapModule)=dlsym(dlib, "bvsHotSwapModule");
// check for errors
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "Loading function bvsHotSwapModule() in '" << modules[id]->library << "' resulted in: " << dlerr);
exit(-1);
}
// call hotswap routine in module
bvsHotSwapModule(id, modules[id]->module.get());
LOG(2, "Hotswapping '" << id << "' successfull!");
// save new dlib information
modules[id]->dlib = dlib;
#else //BVS_MODULE_HOTSWAP
(void) id;
LOG(0, "ERROR: HotSwap disabled!");
#endif //BVS_MODULE_HOTSWAP
return *this;
}
BVS::LibHandle BVS::Loader::loadLibrary(const std::string& id, const std::string& library)
{
// prepare path and load the lib
std::string modulePath = "lib" + library + ".so";
LibHandle dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL)
{
LOG(3, "Loading '" << id << "' from '" << modulePath << "'!");
}
else
{
#ifdef BVS_OSX_ANOMALIES
// additional check for 'dylib' (when compiled under OSX as SHARED instead of MODULE)
modulePath.resize(modulePath.size()-2);
modulePath += "dylib";
dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL) LOG(3, "Loading " << id << " from " << modulePath << "!");
#endif //BVS_OSX_ANOMALIES
}
// check for errors
if (dlib==NULL)
{
LOG(0, "Loading '" << modulePath << "' resulted in: " << dlerror());
exit(-1);
}
return dlib;
}
BVS::Loader& BVS::Loader::unloadLibrary(const std::string& id, const bool& purgeModuleData)
{
// close lib and check for errors
#ifndef BVS_OSX_ANOMALIES
std::string modulePath = "./lib" + modules[id]->library + ".so";
#else
std::string modulePath = "./lib" + modules[id]->library + ".(so|dylib)";
#endif //BVS_OSX_ANOMALIES
LOG(3, "Module '" << id << "' unloading from '" << modulePath << "'!");
// get handle from internals
void* dlib = modules[id]->dlib;
if (dlib==nullptr)
{
LOG(0, "Requested module '" << id << "' not found!");
exit(-1);
}
// purge module data if desired
if (purgeModuleData) control.purgeData(id);
// close the lib
dlclose(dlib);
// check for errors
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "While closing '" << modulePath << "' following error occured: " << dlerror());
exit(-1);
}
LOG(2, "Library '" << modulePath << "' unloaded!");
return *this;
}
BVS::Loader& BVS::Loader::checkModuleInput(const ModuleData* module, const std::string& inputName)
{
auto input = module->connectors.find(inputName);
// check existence and type
if (input == module->connectors.end() || input->second->type != ConnectorType::INPUT)
{
LOG(0, "Input not found: " << module->id << "." << inputName);
printModuleConnectors(module);
exit(1);
}
// check if input is already connected
if (input->second->active)
{
LOG(0, "Input already connected: " << module->id << "." << inputName);
exit(1);
}
return *this;
}
BVS::Loader& BVS::Loader::checkModuleOutput(const ModuleData* module, const std::string& targetModule, const std::string& targetOutput)
{
(void) module;
auto target = modules.find(targetModule);
// check if desired module exists
if (target == modules.end())
{
LOG(0, "Module not found: " << targetModule << " in " << module->id << "." << module->options);
exit(1);
}
auto output = target->second->connectors.find(targetOutput);
// check output existence and type
if (output == target->second->connectors.end() || output->second->type != ConnectorType::OUTPUT)
{
LOG(0, "Output not found: " << targetOutput << " in " << module->id << "." << module->options);
printModuleConnectors(target->second.get());
exit(1);
}
return *this;
}
BVS::Loader& BVS::Loader::printModuleConnectors(const ModuleData* module)
{
if (module->connectors.size()==0)
{
LOG(0, "Module " << module->id << " does not define any connector!");
}
else
{
LOG(0, "Module " << module->id << " defines the following connectors: ");
for (auto& it: module->connectors) LOG(0, it.second->type << ": " << it.second->id);
}
return *this;
}
<commit_msg>loader: cleanup hotswap function<commit_after>#include <dlfcn.h>
#include "loader.h"
BVS::Loader::Loader(Control& control, const Info& info)
: control(control),
logger("Loader"),
info(info),
modules(Control::modules)
{
}
BVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread, const std::string& poolName)
{
/* algorithm:
* SEPARATE id(library).options
* CHECK for duplicate ids
* LOAD the library and CHECK errors
* LINK and execute register function, CHECK errors
* SAVE metadata
* MOVE connectors to metadata
* START (un/)threaded module
*/
std::string id;
std::string library;
std::string options;
// search for '.' in id and separate id and options
size_t separator = moduleTraits.find_first_of('.');
if (separator!=std::string::npos)
{
id = moduleTraits.substr(0, separator);
options = moduleTraits.substr(separator+1, std::string::npos);
}
else
id = moduleTraits;
// search for '(' in id and separate if necessary
separator = id.find_first_of('(');
if (separator!=std::string::npos)
{
library = id.substr(separator+1, std::string::npos);
library.erase(library.length()-1);
id = id.erase(separator, std::string::npos);
}
else
library = id;
// search for duplicate id in modules
if (modules.find(id)!=modules.end())
{
LOG(0, "Duplicate id for module: " << id);
LOG(0, "If you try to load a module more than once, use unique ids and the id(library).options syntax!");
exit(-1);
}
// load library
LibHandle dlib = loadLibrary(id, library);
// look for bvsRegisterModule in loaded lib, check for errors and execute register function
typedef void (*bvsRegisterModule_t)(const std::string& id, const Info& info);
bvsRegisterModule_t bvsRegisterModule;
*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule");
// check for errors
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "Loading function bvsRegisterModule() in '" << library << "' resulted in: " << dlerr);
exit(-1);
}
// register
bvsRegisterModule(id, info);
LOG(2, "Loading '" << id << "' successfull!");
// load library and save handle, library name and option string for later use
modules[id]->dlib = dlib;
modules[id]->library = library;
modules[id]->options = options;
// move connectors from temporary to metadata
modules[id]->connectors = std::move(ConnectorDataCollector::connectors);
// let control handle module start
modules[id]->asThread = asThread;
modules[id]->poolName = poolName;
control.startModule(id);
return *this;
}
BVS::Loader& BVS::Loader::unload(const std::string& id)
{
/* algorithm:
* CHECK thread, signal exit
* DISCONNECT connectors
* DELETE module instance and connectors
* CHECK library handle
* PURGE module and its metadata
* CLOSE library
* CHECK errors
*/
// wait for thread to join, first check if it is still running
if (modules[id]->asThread == true)
{
if (modules[id]->thread.joinable())
{
modules[id]->flag = ControlFlag::QUIT;
control.notifyThreads();
LOG(3, "Waiting for '" << id << "' to join!");
modules[id]->thread.join();
}
}
// disconnect connectors
for (auto& it: modules)
{
for (auto& con: it.second->connectors)
{
if (con.second->type==ConnectorType::INPUT) continue;
// find and reset all inputs connected to output
for (auto& mods: modules)
{
for (auto& modCon: mods.second->connectors)
{
if (con.second->pointer==modCon.second->pointer)
{
modCon.second->pointer = nullptr;
modCon.second->active = false;
modCon.second->mutex = nullptr;
}
}
}
}
}
unloadLibrary(id, true);
return *this;
}
BVS::Loader& BVS::Loader::unloadAll()
{
while (!modules.empty()) unload(modules.begin()->first);
return *this;
}
BVS::Loader& BVS::Loader::connectAllModules(const bool connectorTypeMatching)
{
for (auto& it: modules) connectModule(it.second->id, connectorTypeMatching);
return *this;
}
BVS::Loader& BVS::Loader::connectModule(const std::string& id, const bool connectorTypeMatching)
{
/* algorithm:
* WHILE option string not empty
* SEPARATE selection
* CHECK input and output
* CHECK input typeid hash == output typeid hash
* CONNECT
* DONE
*/
ModuleData* module = modules[id].get();
std::string options = module->options;
std::string selection;
std::string input;
std::string targetModule;
std::string targetOutput;
size_t separator;
size_t separator2;
while (!options.empty())
{
// get input name and selection
separator = options.find_first_of('(');
separator2 = options.find_first_of(')');
selection = options.substr(0, separator2+1);
if (separator!=std::string::npos)
{
input = options.substr(0, separator);
targetModule= options.substr(separator+1, separator2-separator-1);
}
else
{
LOG(0, "No input selection found: " << selection);
exit(1);
}
// remove parsed part
options.erase(0, separator2+1);
if (options[0] == '.') options.erase(options.begin());
// search for '.' in selection and separate module and output
separator = targetModule.find_first_of('.');
if (separator!=std::string::npos)
{
targetOutput = targetModule.substr(separator+1, std::string::npos);
targetModule = targetModule.substr(0, separator);
}
else
{
LOG(0, "No module output selected: " << module->id << "." << selection);
exit(1);
}
// check input and output
checkModuleInput(module, input);
checkModuleOutput(module, targetModule, targetOutput);
// check input typeid hash == output typeid hash
if (connectorTypeMatching && module->connectors[input]->typeIDHash != modules[targetModule]->connectors[targetOutput]->typeIDHash)
{
LOG(0, "Selected input and output connector template instantiations are of different type: "
<< module->id << "." << selection << " -> "
<< module->connectors[input]->typeIDName << " != " << modules[targetModule]->connectors[targetOutput]->typeIDName);
exit(1);
}
// connect
module->connectors[input]->pointer = modules[targetModule]->connectors[targetOutput]->pointer;
module->connectors[input]->mutex = modules[targetModule]->connectors[targetOutput]->mutex;
LOG(3, "Connected: " << module->id << "." << module->connectors[input]->id << " <- " << modules[targetModule]->id << "." << modules[targetModule]->connectors[targetOutput]->id);
}
return *this;
}
BVS::Loader& BVS::Loader::hotSwapModule(const std::string& id)
{
#ifdef BVS_MODULE_HOTSWAP
// wait for thread or pool
if (modules[id]->asThread || !modules[id]->poolName.empty())
control.waitUntilInactive(id);
// reload library
unloadLibrary(id, false);
LibHandle dlib = loadLibrary(id, modules[id]->library);
// look for bvsHotSwapModule
typedef void (*bvsHotSwapModule_t)(const std::string& id, BVS::Module* module);
bvsHotSwapModule_t bvsHotSwapModule;
*reinterpret_cast<void**>(&bvsHotSwapModule)=dlsym(dlib, "bvsHotSwapModule");
// check for errors
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "Loading function bvsHotSwapModule() in '" << modules[id]->library << "' resulted in: " << dlerr);
exit(-1);
}
// call hotswap routine in module
bvsHotSwapModule(id, modules[id]->module.get());
LOG(2, "Hotswapping '" << id << "' successfull!");
// save new dlib information
modules[id]->dlib = dlib;
#else //BVS_MODULE_HOTSWAP
LOG(0, "ERROR: HotSwap disabled, could not hotswap: '" << id << "'!");
#endif //BVS_MODULE_HOTSWAP
return *this;
}
BVS::LibHandle BVS::Loader::loadLibrary(const std::string& id, const std::string& library)
{
// prepare path and load the lib
std::string modulePath = "lib" + library + ".so";
LibHandle dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL)
{
LOG(3, "Loading '" << id << "' from '" << modulePath << "'!");
}
else
{
#ifdef BVS_OSX_ANOMALIES
// additional check for 'dylib' (when compiled under OSX as SHARED instead of MODULE)
modulePath.resize(modulePath.size()-2);
modulePath += "dylib";
dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL) LOG(3, "Loading " << id << " from " << modulePath << "!");
#endif //BVS_OSX_ANOMALIES
}
// check for errors
if (dlib==NULL)
{
LOG(0, "Loading '" << modulePath << "' resulted in: " << dlerror());
exit(-1);
}
return dlib;
}
BVS::Loader& BVS::Loader::unloadLibrary(const std::string& id, const bool& purgeModuleData)
{
// close lib and check for errors
#ifndef BVS_OSX_ANOMALIES
std::string modulePath = "./lib" + modules[id]->library + ".so";
#else
std::string modulePath = "./lib" + modules[id]->library + ".(so|dylib)";
#endif //BVS_OSX_ANOMALIES
LOG(3, "Module '" << id << "' unloading from '" << modulePath << "'!");
// get handle from internals
void* dlib = modules[id]->dlib;
if (dlib==nullptr)
{
LOG(0, "Requested module '" << id << "' not found!");
exit(-1);
}
// purge module data if desired
if (purgeModuleData) control.purgeData(id);
// close the lib
dlclose(dlib);
// check for errors
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "While closing '" << modulePath << "' following error occured: " << dlerror());
exit(-1);
}
LOG(2, "Library '" << modulePath << "' unloaded!");
return *this;
}
BVS::Loader& BVS::Loader::checkModuleInput(const ModuleData* module, const std::string& inputName)
{
auto input = module->connectors.find(inputName);
// check existence and type
if (input == module->connectors.end() || input->second->type != ConnectorType::INPUT)
{
LOG(0, "Input not found: " << module->id << "." << inputName);
printModuleConnectors(module);
exit(1);
}
// check if input is already connected
if (input->second->active)
{
LOG(0, "Input already connected: " << module->id << "." << inputName);
exit(1);
}
return *this;
}
BVS::Loader& BVS::Loader::checkModuleOutput(const ModuleData* module, const std::string& targetModule, const std::string& targetOutput)
{
(void) module;
auto target = modules.find(targetModule);
// check if desired module exists
if (target == modules.end())
{
LOG(0, "Module not found: " << targetModule << " in " << module->id << "." << module->options);
exit(1);
}
auto output = target->second->connectors.find(targetOutput);
// check output existence and type
if (output == target->second->connectors.end() || output->second->type != ConnectorType::OUTPUT)
{
LOG(0, "Output not found: " << targetOutput << " in " << module->id << "." << module->options);
printModuleConnectors(target->second.get());
exit(1);
}
return *this;
}
BVS::Loader& BVS::Loader::printModuleConnectors(const ModuleData* module)
{
if (module->connectors.size()==0)
{
LOG(0, "Module " << module->id << " does not define any connector!");
}
else
{
LOG(0, "Module " << module->id << " defines the following connectors: ");
for (auto& it: module->connectors) LOG(0, it.second->type << ": " << it.second->id);
}
return *this;
}
<|endoftext|> |
<commit_before>#include <time.h>
#include <stdlib.h>
#include "game_modes.hpp"
GameModes::GameModes(GameDesk* desk_point, IoView* view) {
desk_ = desk_point;
ioview_ = view;
}
void GameModes::start(int argc, char* argv[]) {
if (argc == 1) {
help();
} else if (*++argv[1] == 'w') {
gameForWin();
} else if (*argv[1] == 's') {
gameForScore();
} else if (*argv[1] == 't') {
gameWithTime();
} else {
help();
}
}
void GameModes::gameForWin() {
int desk_size;
desk_size = ioview_->getDeskSize();
int win_number;
win_number = ioview_->getWinNumber();
setDesk(desk_size);
ioview_->output();
int steps_number = 0;
while (!checkFail() && !checkWin(win_number)) {
steps_number += 1;
play();
}
ioview_->finish(checkFail(), score(), steps_number);
}
void GameModes::gameForScore() {
int desk_size;
desk_size = ioview_->getDeskSize();
setDesk(desk_size);
ioview_->output();
int steps_number = 0;
while (!checkFail()) {
steps_number += 1;
play();
}
ioview_->finish(checkFail(), score(), steps_number);
}
void GameModes::gameWithTime() {
int desk_size;
desk_size = ioview_->getDeskSize();
int time_number;
time_number = ioview_->getTimeNumber();
setDesk(desk_size);
int t1 = time(NULL);
int t2 = 0;
ioview_->output();
int steps_number = 0;
while (!checkFail() && ((t2 - t1) < time_number * 60)) {
steps_number += 1;
play();
t2 = time(NULL);
}
ioview_->finish(checkFail(), score(), steps_number);
}
void GameModes::help() {
ioview_->sendHelpMessage();
}
void GameModes::setDesk(int desk_size) {
int i, x;
Point point;
desk_->resize(desk_size);
for (i = 0; i < desk_size; i++) {
for (x = 0; x < desk_size; x++) {
point.col = i;
point.row = x;
if (rand() <= (RAND_MAX / 2)) {
desk_->setDeskNumber(point, 1);
} else {
desk_->setDeskNumber(point, 2);
}
}
}
}
void GameModes::play() {
Points points;
Checker checker;
points = ioview_->getIndex();
if (checker.checkStep(*desk_, points)) {
replace(points);
ioview_->output();
} else {
ioview_->indexError();
}
}
void GameModes::replace(Points& points) {
if (points.undo_action = true) {
gameUndo(points);
}
int n1 = desk_->getDeskNumber(points.p1);
int n2 = desk_->getDeskNumber(points.p2);
desk_->setDeskNumber(points.p2, n2 * 2);
while (points.p1.col < (desk_->getRowNumber() - 1)) {
Points points_local;
points_local = points;
points_local.p1.col += 1;
desk_->setDeskNumber(points.p1, desk_->getDeskNumber(points_local.p1));
points.p1.col = points_local.p1.col;
}
if (rand() <= (RAND_MAX / 2)) {
desk_->setDeskNumber(points.p1, 2);
} else {
desk_->setDeskNumber(points.p1, 1);
}
}
int GameModes::score() {
Point point;
int all_score = 0;
int row_score = 0;
int i, x;
for (i = 0; i < desk_->getRowNumber(); i++) {
for (x = 0; x < desk_->getRowNumber(); x++) {
point.col = i;
point.row = x;
row_score += desk_->getDeskNumber(point);
}
all_score += row_score;
row_score = 0;
}
return all_score;
}
bool GameModes::checkWin(int for_win) {
if (for_win <= score()) {
return true;
}
return false;
}
bool GameModes::checkFail() {
Points points;
Checker checker;
int i, x, z, t;
for (i = 0; i < desk_->getRowNumber(); i++) {
points.p1.col = i;
for (x = 0; x < desk_->getRowNumber(); x++) {
points.p1.row = x;
for (z = 0; z < desk_->getRowNumber(); z++) {
points.p2.col = z;
for (t = 0; t < desk_->getRowNumber(); t++) {
points.p2.row = t;
if (checker.checkStep(*desk_, points)) {
return false;
}
}
}
}
}
return true;
}
void GameModes::gameUndo(Points& points) {
}
<commit_msg>Save user's steps using saveStep method<commit_after>#include <time.h>
#include <stdlib.h>
#include "game_modes.hpp"
GameModes::GameModes(GameDesk* desk_point, IoView* view) {
desk_ = desk_point;
ioview_ = view;
}
void GameModes::start(int argc, char* argv[]) {
if (argc == 1) {
help();
} else if (*++argv[1] == 'w') {
gameForWin();
} else if (*argv[1] == 's') {
gameForScore();
} else if (*argv[1] == 't') {
gameWithTime();
} else {
help();
}
}
void GameModes::gameForWin() {
int desk_size;
desk_size = ioview_->getDeskSize();
int win_number;
win_number = ioview_->getWinNumber();
setDesk(desk_size);
ioview_->output();
int steps_number = 0;
while (!checkFail() && !checkWin(win_number)) {
steps_number += 1;
play();
}
ioview_->finish(checkFail(), score(), steps_number);
}
void GameModes::gameForScore() {
int desk_size;
desk_size = ioview_->getDeskSize();
setDesk(desk_size);
ioview_->output();
int steps_number = 0;
while (!checkFail()) {
steps_number += 1;
play();
}
ioview_->finish(checkFail(), score(), steps_number);
}
void GameModes::gameWithTime() {
int desk_size;
desk_size = ioview_->getDeskSize();
int time_number;
time_number = ioview_->getTimeNumber();
setDesk(desk_size);
int t1 = time(NULL);
int t2 = 0;
ioview_->output();
int steps_number = 0;
while (!checkFail() && ((t2 - t1) < time_number * 60)) {
steps_number += 1;
play();
t2 = time(NULL);
}
ioview_->finish(checkFail(), score(), steps_number);
}
void GameModes::help() {
ioview_->sendHelpMessage();
}
void GameModes::setDesk(int desk_size) {
int i, x;
Point point;
desk_->resize(desk_size);
for (i = 0; i < desk_size; i++) {
for (x = 0; x < desk_size; x++) {
point.col = i;
point.row = x;
if (rand() <= (RAND_MAX / 2)) {
desk_->setDeskNumber(point, 1);
} else {
desk_->setDeskNumber(point, 2);
}
}
}
}
void GameModes::play() {
Points points;
Checker checker;
points = ioview_->getIndex();
if (checker.checkStep(*desk_, points)) {
desk_->saveStep(points);
replace(points);
ioview_->output();
} else {
ioview_->indexError();
}
}
void GameModes::replace(Points& points) {
if (points.undo_action = true) {
gameUndo(points);
return;
}
int n1 = desk_->getDeskNumber(points.p1);
int n2 = desk_->getDeskNumber(points.p2);
desk_->setDeskNumber(points.p2, n2 * 2);
while (points.p1.col < (desk_->getRowNumber() - 1)) {
Points points_local;
points_local = points;
points_local.p1.col += 1;
desk_->setDeskNumber(points.p1, desk_->getDeskNumber(points_local.p1));
points.p1.col = points_local.p1.col;
}
if (rand() <= (RAND_MAX / 2)) {
desk_->setDeskNumber(points.p1, 2);
} else {
desk_->setDeskNumber(points.p1, 1);
}
}
int GameModes::score() {
Point point;
int all_score = 0;
int row_score = 0;
int i, x;
for (i = 0; i < desk_->getRowNumber(); i++) {
for (x = 0; x < desk_->getRowNumber(); x++) {
point.col = i;
point.row = x;
row_score += desk_->getDeskNumber(point);
}
all_score += row_score;
row_score = 0;
}
return all_score;
}
bool GameModes::checkWin(int for_win) {
if (for_win <= score()) {
return true;
}
return false;
}
bool GameModes::checkFail() {
Points points;
Checker checker;
int i, x, z, t;
for (i = 0; i < desk_->getRowNumber(); i++) {
points.p1.col = i;
for (x = 0; x < desk_->getRowNumber(); x++) {
points.p1.row = x;
for (z = 0; z < desk_->getRowNumber(); z++) {
points.p2.col = z;
for (t = 0; t < desk_->getRowNumber(); t++) {
points.p2.row = t;
if (checker.checkStep(*desk_, points)) {
return false;
}
}
}
}
}
return true;
}
void GameModes::gameUndo(Points& points) {
}
<|endoftext|> |
<commit_before>/*
* Written by Nitin Kumar Maharana
* [email protected]
*/
class Solution {
int haystackLen, needleLen;
void findPrefixArray(string& pattern, int *prefix)
{
int lastPrefixLen = 0;
prefix[0] = 0;
int i = 1;
while(i < needleLen)
{
if(pattern[i] == pattern[lastPrefixLen])
{
lastPrefixLen++;
prefix[i] = lastPrefixLen;
i++;
}
else
{
if(lastPrefixLen)
lastPrefixLen = prefix[lastPrefixLen-1];
else
{
prefix[i] = 0;
i++;
}
}
}
}
public:
int strStr(string haystack, string needle) {
haystackLen = haystack.length();
needleLen = needle.length();
if(!needleLen)
return 0;
int *prefixArray = new int[needleLen];
findPrefixArray(needle, prefixArray);
int i = 0, j = 0;
while(i < haystackLen)
{
if(haystack[i] == needle[j])
{
i++;
j++;
}
if(j == needleLen)
return (i-j);
else if((i < haystackLen) && (haystack[i] != needle[j]))
{
if(j != 0)
j = prefixArray[j-1];
else
i++;
}
}
return -1;
}
};<commit_msg>28. Implement strStr() (One more version of KMP - Easy to understand)<commit_after>/*
* Written by Nitin Kumar Maharana
* [email protected]
*/
class Solution {
int haystackLen, needleLen;
void findPrefixArray(string& pattern, int *prefix)
{
int lastPrefixLen = 0;
prefix[0] = 0;
int i = 1;
while(i < needleLen)
{
if(pattern[i] == pattern[lastPrefixLen])
{
lastPrefixLen++;
prefix[i] = lastPrefixLen;
i++;
}
else
{
if(lastPrefixLen)
lastPrefixLen = prefix[lastPrefixLen-1];
else
{
prefix[i] = 0;
i++;
}
}
}
}
public:
int strStr(string haystack, string needle) {
haystackLen = haystack.length();
needleLen = needle.length();
if(!needleLen)
return 0;
int *prefixArray = new int[needleLen];
findPrefixArray(needle, prefixArray);
int i = 0, j = 0;
while(i < haystackLen)
{
if(haystack[i] == needle[j])
{
i++;
j++;
}
if(j == needleLen)
return (i-j);
else if((i < haystackLen) && (haystack[i] != needle[j]))
{
if(j != 0)
j = prefixArray[j-1];
else
i++;
}
}
return -1;
}
};
class Solution1 {
int haystackLen, needleLen;
void findPrefixArray(string& needle, int *prefix)
{
prefix[0] = -1;
int i = 0, j = -1;
while(i < needleLen-1)
{
if(j == -1 || needle[i] == needle[j])
{
i++; j++;
prefix[i] = j;
}
else
j = prefix[j];
}
}
public:
int strStr(string haystack, string needle)
{
haystackLen = haystack.length();
needleLen = needle.length();
int *prev = new int[needleLen];
findPrefixArray(needle, prev);
int i = 0, j = 0;
while(i < haystackLen && j < needleLen)
{
if(j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
j = prev[j];
}
if(j == needleLen)
return (i - j);
else
return -1;
}
};<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (c) 2012-2017 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
****************************************************************************/
#ifndef DTK_NODE_HPP
#define DTK_NODE_HPP
#include <DTK_DetailsBox.hpp>
#include <Kokkos_Pair.hpp>
namespace DataTransferKit
{
struct Node
{
KOKKOS_INLINE_FUNCTION
Node()
: parent( nullptr )
, children( {nullptr, nullptr} )
{
}
Node *parent = nullptr;
Kokkos::pair<Node *, Node *> children;
Box bounding_box;
};
}
#endif
<commit_msg>Use defaulted default constructor for Node<commit_after>/****************************************************************************
* Copyright (c) 2012-2017 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
****************************************************************************/
#ifndef DTK_NODE_HPP
#define DTK_NODE_HPP
#include <DTK_DetailsBox.hpp>
#include <Kokkos_Pair.hpp>
namespace DataTransferKit
{
struct Node
{
KOKKOS_INLINE_FUNCTION
Node() = default;
Node *parent = nullptr;
Kokkos::pair<Node *, Node *> children = {nullptr, nullptr};
Box bounding_box;
};
}
#endif
<|endoftext|> |
<commit_before>//!
//! @author Yue Wang
//! @date 26.11.2014
//!
//! @brief Implementation for Listing 4.12
#include <../include/utilities.hpp>
#include <iostream>
#include <list>
#include <algorithm>
namespace para {
/**
* @brief sequential_functional_quick_sort
*
* for Listing 4.12
*/
template<typename T>
std::list<T> sequential_functional_quick_sort(std::list<T> input)
{
if(input.empty()) return input; // termination condtion
std::list<T> ret;
ret.splice(ret.begin(),input,input.begin());
T pivot = ret.front();
auto divide_point = std::partition(input.begin(),input.end(), [=](T const& t){
return t < pivot;
});
std::list<T> lower;
lower.splice(lower.end(), input, input.begin(),divide_point);
auto new_lower (para::sequential_functional_quick_sort(lower)); //recur
auto new_higher(para::sequential_functional_quick_sort(input)); //recur
ret.splice(ret.end(), new_higher);
ret.splice(ret.begin(),new_lower);
return ret;
}
}//namespace
int main()
{
std::list<int> l {6,3,2,5,1,4};
para::println_range(l);
l = para::sequential_functional_quick_sort(l);
para::println_range(l);
return 0;
}
//! @output
//!
//para> 6 3 2 5 1 4
//para> 1 2 3 4 5 6
<commit_msg>done modified: functional_quick_sort.cpp<commit_after>//!
//! @author Yue Wang
//! @date 26.11.2014
//!
//! @brief Implementation for Listing 4.12
#include <../include/utilities.hpp>
#include <iostream>
#include <list>
#include <algorithm>
namespace para {
/**
* @brief sequential_functional_quick_sort
*
* for Listing 4.12
*/
template<typename T>
std::list<T> sequential_functional_quick_sort(std::list<T> input)
{
if(input.empty()) return input; // termination condtion
std::list<T> ret;
ret.splice(ret.begin(),input,input.begin());
T pivot = ret.front();
auto divide_point = std::partition(input.begin(),input.end(),
[=](T const& t){
return t < pivot;
});
std::list<T> lower;
lower.splice(lower.end(), input, input.begin(),divide_point);
auto new_lower (para::sequential_functional_quick_sort(lower)); //recur
auto new_higher(para::sequential_functional_quick_sort(input)); //recur
ret.splice(ret.end(), new_higher);
ret.splice(ret.begin(),new_lower);
return ret;
}
}//namespace
int main()
{
std::list<int> l {6,3,2,5,1,4};
para::println_range(l);
l = para::sequential_functional_quick_sort(l);
para::println_range(l);
return 0;
}
//! @output
//!
//para> 6 3 2 5 1 4
//para> 1 2 3 4 5 6
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/app/ApplicationContextPublic.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/zapper/User.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanResult.h>
#include <stingray/scanner/DefaultServiceNetworkInfo.h>
#include <stingray/scanner/LcnList.h>
#include <stingray/scanner/OtherTransportInfoEntry.h>
#include <stingray/storage/FatFileSystemProber.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/DefaultDVBTTransport.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbs/Transport.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanResult);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultServiceNetworkInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LcnList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(OtherTransportInfoEntry);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FatFileSystemIdentity);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(dvbs::Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(dvbs::Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(dvbs::Transport);
#endif
}
}}
<commit_msg>moved DBVT stuff to dvbt folder<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/app/ApplicationContextPublic.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/zapper/User.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanResult.h>
#include <stingray/scanner/DefaultServiceNetworkInfo.h>
#include <stingray/scanner/LcnList.h>
#include <stingray/scanner/OtherTransportInfoEntry.h>
#include <stingray/storage/FatFileSystemProber.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbs/Transport.h>
#include <stingray/tuners/dvbt/DefaultDVBTTransport.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanResult);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultServiceNetworkInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LcnList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(OtherTransportInfoEntry);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FatFileSystemIdentity);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(dvbs::Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(dvbs::Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(dvbs::Transport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);
#endif
}
}}
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/crypto/DefaultCertificateExtension.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp3/Mp3MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/ContentDescription.h>
#include <stingray/mpeg/PvrDescription.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/EmuScanPerformerFactory.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/pushvod/pushvod_emu/PushVODEmulationMovie.h>
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanPerformerFactory.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/LybidScanPerformerFactory.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/TricolorScanPerformerFactory.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4SubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultCertificateExtension);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>Implemented SubscriptionClassBundle<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/ca/SubscriptionClassBundle.h>
#include <stingray/crypto/DefaultCertificateExtension.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp3/Mp3MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/ContentDescription.h>
#include <stingray/mpeg/PvrDescription.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/EmuScanPerformerFactory.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/pushvod/pushvod_emu/PushVODEmulationMovie.h>
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanPerformerFactory.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/LybidScanPerformerFactory.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/TricolorScanPerformerFactory.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4SubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionClassBundle);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultCertificateExtension);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>#include "BodymovinParser.h"
#include "FilepathHelper.h"
#include <fstream>
#include <assert.h>
#include <string.h>
namespace gum
{
BodymovinParser::BodymovinParser()
: m_frame_rate(0)
, m_width(0)
, m_height(0)
, m_start_frame(0)
, m_end_frame(0)
{
}
void BodymovinParser::Parse(const Json::Value& val, const std::string& dir)
{
Clear();
ParseHeader(val);
ParseAssets(val["assets"], dir);
ParseLayers(val["layers"], m_layers);
}
void BodymovinParser::Clear()
{
m_assets.clear();
m_layers.clear();
}
void BodymovinParser::ParseHeader(const Json::Value& val)
{
m_version = val["v"].asString();
m_name = val["nm"].asString();
m_frame_rate = val["fr"].asInt();
m_width = val["w"].asInt();
m_height = val["h"].asInt();
m_start_frame = val["ip"].asInt();
m_end_frame = val["op"].asInt();
}
void BodymovinParser::ParseAssets(const Json::Value& val, const std::string& dir)
{
for (int i = 0, n = val.size(); i < n; ++i)
{
const Json::Value& cval = val[i];
Asset a;
a.id = cval["id"].asString();
if (cval.isMember("layers"))
{
ParseLayers(cval["layers"], a.layers);
}
else
{
a.w = cval["w"].asInt();
a.h = cval["h"].asInt();
a.filepath = dir + "\\" + cval["u"].asString() + cval["p"].asString();
}
m_assets.push_back(a);
}
}
void BodymovinParser::ParseLayers(const Json::Value& val, std::vector<Layer>& layers)
{
if (val.size() == 0) {
return;
}
layers.reserve(val.size());
for (int i = val.size() - 1; i >= 0; --i)
{
Layer layer;
if (layer.Load(val[i])) {
layers.push_back(layer);
}
}
}
/************************************************************************/
/* class BodymovinParser::FloatVal::Float3 */
/************************************************************************/
BodymovinParser::FloatVal::Float3::Float3()
{
memset(data, 0, sizeof(data));
}
BodymovinParser::FloatVal::Float3::Float3(const Json::Value& val)
{
memset(data, 0, sizeof(data));
if (val.isArray()) {
assert(val.size() <= 3);
int n = std::min(3, static_cast<int>(val.size()));
for (int i = 0; i < n; ++i) {
data[i] = val[i].asDouble();
}
} else {
data[0] = val.asDouble();
}
}
bool BodymovinParser::FloatVal::Float3::operator == (const Float3& f) const
{
for (int i = 0; i < 3; ++i) {
if (fabs(data[i] - f.data[i]) > FLT_EPSILON) {
return false;
}
}
return true;
}
/************************************************************************/
/* class BodymovinParser::FloatVal */
/************************************************************************/
void BodymovinParser::FloatVal::Load(const Json::Value& val)
{
expression = val["x"].asString();
bool anim = val["a"].asInt() == 1;
if (!anim)
{
KeyFrame kf;
kf.s_val = Float3(val["k"]);
frames.push_back(kf);
return;
}
int n = val["k"].size();
frames.resize(n);
for (int i = 0; i < n; ++i)
{
const Json::Value& src = val["k"][i];
KeyFrame& dst = frames[i];
dst.frame = src["t"].asInt();
if (src.isMember("s")) {
dst.s_val = Float3(src["s"]);
}
if (src.isMember("e")) {
dst.e_val = Float3(src["e"]);
if (i != n - 1) {
frames[i + 1].s_val = dst.e_val;
}
}
if (src.isMember("i")) {
assert(src["i"].isMember("x") && src["i"].isMember("y"));
dst.ix = Float3(src["i"]["x"]);
dst.iy = Float3(src["i"]["y"]);
}
if (src.isMember("o")) {
assert(src["o"].isMember("x") && src["o"].isMember("y"));
dst.ox = Float3(src["o"]["x"]);
dst.oy = Float3(src["o"]["y"]);
}
if (src.isMember("ti")) {
dst.ti = Float3(src["ti"]);
}
if (src.isMember("to")) {
dst.to = Float3(src["to"]);
}
}
#ifndef NDEBUG
if (n > 1) {
for (int i = 0; i < n - 1; ++i) {
assert(frames[i].e_val == frames[i + 1].s_val);
}
}
#endif // NDEBUG
}
/************************************************************************/
/* class BodymovinParser::Transform */
/************************************************************************/
BodymovinParser::Transform::Transform()
{
}
void BodymovinParser::Transform::Load(const Json::Value& val)
{
if (val.isMember("a")) {
anchor.Load(val["a"]);
}
if (val.isMember("o")) {
opacity.Load(val["o"]);
}
if (val.isMember("p")) {
position.Load(val["p"]);
}
if (val.isMember("r")) {
rotate.Load(val["r"]);
}
if (val.isMember("s")) {
scale.Load(val["s"]);
}
}
/************************************************************************/
/* class BodymovinParser::Layer */
/************************************************************************/
BodymovinParser::Layer::Layer()
{
}
bool BodymovinParser::Layer::Load(const Json::Value& val)
{
name = val["nm"].asString();
ref_id = val["refId"].asString();
layer_id = val["ind"].asInt();
layer_type = val["ty"].asInt();
switch (layer_type)
{
case LAYER_PRE_COMP:
comp_width = val["w"].asInt();
comp_height = val["h"].asInt();
break;
case LAYER_SOLID:
// todo: not support mask now
if (val.isMember("hasMask") && val["hasMask"].asBool()) {
return false;
}
solid_width = val["sw"].asInt();
solid_height = val["sh"].asInt();
solid_color = val["sc"].asString();
break;
}
if (val.isMember("parent")) {
parent_id = val["parent"].asInt();
} else {
parent_id = -1;
}
cl = val["cl"].asString();
float time_stretch = 1;
if (val.isMember("sr")) {
time_stretch = val["sr"].asDouble();
}
in_frame = val["ip"].asDouble() / time_stretch;
out_frame = val["op"].asDouble() / time_stretch;
start_frame = val["st"].asInt();
auto_ori = val["ao"].asInt();
blend_mode = val["bm"].asInt();
trans.Load(val["ks"]);
return true;
}
}<commit_msg>[FIXED] read expression val<commit_after>#include "BodymovinParser.h"
#include "FilepathHelper.h"
#include <fstream>
#include <assert.h>
#include <string.h>
namespace gum
{
BodymovinParser::BodymovinParser()
: m_frame_rate(0)
, m_width(0)
, m_height(0)
, m_start_frame(0)
, m_end_frame(0)
{
}
void BodymovinParser::Parse(const Json::Value& val, const std::string& dir)
{
Clear();
ParseHeader(val);
ParseAssets(val["assets"], dir);
ParseLayers(val["layers"], m_layers);
}
void BodymovinParser::Clear()
{
m_assets.clear();
m_layers.clear();
}
void BodymovinParser::ParseHeader(const Json::Value& val)
{
m_version = val["v"].asString();
m_name = val["nm"].asString();
m_frame_rate = val["fr"].asInt();
m_width = val["w"].asInt();
m_height = val["h"].asInt();
m_start_frame = val["ip"].asInt();
m_end_frame = val["op"].asInt();
}
void BodymovinParser::ParseAssets(const Json::Value& val, const std::string& dir)
{
for (int i = 0, n = val.size(); i < n; ++i)
{
const Json::Value& cval = val[i];
Asset a;
a.id = cval["id"].asString();
if (cval.isMember("layers"))
{
ParseLayers(cval["layers"], a.layers);
}
else
{
a.w = cval["w"].asInt();
a.h = cval["h"].asInt();
a.filepath = dir + "\\" + cval["u"].asString() + cval["p"].asString();
}
m_assets.push_back(a);
}
}
void BodymovinParser::ParseLayers(const Json::Value& val, std::vector<Layer>& layers)
{
if (val.size() == 0) {
return;
}
layers.reserve(val.size());
for (int i = val.size() - 1; i >= 0; --i)
{
Layer layer;
if (layer.Load(val[i])) {
layers.push_back(layer);
}
}
}
/************************************************************************/
/* class BodymovinParser::FloatVal::Float3 */
/************************************************************************/
BodymovinParser::FloatVal::Float3::Float3()
{
memset(data, 0, sizeof(data));
}
BodymovinParser::FloatVal::Float3::Float3(const Json::Value& val)
{
memset(data, 0, sizeof(data));
if (val.isArray()) {
assert(val.size() <= 3);
int n = std::min(3, static_cast<int>(val.size()));
for (int i = 0; i < n; ++i) {
data[i] = val[i].asDouble();
}
} else {
data[0] = val.asDouble();
}
}
bool BodymovinParser::FloatVal::Float3::operator == (const Float3& f) const
{
for (int i = 0; i < 3; ++i) {
if (fabs(data[i] - f.data[i]) > FLT_EPSILON) {
return false;
}
}
return true;
}
/************************************************************************/
/* class BodymovinParser::FloatVal */
/************************************************************************/
void BodymovinParser::FloatVal::Load(const Json::Value& val)
{
if (val.isMember("x") && val["x"].isString()) {
expression = val["x"].asString();
}
bool anim = val["a"].asInt() == 1;
if (!anim)
{
KeyFrame kf;
kf.s_val = Float3(val["k"]);
frames.push_back(kf);
return;
}
int n = val["k"].size();
frames.resize(n);
for (int i = 0; i < n; ++i)
{
const Json::Value& src = val["k"][i];
KeyFrame& dst = frames[i];
dst.frame = src["t"].asInt();
if (src.isMember("s")) {
dst.s_val = Float3(src["s"]);
}
if (src.isMember("e")) {
dst.e_val = Float3(src["e"]);
if (i != n - 1) {
frames[i + 1].s_val = dst.e_val;
}
}
if (src.isMember("i")) {
assert(src["i"].isMember("x") && src["i"].isMember("y"));
dst.ix = Float3(src["i"]["x"]);
dst.iy = Float3(src["i"]["y"]);
}
if (src.isMember("o")) {
assert(src["o"].isMember("x") && src["o"].isMember("y"));
dst.ox = Float3(src["o"]["x"]);
dst.oy = Float3(src["o"]["y"]);
}
if (src.isMember("ti")) {
dst.ti = Float3(src["ti"]);
}
if (src.isMember("to")) {
dst.to = Float3(src["to"]);
}
}
#ifndef NDEBUG
if (n > 1) {
for (int i = 0; i < n - 1; ++i) {
assert(frames[i].e_val == frames[i + 1].s_val);
}
}
#endif // NDEBUG
}
/************************************************************************/
/* class BodymovinParser::Transform */
/************************************************************************/
BodymovinParser::Transform::Transform()
{
}
void BodymovinParser::Transform::Load(const Json::Value& val)
{
if (val.isMember("a")) {
anchor.Load(val["a"]);
}
if (val.isMember("o")) {
opacity.Load(val["o"]);
}
if (val.isMember("p")) {
position.Load(val["p"]);
}
if (val.isMember("r")) {
rotate.Load(val["r"]);
}
if (val.isMember("s")) {
scale.Load(val["s"]);
}
}
/************************************************************************/
/* class BodymovinParser::Layer */
/************************************************************************/
BodymovinParser::Layer::Layer()
{
}
bool BodymovinParser::Layer::Load(const Json::Value& val)
{
name = val["nm"].asString();
ref_id = val["refId"].asString();
layer_id = val["ind"].asInt();
layer_type = val["ty"].asInt();
switch (layer_type)
{
case LAYER_PRE_COMP:
comp_width = val["w"].asInt();
comp_height = val["h"].asInt();
break;
case LAYER_SOLID:
// todo: not support mask now
if (val.isMember("hasMask") && val["hasMask"].asBool()) {
return false;
}
solid_width = val["sw"].asInt();
solid_height = val["sh"].asInt();
solid_color = val["sc"].asString();
break;
}
if (val.isMember("parent")) {
parent_id = val["parent"].asInt();
} else {
parent_id = -1;
}
cl = val["cl"].asString();
float time_stretch = 1;
if (val.isMember("sr")) {
time_stretch = val["sr"].asDouble();
}
in_frame = val["ip"].asDouble() / time_stretch;
out_frame = val["op"].asDouble() / time_stretch;
start_frame = val["st"].asInt();
auto_ori = val["ao"].asInt();
blend_mode = val["bm"].asInt();
trans.Load(val["ks"]);
return true;
}
}<|endoftext|> |
<commit_before><commit_msg>Fix the offical build by passing local state to the initialize metrics function.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/url_info.h"
#include <math.h>
#include <algorithm>
#include <string>
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/stringprintf.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
namespace chrome_browser_net {
static bool detailed_logging_enabled = false;
// Use command line switch to enable detailed logging.
void EnablePredictorDetailedLog(bool enable) {
detailed_logging_enabled = enable;
}
// static
int UrlInfo::sequence_counter = 1;
UrlInfo::UrlInfo()
: state_(PENDING),
old_prequeue_state_(state_),
resolve_duration_(kNullDuration),
queue_duration_(kNullDuration),
sequence_number_(0),
motivation_(NO_PREFETCH_MOTIVATION),
was_linked_(false) {
}
UrlInfo::~UrlInfo() {}
bool UrlInfo::NeedsDnsUpdate() {
switch (state_) {
case PENDING: // Just now created info.
return true;
case QUEUED: // In queue.
case ASSIGNED: // It's being resolved.
case ASSIGNED_BUT_MARKED: // It's being resolved.
return false; // We're already working on it
case NO_SUCH_NAME: // Lookup failed.
case FOUND: // Lookup succeeded.
return !IsStillCached(); // See if DNS cache expired.
default:
NOTREACHED();
return false;
}
}
const TimeDelta UrlInfo::kNullDuration(TimeDelta::FromMilliseconds(-1));
// Common low end TTL for sites is 5 minutes. However, DNS servers give us
// the remaining time, not the original 5 minutes. Hence it doesn't much matter
// whether we found something in the local cache, or an ISP cache, it will
// on average be 2.5 minutes before it expires. We could try to model this with
// 180 seconds, but simpler is just to do the lookups all the time (wasting
// OS calls(?)), and let that OS cache decide what to do (with TTL in hand).
// We use a small time to help get some duplicate suppression, in case a page
// has a TON of copies of the same domain name, so that we don't thrash the OS
// to death. Hopefully it is small enough that we're not hurting our cache hit
// rate (i.e., we could always ask the OS).
TimeDelta UrlInfo::cache_expiration_duration_(TimeDelta::FromSeconds(5));
const TimeDelta UrlInfo::kMaxNonNetworkDnsLookupDuration(
TimeDelta::FromMilliseconds(15));
// Used by test ONLY. The value is otherwise constant.
// static
void UrlInfo::set_cache_expiration(TimeDelta time) {
cache_expiration_duration_ = time;
}
// static
TimeDelta UrlInfo::get_cache_expiration() {
return cache_expiration_duration_;
}
void UrlInfo::SetQueuedState(ResolutionMotivation motivation) {
DCHECK(PENDING == state_ || FOUND == state_ || NO_SUCH_NAME == state_);
old_prequeue_state_ = state_;
state_ = QUEUED;
queue_duration_ = resolve_duration_ = kNullDuration;
SetMotivation(motivation);
GetDuration(); // Set time_
DLogResultsStats("DNS Prefetch in queue");
}
void UrlInfo::SetAssignedState() {
DCHECK(QUEUED == state_);
state_ = ASSIGNED;
queue_duration_ = GetDuration();
DLogResultsStats("DNS Prefetch assigned");
UMA_HISTOGRAM_TIMES("DNS.PrefetchQueue", queue_duration_);
}
void UrlInfo::RemoveFromQueue() {
DCHECK(ASSIGNED == state_);
state_ = old_prequeue_state_;
DLogResultsStats("DNS Prefetch reset to prequeue");
static const TimeDelta kBoundary = TimeDelta::FromSeconds(2);
if (queue_duration_ > kBoundary) {
UMA_HISTOGRAM_MEDIUM_TIMES("DNS.QueueRecycledDeltaOver2",
queue_duration_ - kBoundary);
return;
}
// Make a custom linear histogram for the region from 0 to boundary.
const size_t kBucketCount = 52;
static base::Histogram* histogram(NULL);
if (!histogram)
histogram = base::LinearHistogram::FactoryTimeGet(
"DNS.QueueRecycledUnder2", TimeDelta(), kBoundary, kBucketCount,
base::Histogram::kUmaTargetedHistogramFlag);
histogram->AddTime(queue_duration_);
}
void UrlInfo::SetPendingDeleteState() {
DCHECK(ASSIGNED == state_ || ASSIGNED_BUT_MARKED == state_);
state_ = ASSIGNED_BUT_MARKED;
}
void UrlInfo::SetFoundState() {
DCHECK(ASSIGNED == state_);
state_ = FOUND;
resolve_duration_ = GetDuration();
if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) {
UMA_HISTOGRAM_CUSTOM_TIMES("DNS.PrefetchResolution", resolve_duration_,
kMaxNonNetworkDnsLookupDuration, TimeDelta::FromMinutes(15), 100);
}
sequence_number_ = sequence_counter++;
DLogResultsStats("DNS PrefetchFound");
}
void UrlInfo::SetNoSuchNameState() {
DCHECK(ASSIGNED == state_);
state_ = NO_SUCH_NAME;
resolve_duration_ = GetDuration();
if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) {
DHISTOGRAM_TIMES("DNS.PrefetchNotFoundName", resolve_duration_);
}
sequence_number_ = sequence_counter++;
DLogResultsStats("DNS PrefetchNotFound");
}
void UrlInfo::SetUrl(const GURL& url) {
if (url_.is_empty()) // Not yet initialized.
url_ = url;
else
DCHECK_EQ(url_, url);
}
// IsStillCached() guesses if the DNS cache still has IP data,
// or at least remembers results about "not finding host."
bool UrlInfo::IsStillCached() const {
DCHECK(FOUND == state_ || NO_SUCH_NAME == state_);
// Default MS OS does not cache failures. Hence we could return false almost
// all the time for that case. However, we'd never try again to prefetch
// the value if we returned false that way. Hence we'll just let the lookup
// time out the same way as FOUND case.
if (sequence_counter - sequence_number_ > kMaxGuaranteedDnsCacheSize)
return false;
TimeDelta time_since_resolution = TimeTicks::Now() - time_;
return time_since_resolution < cache_expiration_duration_;
}
void UrlInfo::DLogResultsStats(const char* message) const {
if (!detailed_logging_enabled)
return;
DVLOG(1) << "\t" << message << "\tq=" << queue_duration().InMilliseconds()
<< "ms,\tr=" << resolve_duration().InMilliseconds()
<< "ms,\tp=" << sequence_number_ << "\t" << url_.spec();
}
//------------------------------------------------------------------------------
// This last section supports HTML output, such as seen in about:dns.
//------------------------------------------------------------------------------
// Preclude any possibility of Java Script or markup in the text, by only
// allowing alphanumerics, '.', '-', ':', and whitespace.
static std::string RemoveJs(const std::string& text) {
std::string output(text);
size_t length = output.length();
for (size_t i = 0; i < length; i++) {
char next = output[i];
if (isalnum(next) || isspace(next) || strchr(".-:/", next) != NULL)
continue;
output[i] = '?';
}
return output;
}
class MinMaxAverage {
public:
MinMaxAverage()
: sum_(0), square_sum_(0), count_(0),
minimum_(kint64max), maximum_(kint64min) {
}
// Return values for use in printf formatted as "%d"
int sample(int64 value) {
sum_ += value;
square_sum_ += value * value;
count_++;
minimum_ = std::min(minimum_, value);
maximum_ = std::max(maximum_, value);
return static_cast<int>(value);
}
int minimum() const { return static_cast<int>(minimum_); }
int maximum() const { return static_cast<int>(maximum_); }
int average() const { return static_cast<int>(sum_/count_); }
int sum() const { return static_cast<int>(sum_); }
int standard_deviation() const {
double average = static_cast<float>(sum_) / count_;
double variance = static_cast<float>(square_sum_)/count_
- average * average;
return static_cast<int>(floor(sqrt(variance) + .5));
}
private:
int64 sum_;
int64 square_sum_;
int count_;
int64 minimum_;
int64 maximum_;
// DISALLOW_COPY_AND_ASSIGN(MinMaxAverage);
};
static std::string HoursMinutesSeconds(int seconds) {
std::string result;
int print_seconds = seconds % 60;
int minutes = seconds / 60;
int print_minutes = minutes % 60;
int print_hours = minutes/60;
if (print_hours)
base::StringAppendF(&result, "%.2d:", print_hours);
if (print_hours || print_minutes)
base::StringAppendF(&result, "%2.2d:", print_minutes);
base::StringAppendF(&result, "%2.2d", print_seconds);
return result;
}
// static
void UrlInfo::GetHtmlTable(const UrlInfoTable& host_infos,
const char* description,
bool brief,
std::string* output) {
if (0 == host_infos.size())
return;
output->append(description);
base::StringAppendF(output, "%" PRIuS " %s", host_infos.size(),
(1 == host_infos.size()) ? "hostname" : "hostnames");
if (brief) {
output->append("<br><br>");
return;
}
output->append("<br><table border=1>"
"<tr><th>Host name</th>"
"<th>How long ago<br>(HH:MM:SS)</th>"
"<th>Motivation</th>"
"</tr>");
const char* row_format = "<tr align=right><td>%s</td>" // Host name.
"<td>%s</td>" // How long ago.
"<td>%s</td>" // Motivation.
"</tr>";
// Print bulk of table, and gather stats at same time.
MinMaxAverage queue, when;
TimeTicks current_time = TimeTicks::Now();
for (UrlInfoTable::const_iterator it(host_infos.begin());
it != host_infos.end(); it++) {
queue.sample((it->queue_duration_.InMilliseconds()));
base::StringAppendF(
output,
row_format,
RemoveJs(it->url_.spec()).c_str(),
HoursMinutesSeconds(when.sample(
(current_time - it->time_).InSeconds())).c_str(),
it->GetAsciiMotivation().c_str());
}
output->append("</table>");
#ifndef NDEBUG
base::StringAppendF(
output,
"Prefetch Queue Durations: min=%d, avg=%d, max=%d<br><br>",
queue.minimum(), queue.average(), queue.maximum());
#endif
output->append("<br>");
}
void UrlInfo::SetMotivation(ResolutionMotivation motivation) {
motivation_ = motivation;
if (motivation < LINKED_MAX_MOTIVATED)
was_linked_ = true;
}
std::string UrlInfo::GetAsciiMotivation() const {
switch (motivation_) {
case MOUSE_OVER_MOTIVATED:
return "[mouse-over]";
case PAGE_SCAN_MOTIVATED:
return "[page scan]";
case OMNIBOX_MOTIVATED:
return "[omnibox]";
case STARTUP_LIST_MOTIVATED:
return "[startup list]";
case NO_PREFETCH_MOTIVATION:
return "n/a";
case STATIC_REFERAL_MOTIVATED:
return RemoveJs(referring_url_.spec()) + "*";
case LEARNED_REFERAL_MOTIVATED:
return RemoveJs(referring_url_.spec());
default:
return "";
}
}
} // namespace chrome_browser_net
<commit_msg>Towards an android build of "browser".<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 "chrome/browser/net/url_info.h"
#include <ctype.h>
#include <math.h>
#include <algorithm>
#include <string>
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/stringprintf.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
namespace chrome_browser_net {
static bool detailed_logging_enabled = false;
// Use command line switch to enable detailed logging.
void EnablePredictorDetailedLog(bool enable) {
detailed_logging_enabled = enable;
}
// static
int UrlInfo::sequence_counter = 1;
UrlInfo::UrlInfo()
: state_(PENDING),
old_prequeue_state_(state_),
resolve_duration_(kNullDuration),
queue_duration_(kNullDuration),
sequence_number_(0),
motivation_(NO_PREFETCH_MOTIVATION),
was_linked_(false) {
}
UrlInfo::~UrlInfo() {}
bool UrlInfo::NeedsDnsUpdate() {
switch (state_) {
case PENDING: // Just now created info.
return true;
case QUEUED: // In queue.
case ASSIGNED: // It's being resolved.
case ASSIGNED_BUT_MARKED: // It's being resolved.
return false; // We're already working on it
case NO_SUCH_NAME: // Lookup failed.
case FOUND: // Lookup succeeded.
return !IsStillCached(); // See if DNS cache expired.
default:
NOTREACHED();
return false;
}
}
const TimeDelta UrlInfo::kNullDuration(TimeDelta::FromMilliseconds(-1));
// Common low end TTL for sites is 5 minutes. However, DNS servers give us
// the remaining time, not the original 5 minutes. Hence it doesn't much matter
// whether we found something in the local cache, or an ISP cache, it will
// on average be 2.5 minutes before it expires. We could try to model this with
// 180 seconds, but simpler is just to do the lookups all the time (wasting
// OS calls(?)), and let that OS cache decide what to do (with TTL in hand).
// We use a small time to help get some duplicate suppression, in case a page
// has a TON of copies of the same domain name, so that we don't thrash the OS
// to death. Hopefully it is small enough that we're not hurting our cache hit
// rate (i.e., we could always ask the OS).
TimeDelta UrlInfo::cache_expiration_duration_(TimeDelta::FromSeconds(5));
const TimeDelta UrlInfo::kMaxNonNetworkDnsLookupDuration(
TimeDelta::FromMilliseconds(15));
// Used by test ONLY. The value is otherwise constant.
// static
void UrlInfo::set_cache_expiration(TimeDelta time) {
cache_expiration_duration_ = time;
}
// static
TimeDelta UrlInfo::get_cache_expiration() {
return cache_expiration_duration_;
}
void UrlInfo::SetQueuedState(ResolutionMotivation motivation) {
DCHECK(PENDING == state_ || FOUND == state_ || NO_SUCH_NAME == state_);
old_prequeue_state_ = state_;
state_ = QUEUED;
queue_duration_ = resolve_duration_ = kNullDuration;
SetMotivation(motivation);
GetDuration(); // Set time_
DLogResultsStats("DNS Prefetch in queue");
}
void UrlInfo::SetAssignedState() {
DCHECK(QUEUED == state_);
state_ = ASSIGNED;
queue_duration_ = GetDuration();
DLogResultsStats("DNS Prefetch assigned");
UMA_HISTOGRAM_TIMES("DNS.PrefetchQueue", queue_duration_);
}
void UrlInfo::RemoveFromQueue() {
DCHECK(ASSIGNED == state_);
state_ = old_prequeue_state_;
DLogResultsStats("DNS Prefetch reset to prequeue");
static const TimeDelta kBoundary = TimeDelta::FromSeconds(2);
if (queue_duration_ > kBoundary) {
UMA_HISTOGRAM_MEDIUM_TIMES("DNS.QueueRecycledDeltaOver2",
queue_duration_ - kBoundary);
return;
}
// Make a custom linear histogram for the region from 0 to boundary.
const size_t kBucketCount = 52;
static base::Histogram* histogram(NULL);
if (!histogram)
histogram = base::LinearHistogram::FactoryTimeGet(
"DNS.QueueRecycledUnder2", TimeDelta(), kBoundary, kBucketCount,
base::Histogram::kUmaTargetedHistogramFlag);
histogram->AddTime(queue_duration_);
}
void UrlInfo::SetPendingDeleteState() {
DCHECK(ASSIGNED == state_ || ASSIGNED_BUT_MARKED == state_);
state_ = ASSIGNED_BUT_MARKED;
}
void UrlInfo::SetFoundState() {
DCHECK(ASSIGNED == state_);
state_ = FOUND;
resolve_duration_ = GetDuration();
if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) {
UMA_HISTOGRAM_CUSTOM_TIMES("DNS.PrefetchResolution", resolve_duration_,
kMaxNonNetworkDnsLookupDuration, TimeDelta::FromMinutes(15), 100);
}
sequence_number_ = sequence_counter++;
DLogResultsStats("DNS PrefetchFound");
}
void UrlInfo::SetNoSuchNameState() {
DCHECK(ASSIGNED == state_);
state_ = NO_SUCH_NAME;
resolve_duration_ = GetDuration();
if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) {
DHISTOGRAM_TIMES("DNS.PrefetchNotFoundName", resolve_duration_);
}
sequence_number_ = sequence_counter++;
DLogResultsStats("DNS PrefetchNotFound");
}
void UrlInfo::SetUrl(const GURL& url) {
if (url_.is_empty()) // Not yet initialized.
url_ = url;
else
DCHECK_EQ(url_, url);
}
// IsStillCached() guesses if the DNS cache still has IP data,
// or at least remembers results about "not finding host."
bool UrlInfo::IsStillCached() const {
DCHECK(FOUND == state_ || NO_SUCH_NAME == state_);
// Default MS OS does not cache failures. Hence we could return false almost
// all the time for that case. However, we'd never try again to prefetch
// the value if we returned false that way. Hence we'll just let the lookup
// time out the same way as FOUND case.
if (sequence_counter - sequence_number_ > kMaxGuaranteedDnsCacheSize)
return false;
TimeDelta time_since_resolution = TimeTicks::Now() - time_;
return time_since_resolution < cache_expiration_duration_;
}
void UrlInfo::DLogResultsStats(const char* message) const {
if (!detailed_logging_enabled)
return;
DVLOG(1) << "\t" << message << "\tq=" << queue_duration().InMilliseconds()
<< "ms,\tr=" << resolve_duration().InMilliseconds()
<< "ms,\tp=" << sequence_number_ << "\t" << url_.spec();
}
//------------------------------------------------------------------------------
// This last section supports HTML output, such as seen in about:dns.
//------------------------------------------------------------------------------
// Preclude any possibility of Java Script or markup in the text, by only
// allowing alphanumerics, '.', '-', ':', and whitespace.
static std::string RemoveJs(const std::string& text) {
std::string output(text);
size_t length = output.length();
for (size_t i = 0; i < length; i++) {
char next = output[i];
if (isalnum(next) || isspace(next) || strchr(".-:/", next) != NULL)
continue;
output[i] = '?';
}
return output;
}
class MinMaxAverage {
public:
MinMaxAverage()
: sum_(0), square_sum_(0), count_(0),
minimum_(kint64max), maximum_(kint64min) {
}
// Return values for use in printf formatted as "%d"
int sample(int64 value) {
sum_ += value;
square_sum_ += value * value;
count_++;
minimum_ = std::min(minimum_, value);
maximum_ = std::max(maximum_, value);
return static_cast<int>(value);
}
int minimum() const { return static_cast<int>(minimum_); }
int maximum() const { return static_cast<int>(maximum_); }
int average() const { return static_cast<int>(sum_/count_); }
int sum() const { return static_cast<int>(sum_); }
int standard_deviation() const {
double average = static_cast<float>(sum_) / count_;
double variance = static_cast<float>(square_sum_)/count_
- average * average;
return static_cast<int>(floor(sqrt(variance) + .5));
}
private:
int64 sum_;
int64 square_sum_;
int count_;
int64 minimum_;
int64 maximum_;
// DISALLOW_COPY_AND_ASSIGN(MinMaxAverage);
};
static std::string HoursMinutesSeconds(int seconds) {
std::string result;
int print_seconds = seconds % 60;
int minutes = seconds / 60;
int print_minutes = minutes % 60;
int print_hours = minutes/60;
if (print_hours)
base::StringAppendF(&result, "%.2d:", print_hours);
if (print_hours || print_minutes)
base::StringAppendF(&result, "%2.2d:", print_minutes);
base::StringAppendF(&result, "%2.2d", print_seconds);
return result;
}
// static
void UrlInfo::GetHtmlTable(const UrlInfoTable& host_infos,
const char* description,
bool brief,
std::string* output) {
if (0 == host_infos.size())
return;
output->append(description);
base::StringAppendF(output, "%" PRIuS " %s", host_infos.size(),
(1 == host_infos.size()) ? "hostname" : "hostnames");
if (brief) {
output->append("<br><br>");
return;
}
output->append("<br><table border=1>"
"<tr><th>Host name</th>"
"<th>How long ago<br>(HH:MM:SS)</th>"
"<th>Motivation</th>"
"</tr>");
const char* row_format = "<tr align=right><td>%s</td>" // Host name.
"<td>%s</td>" // How long ago.
"<td>%s</td>" // Motivation.
"</tr>";
// Print bulk of table, and gather stats at same time.
MinMaxAverage queue, when;
TimeTicks current_time = TimeTicks::Now();
for (UrlInfoTable::const_iterator it(host_infos.begin());
it != host_infos.end(); it++) {
queue.sample((it->queue_duration_.InMilliseconds()));
base::StringAppendF(
output,
row_format,
RemoveJs(it->url_.spec()).c_str(),
HoursMinutesSeconds(when.sample(
(current_time - it->time_).InSeconds())).c_str(),
it->GetAsciiMotivation().c_str());
}
output->append("</table>");
#ifndef NDEBUG
base::StringAppendF(
output,
"Prefetch Queue Durations: min=%d, avg=%d, max=%d<br><br>",
queue.minimum(), queue.average(), queue.maximum());
#endif
output->append("<br>");
}
void UrlInfo::SetMotivation(ResolutionMotivation motivation) {
motivation_ = motivation;
if (motivation < LINKED_MAX_MOTIVATED)
was_linked_ = true;
}
std::string UrlInfo::GetAsciiMotivation() const {
switch (motivation_) {
case MOUSE_OVER_MOTIVATED:
return "[mouse-over]";
case PAGE_SCAN_MOTIVATED:
return "[page scan]";
case OMNIBOX_MOTIVATED:
return "[omnibox]";
case STARTUP_LIST_MOTIVATED:
return "[startup list]";
case NO_PREFETCH_MOTIVATION:
return "n/a";
case STATIC_REFERAL_MOTIVATED:
return RemoveJs(referring_url_.spec()) + "*";
case LEARNED_REFERAL_MOTIVATED:
return RemoveJs(referring_url_.spec());
default:
return "";
}
}
} // namespace chrome_browser_net
<|endoftext|> |
<commit_before>namespace mant {
namespace bbob2009 {
class BlackBoxOptimisationBenchmark2009 : public OptimisationProblem<double> {
public:
inline explicit BlackBoxOptimisationBenchmark2009(
const unsigned int& numberOfDimensions) noexcept;
virtual ~BlackBoxOptimisationBenchmark2009() = default;
protected:
inline arma::Col<double> getRandomParameterTranslation() const noexcept;
inline arma::Col<double> getParameterConditioning(
const double& conditionNumber) const noexcept;
inline arma::Col<double> getConditionedParameter(
const arma::Col<double>& parameter) const noexcept;
inline arma::Col<double> getAsymmetricParameter(
const double& asymmetry, const arma::Col<double>& parameter) const noexcept;
inline double getOscillatedValue(
const double& oscilliation) const noexcept;
inline arma::Col<double> getOscillatedParameter(
const arma::Col<double>& parameter) const noexcept;
inline double getBoundConstraintsValue(
const arma::Col<double>& parameter) const noexcept;
#if defined(MANTELLA_USE_PARALLEL)
friend class cereal::access;
BlackBoxOptimisationBenchmark2009() = default;
template <typename Archive>
void serialize(
Archive& archive) noexcept {
archive(cereal::make_nvp("optimisationProblem", cereal::base_class<OptimisationProblem>(this)));
}
#endif
};
//
// Implementation
//
inline BlackBoxOptimisationBenchmark2009::BlackBoxOptimisationBenchmark2009(
const unsigned int& numberOfDimensions) noexcept
: OptimisationProblem(numberOfDimensions) {
setLowerBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) - 5.0);
setUpperBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 5.0);
setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::cauchy_distribution<double>(0.0, 100.0)(Rng::getGenerator()))));
setAcceptableObjectiveValue(objectiveValueTranslation_ + 1.0e-8);
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getRandomParameterTranslation() const noexcept {
arma::Col<double> randomParameterTranslation = arma::floor(arma::randu<arma::Col<double>>(numberOfDimensions_) * 1.0e4) / 1.0e4 * 8.0 - 4.0;
randomParameterTranslation.elem(arma::find(randomParameterTranslation == 0)).fill(-1.0e5);
return randomParameterTranslation;
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getParameterConditioning(
const double& conditionNumber) const noexcept {
arma::Col<double> parameterConditioning = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_);
for (auto& conditioning : parameterConditioning) {
conditioning = std::pow(conditionNumber, conditioning);
}
return parameterConditioning;
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getConditionedParameter(
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> conditionedParameter = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_);
for (std::size_t n = 0; n < conditionedParameter.n_elem; ++n) {
conditionedParameter(n) = std::pow(parameter(n), conditionedParameter(n));
}
return conditionedParameter;
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getAsymmetricParameter(
const double& asymmetry,
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> asymmetricParameter(parameter.n_elem);
const arma::Col<double>& spacing = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_);
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
const double& value = parameter(n);
if (value > 0.0) {
asymmetricParameter(n) = std::pow(value, 1 + asymmetry * spacing(n) * std::sqrt(value));
} else {
asymmetricParameter(n) = value;
}
}
return asymmetricParameter;
}
inline double BlackBoxOptimisationBenchmark2009::getOscillatedValue(
const double& value) const noexcept {
if (value != 0.0) {
double c1;
double c2;
if (value > 0.0) {
c1 = 10.0;
c2 = 7.9;
} else {
c1 = 5.5;
c2 = 3.1;
}
const double& logAbsoluteValue = std::log(std::abs(value));
return std::copysign(1.0, value) * std::exp(logAbsoluteValue + 0.049 * (std::sin(c1 * logAbsoluteValue) + std::sin(c2 * logAbsoluteValue)));
} else {
return 0.0;
}
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getOscillatedParameter(
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> oscillatedParameter(parameter.n_elem);
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
oscillatedParameter(n) = getOscillatedValue(parameter(n));
}
return oscillatedParameter;
}
inline double BlackBoxOptimisationBenchmark2009::getBoundConstraintsValue(
const arma::Col<double>& parameter) const noexcept {
double boundConstraintsValue = 0.0;
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
boundConstraintsValue += std::pow(std::max(0.0, std::abs(parameter(n)) - 5.0), 2.0);
}
return boundConstraintsValue;
}
}
}
<commit_msg>Fixed variable not found issue<commit_after>namespace mant {
namespace bbob2009 {
class BlackBoxOptimisationBenchmark2009 : public OptimisationProblem<double> {
public:
inline explicit BlackBoxOptimisationBenchmark2009(
const unsigned int& numberOfDimensions) noexcept;
virtual ~BlackBoxOptimisationBenchmark2009() = default;
protected:
inline arma::Col<double> getRandomParameterTranslation() const noexcept;
inline arma::Col<double> getParameterConditioning(
const double& conditionNumber) const noexcept;
inline arma::Col<double> getConditionedParameter(
const arma::Col<double>& parameter) const noexcept;
inline arma::Col<double> getAsymmetricParameter(
const double& asymmetry, const arma::Col<double>& parameter) const noexcept;
inline double getOscillatedValue(
const double& oscilliation) const noexcept;
inline arma::Col<double> getOscillatedParameter(
const arma::Col<double>& parameter) const noexcept;
inline double getBoundConstraintsValue(
const arma::Col<double>& parameter) const noexcept;
#if defined(MANTELLA_USE_PARALLEL)
friend class cereal::access;
BlackBoxOptimisationBenchmark2009() = default;
template <typename Archive>
void serialize(
Archive& archive) noexcept {
archive(cereal::make_nvp("optimisationProblem", cereal::base_class<OptimisationProblem>(this)));
}
#endif
};
//
// Implementation
//
inline BlackBoxOptimisationBenchmark2009::BlackBoxOptimisationBenchmark2009(
const unsigned int& numberOfDimensions) noexcept
: OptimisationProblem(numberOfDimensions) {
setLowerBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) - 5.0);
setUpperBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 5.0);
setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::cauchy_distribution<double>(0.0, 100.0)(Rng::getGenerator()))));
setAcceptableObjectiveValue(objectiveValueTranslation_ + 1.0e-8);
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getRandomParameterTranslation() const noexcept {
arma::Col<double> randomParameterTranslation = arma::floor(arma::randu<arma::Col<double>>(numberOfDimensions_) * 1.0e4) / 1.0e4 * 8.0 - 4.0;
randomParameterTranslation.elem(arma::find(randomParameterTranslation == 0)).fill(-1.0e5);
return randomParameterTranslation;
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getParameterConditioning(
const double& conditionNumber) const noexcept {
arma::Col<double> parameterConditioning = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_);
for (auto& conditioning : parameterConditioning) {
conditioning = std::pow(conditionNumber, conditioning);
}
return parameterConditioning;
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getConditionedParameter(
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> conditionedParameter = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_);
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
conditionedParameter(n) = std::pow(parameter(n), conditionedParameter(n));
}
return conditionedParameter;
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getAsymmetricParameter(
const double& asymmetry,
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> asymmetricParameter(parameter.n_elem);
const arma::Col<double>& spacing = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_);
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
const double& value = parameter(n);
if (value > 0.0) {
asymmetricParameter(n) = std::pow(value, 1 + asymmetry * spacing(n) * std::sqrt(value));
} else {
asymmetricParameter(n) = value;
}
}
return asymmetricParameter;
}
inline double BlackBoxOptimisationBenchmark2009::getOscillatedValue(
const double& value) const noexcept {
if (value != 0.0) {
double c1;
double c2;
if (value > 0.0) {
c1 = 10.0;
c2 = 7.9;
} else {
c1 = 5.5;
c2 = 3.1;
}
const double& logAbsoluteValue = std::log(std::abs(value));
return std::copysign(1.0, value) * std::exp(logAbsoluteValue + 0.049 * (std::sin(c1 * logAbsoluteValue) + std::sin(c2 * logAbsoluteValue)));
} else {
return 0.0;
}
}
inline arma::Col<double> BlackBoxOptimisationBenchmark2009::getOscillatedParameter(
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> oscillatedParameter(parameter.n_elem);
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
oscillatedParameter(n) = getOscillatedValue(parameter(n));
}
return oscillatedParameter;
}
inline double BlackBoxOptimisationBenchmark2009::getBoundConstraintsValue(
const arma::Col<double>& parameter) const noexcept {
double boundConstraintsValue = 0.0;
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
boundConstraintsValue += std::pow(std::max(0.0, std::abs(parameter(n)) - 5.0), 2.0);
}
return boundConstraintsValue;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Re-disable all Worker tests until I can figure out exact set of failing ones. TBR=atwilson Review URL: http://codereview.chromium.org/239004<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Pavel Kirienko <[email protected]>
*/
#ifndef UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_DISTRIBUTED_SERVER_HPP_INCLUDED
#define UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_DISTRIBUTED_SERVER_HPP_INCLUDED
#include <uavcan/build_config.hpp>
#include <uavcan/debug.hpp>
#include <uavcan/protocol/dynamic_node_id_server/distributed/types.hpp>
#include <uavcan/protocol/dynamic_node_id_server/distributed/raft_core.hpp>
#include <uavcan/protocol/dynamic_node_id_server/allocation_request_manager.hpp>
#include <uavcan/protocol/dynamic_node_id_server/node_id_selector.hpp>
#include <uavcan/protocol/dynamic_node_id_server/node_discoverer.hpp>
#include <uavcan/protocol/dynamic_node_id_server/event.hpp>
namespace uavcan
{
namespace dynamic_node_id_server
{
namespace distributed
{
/**
* This class implements the top-level allocation logic and server API.
*/
class UAVCAN_EXPORT Server : IAllocationRequestHandler
, INodeDiscoveryHandler
, IRaftLeaderMonitor
{
struct UniqueIDLogPredicate
{
const UniqueID unique_id;
UniqueIDLogPredicate(const UniqueID& uid)
: unique_id(uid)
{ }
bool operator()(const RaftCore::LogEntryInfo& info) const
{
return info.entry.unique_id == unique_id;
}
};
struct NodeIDLogPredicate
{
const NodeID node_id;
NodeIDLogPredicate(const NodeID& nid)
: node_id(nid)
{ }
bool operator()(const RaftCore::LogEntryInfo& info) const
{
return info.entry.node_id == node_id.get();
}
};
/*
* Constants
*/
UniqueID own_unique_id_;
/*
* States
*/
INode& node_;
IEventTracer& tracer_;
RaftCore raft_core_;
AllocationRequestManager allocation_request_manager_;
NodeDiscoverer node_discoverer_;
/*
* Methods of IAllocationRequestHandler
*/
virtual bool canPublishFollowupAllocationResponse() const
{
/*
* The server is allowed to publish follow-up allocation responses only if both conditions are met:
* - The server is leader.
* - The last allocation request has been completed successfully.
*
* Why second condition? Imagine a case when there's two Raft nodes that don't hear each other - A and B,
* both of them are leaders (but only A can commit to the log, B is in a minor partition); then there's a
* client X that can exchange with both leaders, and a client Y that can exchange only with A. Such a
* situation can occur in case of a very unlikely failure of redundant interfaces.
*
* Both clients X and Y initially send a first-stage Allocation request; A responds to Y with a first-stage
* response, whereas B responds to X. Both X and Y will issue a follow-up second-stage requests, which may
* cause A to mix second-stage Allocation requests from different nodes, leading to reception of an invalid
* unique ID. When both leaders receive full unique IDs (A will receive an invalid one, B will receive a valid
* unique ID of X), only A will be able to make a commit, because B is in a minority. Since both clients were
* unable to receive node ID values in this round, they will try again later.
*
* Now, in order to prevent B from disrupting client-server communication second time around, we introduce this
* second restriction: the server cannot exchange with clients as long as its log contains uncommitted entries.
*
* Note that this restriction does not apply to allocation requests sent via CAN FD frames, as in this case
* no follow-up responses are necessary. So only CAN FD can offer reliable Allocation exchange.
*/
return raft_core_.isLeader() && raft_core_.areAllLogEntriesCommitted();
}
virtual void handleAllocationRequest(const UniqueID& unique_id, const NodeID preferred_node_id)
{
/*
* Note that it is possible that the local node is not leader. We will still perform the log search
* and try to find the node that requested allocation. If the node is found, response will be sent;
* otherwise the request will be ignored because only leader can add new allocations.
*/
const LazyConstructor<RaftCore::LogEntryInfo> result =
raft_core_.traverseLogFromEndUntil(UniqueIDLogPredicate(unique_id));
if (result.isConstructed())
{
if (result->committed)
{
tryPublishAllocationResult(result->entry);
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server",
"Allocation request served with existing allocation; node ID %d",
int(result->entry.node_id));
}
else
{
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server",
"Allocation request ignored - allocation exists but not committed yet; node ID %d",
int(result->entry.node_id));
}
}
else
{
if (raft_core_.isLeader() && !node_discoverer_.hasUnknownNodes())
{
allocateNewNode(unique_id, preferred_node_id);
}
}
}
/*
* Methods of INodeDiscoveryHandler
*/
virtual bool canDiscoverNewNodes() const
{
return raft_core_.isLeader();
}
virtual NodeAwareness checkNodeAwareness(NodeID node_id) const
{
const LazyConstructor<RaftCore::LogEntryInfo> result =
raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_id));
if (result.isConstructed())
{
return result->committed ? NodeAwarenessKnownAndCommitted : NodeAwarenessKnownButNotCommitted;
}
else
{
return NodeAwarenessUnknown;
}
}
virtual void handleNewNodeDiscovery(const UniqueID* unique_id_or_null, NodeID node_id)
{
if (raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_id)).isConstructed())
{
UAVCAN_ASSERT(0); // Such node is already known, the class that called this method should have known that
return;
}
const UniqueID uid = (unique_id_or_null == NULL) ? UniqueID() : *unique_id_or_null;
if (raft_core_.isLeader())
{
raft_core_.appendLog(uid, node_id);
}
}
/*
* Methods of IRaftLeaderMonitor
*/
virtual void handleLogCommitOnLeader(const protocol::dynamic_node_id::server::Entry& entry)
{
/*
* Maybe this node did not request allocation at all, we don't care, we publish anyway.
*/
tryPublishAllocationResult(entry);
}
virtual void handleLocalLeadershipChange(bool local_node_is_leader)
{
if (!local_node_is_leader)
{
return;
}
const LazyConstructor<RaftCore::LogEntryInfo> result =
raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_.getNodeID()));
if (!result.isConstructed())
{
raft_core_.appendLog(own_unique_id_, node_.getNodeID());
}
}
/*
* Private methods
*/
bool isNodeIDTaken(const NodeID node_id) const
{
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server",
"Testing if node ID %d is taken", int(node_id.get()));
return raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_id));
}
void allocateNewNode(const UniqueID& unique_id, const NodeID preferred_node_id)
{
const NodeID allocated_node_id =
NodeIDSelector<Server>(this, &Server::isNodeIDTaken).findFreeNodeID(preferred_node_id);
if (!allocated_node_id.isUnicast())
{
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server", "Request ignored - no free node ID left");
return;
}
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server", "New node ID allocated: %d",
int(allocated_node_id.get()));
raft_core_.appendLog(unique_id, allocated_node_id);
}
void tryPublishAllocationResult(const protocol::dynamic_node_id::server::Entry& entry)
{
const int res = allocation_request_manager_.broadcastAllocationResponse(entry.unique_id, entry.node_id);
if (res < 0)
{
tracer_.onEvent(TraceError, res);
node_.registerInternalFailure("Dynamic allocation final broadcast");
}
}
public:
Server(INode& node,
IStorageBackend& storage,
IEventTracer& tracer)
: node_(node)
, tracer_(tracer)
, raft_core_(node, storage, tracer, *this)
, allocation_request_manager_(node, tracer, *this)
, node_discoverer_(node, tracer, *this)
{ }
int init(const UniqueID& own_unique_id, const uint8_t cluster_size = ClusterManager::ClusterSizeUnknown)
{
/*
* Initializing Raft core first, because the next step requires Log to be loaded
*/
int res = raft_core_.init(cluster_size);
if (res < 0)
{
return res;
}
/*
* Making sure that the server is started with the same node ID
*/
own_unique_id_ = own_unique_id;
const LazyConstructor<RaftCore::LogEntryInfo> own_log_entry =
raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_.getNodeID()));
if (own_log_entry.isConstructed())
{
if (own_log_entry->entry.unique_id != own_unique_id_)
{
return -ErrInvalidConfiguration;
}
}
/*
* Misc
*/
res = allocation_request_manager_.init();
if (res < 0)
{
return res;
}
res = node_discoverer_.init();
if (res < 0)
{
return res;
}
return 0;
}
Log::Index getNumAllocations() const { return raft_core_.getNumAllocations(); }
/**
* These accessors are needed for debugging, visualization and testing.
*/
const RaftCore& getRaftCore() const { return raft_core_; }
const NodeDiscoverer& getNodeDiscoverer() const { return node_discoverer_; }
};
/**
* This structure represents immediate state of the server.
* It can be used for state visualization and debugging.
*/
struct StateReport
{
uint8_t cluster_size;
RaftCore::ServerState state;
Log::Index last_log_index;
Log::Index commit_index;
Term last_log_term;
Term current_term;
NodeID voted_for;
MonotonicTime last_activity_timestamp;
MonotonicDuration randomized_timeout;
uint8_t num_unknown_nodes;
struct FollowerState
{
NodeID node_id;
Log::Index next_index;
Log::Index match_index;
FollowerState()
: next_index(0)
, match_index(0)
{ }
} followers[ClusterManager::MaxClusterSize - 1];
StateReport(const Server& s)
: cluster_size (s.getRaftCore().getClusterManager().getClusterSize())
, state (s.getRaftCore().getServerState())
, last_log_index (s.getRaftCore().getPersistentState().getLog().getLastIndex())
, commit_index (s.getRaftCore().getCommitIndex())
, last_log_term (0) // See below
, current_term (s.getRaftCore().getPersistentState().getCurrentTerm())
, voted_for (s.getRaftCore().getPersistentState().getVotedFor())
, last_activity_timestamp(s.getRaftCore().getLastActivityTimestamp())
, randomized_timeout (s.getRaftCore().getRandomizedTimeout())
, num_unknown_nodes (s.getNodeDiscoverer().getNumUnknownNodes())
{
const Entry* const e = s.getRaftCore().getPersistentState().getLog().getEntryAtIndex(last_log_index);
UAVCAN_ASSERT(e != NULL);
if (e != NULL)
{
last_log_term = e->term;
}
for (uint8_t i = 0; i < (cluster_size - 1U); i++)
{
const ClusterManager& mgr = s.getRaftCore().getClusterManager();
const NodeID node_id = mgr.getRemoteServerNodeIDAtIndex(i);
if (node_id.isUnicast())
{
followers[i].node_id = node_id;
followers[i].next_index = mgr.getServerNextIndex(node_id);
followers[i].match_index = mgr.getServerMatchIndex(node_id);
}
}
}
};
}
}
}
#endif // Include guard
<commit_msg>Distributed server logging fix<commit_after>/*
* Copyright (C) 2015 Pavel Kirienko <[email protected]>
*/
#ifndef UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_DISTRIBUTED_SERVER_HPP_INCLUDED
#define UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_DISTRIBUTED_SERVER_HPP_INCLUDED
#include <uavcan/build_config.hpp>
#include <uavcan/debug.hpp>
#include <uavcan/protocol/dynamic_node_id_server/distributed/types.hpp>
#include <uavcan/protocol/dynamic_node_id_server/distributed/raft_core.hpp>
#include <uavcan/protocol/dynamic_node_id_server/allocation_request_manager.hpp>
#include <uavcan/protocol/dynamic_node_id_server/node_id_selector.hpp>
#include <uavcan/protocol/dynamic_node_id_server/node_discoverer.hpp>
#include <uavcan/protocol/dynamic_node_id_server/event.hpp>
namespace uavcan
{
namespace dynamic_node_id_server
{
namespace distributed
{
/**
* This class implements the top-level allocation logic and server API.
*/
class UAVCAN_EXPORT Server : IAllocationRequestHandler
, INodeDiscoveryHandler
, IRaftLeaderMonitor
{
struct UniqueIDLogPredicate
{
const UniqueID unique_id;
UniqueIDLogPredicate(const UniqueID& uid)
: unique_id(uid)
{ }
bool operator()(const RaftCore::LogEntryInfo& info) const
{
return info.entry.unique_id == unique_id;
}
};
struct NodeIDLogPredicate
{
const NodeID node_id;
NodeIDLogPredicate(const NodeID& nid)
: node_id(nid)
{ }
bool operator()(const RaftCore::LogEntryInfo& info) const
{
return info.entry.node_id == node_id.get();
}
};
/*
* Constants
*/
UniqueID own_unique_id_;
/*
* States
*/
INode& node_;
IEventTracer& tracer_;
RaftCore raft_core_;
AllocationRequestManager allocation_request_manager_;
NodeDiscoverer node_discoverer_;
/*
* Methods of IAllocationRequestHandler
*/
virtual bool canPublishFollowupAllocationResponse() const
{
/*
* The server is allowed to publish follow-up allocation responses only if both conditions are met:
* - The server is leader.
* - The last allocation request has been completed successfully.
*
* Why second condition? Imagine a case when there's two Raft nodes that don't hear each other - A and B,
* both of them are leaders (but only A can commit to the log, B is in a minor partition); then there's a
* client X that can exchange with both leaders, and a client Y that can exchange only with A. Such a
* situation can occur in case of a very unlikely failure of redundant interfaces.
*
* Both clients X and Y initially send a first-stage Allocation request; A responds to Y with a first-stage
* response, whereas B responds to X. Both X and Y will issue a follow-up second-stage requests, which may
* cause A to mix second-stage Allocation requests from different nodes, leading to reception of an invalid
* unique ID. When both leaders receive full unique IDs (A will receive an invalid one, B will receive a valid
* unique ID of X), only A will be able to make a commit, because B is in a minority. Since both clients were
* unable to receive node ID values in this round, they will try again later.
*
* Now, in order to prevent B from disrupting client-server communication second time around, we introduce this
* second restriction: the server cannot exchange with clients as long as its log contains uncommitted entries.
*
* Note that this restriction does not apply to allocation requests sent via CAN FD frames, as in this case
* no follow-up responses are necessary. So only CAN FD can offer reliable Allocation exchange.
*/
return raft_core_.isLeader() && raft_core_.areAllLogEntriesCommitted();
}
virtual void handleAllocationRequest(const UniqueID& unique_id, const NodeID preferred_node_id)
{
/*
* Note that it is possible that the local node is not leader. We will still perform the log search
* and try to find the node that requested allocation. If the node is found, response will be sent;
* otherwise the request will be ignored because only leader can add new allocations.
*/
const LazyConstructor<RaftCore::LogEntryInfo> result =
raft_core_.traverseLogFromEndUntil(UniqueIDLogPredicate(unique_id));
if (result.isConstructed())
{
if (result->committed)
{
tryPublishAllocationResult(result->entry);
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server",
"Allocation request served with existing allocation; node ID %d",
int(result->entry.node_id));
}
else
{
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server",
"Allocation request ignored - allocation exists but not committed yet; node ID %d",
int(result->entry.node_id));
}
}
else
{
if (raft_core_.isLeader() && !node_discoverer_.hasUnknownNodes())
{
allocateNewNode(unique_id, preferred_node_id);
}
}
}
/*
* Methods of INodeDiscoveryHandler
*/
virtual bool canDiscoverNewNodes() const
{
return raft_core_.isLeader();
}
virtual NodeAwareness checkNodeAwareness(NodeID node_id) const
{
const LazyConstructor<RaftCore::LogEntryInfo> result =
raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_id));
if (result.isConstructed())
{
return result->committed ? NodeAwarenessKnownAndCommitted : NodeAwarenessKnownButNotCommitted;
}
else
{
return NodeAwarenessUnknown;
}
}
virtual void handleNewNodeDiscovery(const UniqueID* unique_id_or_null, NodeID node_id)
{
if (raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_id)).isConstructed())
{
UAVCAN_ASSERT(0); // Such node is already known, the class that called this method should have known that
return;
}
const UniqueID uid = (unique_id_or_null == NULL) ? UniqueID() : *unique_id_or_null;
if (raft_core_.isLeader())
{
raft_core_.appendLog(uid, node_id);
}
}
/*
* Methods of IRaftLeaderMonitor
*/
virtual void handleLogCommitOnLeader(const protocol::dynamic_node_id::server::Entry& entry)
{
/*
* Maybe this node did not request allocation at all, we don't care, we publish anyway.
*/
tryPublishAllocationResult(entry);
}
virtual void handleLocalLeadershipChange(bool local_node_is_leader)
{
if (!local_node_is_leader)
{
return;
}
const LazyConstructor<RaftCore::LogEntryInfo> result =
raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_.getNodeID()));
if (!result.isConstructed())
{
raft_core_.appendLog(own_unique_id_, node_.getNodeID());
}
}
/*
* Private methods
*/
bool isNodeIDTaken(const NodeID node_id) const
{
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server",
"Testing if node ID %d is taken", int(node_id.get()));
return raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_id));
}
void allocateNewNode(const UniqueID& unique_id, const NodeID preferred_node_id)
{
const NodeID allocated_node_id =
NodeIDSelector<Server>(this, &Server::isNodeIDTaken).findFreeNodeID(preferred_node_id);
if (!allocated_node_id.isUnicast())
{
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server", "Request ignored - no free node ID left");
return;
}
UAVCAN_TRACE("dynamic_node_id_server::distributed::Server", "New node ID allocated: %d",
int(allocated_node_id.get()));
raft_core_.appendLog(unique_id, allocated_node_id);
}
void tryPublishAllocationResult(const protocol::dynamic_node_id::server::Entry& entry)
{
const int res = allocation_request_manager_.broadcastAllocationResponse(entry.unique_id, entry.node_id);
if (res < 0)
{
tracer_.onEvent(TraceError, res);
node_.registerInternalFailure("Dynamic allocation response");
}
}
public:
Server(INode& node,
IStorageBackend& storage,
IEventTracer& tracer)
: node_(node)
, tracer_(tracer)
, raft_core_(node, storage, tracer, *this)
, allocation_request_manager_(node, tracer, *this)
, node_discoverer_(node, tracer, *this)
{ }
int init(const UniqueID& own_unique_id, const uint8_t cluster_size = ClusterManager::ClusterSizeUnknown)
{
/*
* Initializing Raft core first, because the next step requires Log to be loaded
*/
int res = raft_core_.init(cluster_size);
if (res < 0)
{
return res;
}
/*
* Making sure that the server is started with the same node ID
*/
own_unique_id_ = own_unique_id;
const LazyConstructor<RaftCore::LogEntryInfo> own_log_entry =
raft_core_.traverseLogFromEndUntil(NodeIDLogPredicate(node_.getNodeID()));
if (own_log_entry.isConstructed())
{
if (own_log_entry->entry.unique_id != own_unique_id_)
{
return -ErrInvalidConfiguration;
}
}
/*
* Misc
*/
res = allocation_request_manager_.init();
if (res < 0)
{
return res;
}
res = node_discoverer_.init();
if (res < 0)
{
return res;
}
return 0;
}
Log::Index getNumAllocations() const { return raft_core_.getNumAllocations(); }
/**
* These accessors are needed for debugging, visualization and testing.
*/
const RaftCore& getRaftCore() const { return raft_core_; }
const NodeDiscoverer& getNodeDiscoverer() const { return node_discoverer_; }
};
/**
* This structure represents immediate state of the server.
* It can be used for state visualization and debugging.
*/
struct StateReport
{
uint8_t cluster_size;
RaftCore::ServerState state;
Log::Index last_log_index;
Log::Index commit_index;
Term last_log_term;
Term current_term;
NodeID voted_for;
MonotonicTime last_activity_timestamp;
MonotonicDuration randomized_timeout;
uint8_t num_unknown_nodes;
struct FollowerState
{
NodeID node_id;
Log::Index next_index;
Log::Index match_index;
FollowerState()
: next_index(0)
, match_index(0)
{ }
} followers[ClusterManager::MaxClusterSize - 1];
StateReport(const Server& s)
: cluster_size (s.getRaftCore().getClusterManager().getClusterSize())
, state (s.getRaftCore().getServerState())
, last_log_index (s.getRaftCore().getPersistentState().getLog().getLastIndex())
, commit_index (s.getRaftCore().getCommitIndex())
, last_log_term (0) // See below
, current_term (s.getRaftCore().getPersistentState().getCurrentTerm())
, voted_for (s.getRaftCore().getPersistentState().getVotedFor())
, last_activity_timestamp(s.getRaftCore().getLastActivityTimestamp())
, randomized_timeout (s.getRaftCore().getRandomizedTimeout())
, num_unknown_nodes (s.getNodeDiscoverer().getNumUnknownNodes())
{
const Entry* const e = s.getRaftCore().getPersistentState().getLog().getEntryAtIndex(last_log_index);
UAVCAN_ASSERT(e != NULL);
if (e != NULL)
{
last_log_term = e->term;
}
for (uint8_t i = 0; i < (cluster_size - 1U); i++)
{
const ClusterManager& mgr = s.getRaftCore().getClusterManager();
const NodeID node_id = mgr.getRemoteServerNodeIDAtIndex(i);
if (node_id.isUnicast())
{
followers[i].node_id = node_id;
followers[i].next_index = mgr.getServerNextIndex(node_id);
followers[i].match_index = mgr.getServerMatchIndex(node_id);
}
}
}
};
}
}
}
#endif // Include guard
<|endoftext|> |
<commit_before>#include "compiler.h"
#include "dosio.h"
static OEMCHAR curpath[MAX_PATH];
static OEMCHAR *curfilep = curpath;
#define ISKANJI(c) (((((c) ^ 0x20) - 0xa1) & 0xff) < 0x3c)
// ----
static FATFS Fatfs;
static FILINFO _fi;
#ifdef _USE_LFN
static char lfn[_MAX_LFN + 1];
#endif
void dosio_init(void) {
f_mount(0, &Fatfs);
#ifdef _USE_LFN
_fi.lfname = lfn;
_fi.lfsize = sizeof(lfn);
#endif
}
void dosio_term(void) {
f_mount(0, NULL);
}
// t@C
FILEH file_open(const OEMCHAR *path)
{
FRESULT res;
FILEH fi;
fi = (FILEH)malloc(sizeof(FIL));
res = f_open(fi, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING);
if (res != FR_OK) {
#ifndef NOSERIAL
printf("%s failed %s %d\n", __func__, path, res);
#endif
return FILEH_INVALID;
}
return(fi);
}
FILEH file_open_rb(const OEMCHAR *path)
{
FRESULT res;
FILEH fi;
fi = (FILEH)malloc(sizeof(FIL));
res = f_open(fi, path, FA_READ | FA_OPEN_EXISTING);
if (res != FR_OK) {
#ifndef NOSERIAL
printf("%s failed %s %d\n", __func__, path, res);
#endif
return FILEH_INVALID;
}
return(fi);
}
FILEH file_create(const OEMCHAR *path)
{
FRESULT res;
FILEH fi;
fi = (FILEH)malloc(sizeof(FIL));
res = f_open(fi, path, FA_READ | FA_WRITE | FA_CREATE_ALWAYS);
if (res != FR_OK) {
#ifndef NOSERIAL
printf("%s failed %s %d\n", __func__, path, res);
#endif
return FILEH_INVALID;
}
return(fi);
}
long file_seek(FILEH handle, long pointer, int method) {
long ret;
FRESULT res;
ret = 0;
switch (method) {
case 1:
ret = f_tell(handle);
break;
case 2:
ret = f_size(handle);
break;
}
ret += pointer;
if (ret < 0) {
ret = 0;
} else if (ret > (long)f_size(handle)) {
ret = f_size(handle);
}
res = f_lseek (handle, ret);
if (res != FR_OK)
return -1;
return ret;
}
UINT file_read(FILEH handle, void *data, UINT length)
{
UINT readsize;
if(f_read (handle, data, length, &readsize) != FR_OK) {
#ifndef NOSERIAL
printf("%s failed 0x%x 0x%x\n", __func__, length, readsize);
#endif
return(0);
}
return(readsize);
}
UINT file_write(FILEH handle, const void *data, UINT length)
{
UINT writesize;
if (length) {
if (f_write (handle, data, length, &writesize) == FR_OK) {
return(writesize);
}
else {
f_lseek (handle, f_size(handle));
}
}
return(0);
}
short file_close(FILEH handle)
{
f_close (handle);
free(handle);
return 0;
}
UINT file_getsize(FILEH handle)
{
return f_size(handle);
}
static BOOL cnvdatetime(FILINFO *fno, DOSDATE *dosdate, DOSTIME *dostime)
{
if (dosdate) {
dosdate->year = (fno->fdate >> 9) + 1980;
dosdate->month = (fno->fdate >> 5) & 0x0f;
dosdate->day = (fno->fdate >> 0) & 0x0f;
}
if (dostime) {
dostime->hour = (fno->ftime >> 11);
dostime->minute = (fno->ftime >> 5) & 0x3f;
dostime->second = (fno->ftime >> 0) & 0x0f;
}
return SUCCESS;
}
short file_getdatetime(const char *path, DOSDATE *dosdate, DOSTIME *dostime)
{
FILINFO *fi = &_fi;
if ((f_stat(path, fi) == FR_OK)
&& (cnvdatetime(fi, dosdate, dostime)))
return 0;
return -1;
}
short file_delete(const OEMCHAR *path)
{
return(f_unlink(path)? FAILURE:SUCCESS);
}
short file_attr(const OEMCHAR *path)
{
FILINFO *fi = &_fi;
if (f_stat(path, fi) != FR_OK)
return 0;
return fi->fattrib;
}
short file_dircreate(const OEMCHAR *path)
{
return(f_mkdir(path) ?FAILURE:SUCCESS);
}
// Jgt@C
void file_setcd(const OEMCHAR *exepath)
{
file_cpyname(curpath, exepath, sizeof(curpath));
curfilep = file_getname(curpath);
*curfilep = '\0';
}
OEMCHAR *file_getcd(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return curpath;
}
FILEH file_open_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_open(curpath);
}
FILEH file_open_rb_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_open_rb(curpath);
}
FILEH file_create_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_create(curpath);
}
short file_delete_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_delete(curpath);
}
short file_attr_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_attr(curpath);
}
static BRESULT setflist(FILINFO *fi, FLINFO *fli) {
char *fn;
fli->caps = FLICAPS_SIZE | FLICAPS_ATTR | FLICAPS_DATE | FLICAPS_TIME;
fli->size = fi->fsize;
fli->attr = fi->fattrib;
cnvdatetime(fi, &fli->date, &fli->time);
#ifdef _USE_LFN
fn = *fi->lfname ? fi->lfname : fi->fname;
#else
fn = fi->fname;
#endif
file_cpyname(fli->path, fn, NELEMENTS(fli->path));
return(SUCCESS);
}
FLISTH file_list1st(const OEMCHAR *dir, FLINFO *fli) {
FRESULT res;
FILINFO *fi = &_fi;
OEMCHAR path[MAX_PATH];
file_cpyname(path, dir, NELEMENTS(path));
// file_setseparator(path, NELEMENTS(path));
#ifndef NOSERIAL
printf("file_list1st %s\n", path);
#endif
FLISTH dj = (FLISTH)malloc(sizeof(DIR));
res = f_opendir(dj, path);
if (res == FR_OK) {
while ((f_readdir(dj, fi) == FR_OK) && fi->fname[0]) {
if (setflist(fi, fli) == SUCCESS) {
return(dj);
}
}
}
return(FLISTH_INVALID);
}
BRESULT file_listnext(FLISTH hdl, FLINFO *fli) {
FILINFO *fi = &_fi;
if ((f_readdir(hdl, fi) != FR_OK) || fi->fname[0] == 0) {
return(FAILURE);
}
if (setflist(fi, fli) == SUCCESS) {
return(SUCCESS);
}
#ifndef NOSERIAL
printf("file_listnext fail %s\n", fi->fname);
#endif
return(FAILURE);
}
void file_listclose(FLISTH hdl) {
free(hdl);
}
OEMCHAR *file_getname(const OEMCHAR *path) {
const OEMCHAR *ret;
int csize;
ret = path;
while((csize = milstr_charsize(path)) != 0) {
if ((csize == 1) &&
((*path == '\\') || (*path == '/') || (*path == ':'))) {
ret = path + 1;
}
path += csize;
}
return((OEMCHAR *)ret);
}
void file_cutname(OEMCHAR *path) {
OEMCHAR *p;
p = file_getname(path);
p[0] = '\0';
}
OEMCHAR *file_getext(const OEMCHAR *path) {
const OEMCHAR *p;
const OEMCHAR *q;
int csize;
p = file_getname(path);
q = NULL;
while((csize = milstr_charsize(p)) != 0) {
if ((csize == 1) && (*p == '.')) {
q = p + 1;
}
p += csize;
}
if (q == NULL) {
q = p;
}
return((OEMCHAR *)q);
}
void file_cutext(OEMCHAR *path) {
OEMCHAR *p;
OEMCHAR *q;
int csize;
p = file_getname(path);
q = NULL;
while((csize = milstr_charsize(p)) != 0) {
if ((csize == 1) && (*p == '.')) {
q = p;
}
p += csize;
}
if (q) {
*q = '\0';
}
}
void file_cutseparator(OEMCHAR *path) {
int pos;
pos = OEMSTRLEN(path) - 1;
if ((pos > 0) && // 2ȏŁ[
(path[pos] == '\\') && // Pc \ Ł[
(!milstr_kanji2nd(path, pos)) && // 2oCgڂȂā[
((pos != 1) || (path[0] != '\\')) && // '\\' ł͂Ȃā[
((pos != 2) || (path[1] != ':'))) { // '?:\' ł͂Ȃ
path[pos] = '\0';
}
}
void file_setseparator(OEMCHAR *path, int maxlen) {
int pos;
pos = OEMSTRLEN(path) - 1;
if ((pos < 0) ||
((pos == 1) && (path[1] == ':')) ||
((path[pos] == '\\') && (!milstr_kanji2nd(path, pos))) ||
((pos + 2) >= maxlen)) {
return;
}
path[++pos] = '\\';
path[++pos] = '\0';
}
<commit_msg>Fixed memory leak<commit_after>#include "compiler.h"
#include "dosio.h"
static OEMCHAR curpath[MAX_PATH];
static OEMCHAR *curfilep = curpath;
#define ISKANJI(c) (((((c) ^ 0x20) - 0xa1) & 0xff) < 0x3c)
// ----
static FATFS Fatfs;
static FILINFO _fi;
#ifdef _USE_LFN
static char lfn[_MAX_LFN + 1];
#endif
void dosio_init(void) {
f_mount(0, &Fatfs);
#ifdef _USE_LFN
_fi.lfname = lfn;
_fi.lfsize = sizeof(lfn);
#endif
}
void dosio_term(void) {
f_mount(0, NULL);
}
// t@C
FILEH file_open(const OEMCHAR *path)
{
FRESULT res;
FILEH fi;
fi = (FILEH)malloc(sizeof(FIL));
if (fi == NULL) return FILEH_INVALID;
res = f_open(fi, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING);
if (res != FR_OK) {
#ifndef NOSERIAL
printf("%s failed %s %d\n", __func__, path, res);
#endif
free(fi);
return FILEH_INVALID;
}
return(fi);
}
FILEH file_open_rb(const OEMCHAR *path)
{
FRESULT res;
FILEH fi;
fi = (FILEH)malloc(sizeof(FIL));
if (fi == NULL) return FILEH_INVALID;
res = f_open(fi, path, FA_READ | FA_OPEN_EXISTING);
if (res != FR_OK) {
#ifndef NOSERIAL
printf("%s failed %s %d\n", __func__, path, res);
#endif
free(fi);
return FILEH_INVALID;
}
return(fi);
}
FILEH file_create(const OEMCHAR *path)
{
FRESULT res;
FILEH fi;
fi = (FILEH)malloc(sizeof(FIL));
if (fi == NULL) return FILEH_INVALID;
res = f_open(fi, path, FA_READ | FA_WRITE | FA_CREATE_ALWAYS);
if (res != FR_OK) {
#ifndef NOSERIAL
printf("%s failed %s %d\n", __func__, path, res);
#endif
free(fi);
return FILEH_INVALID;
}
return(fi);
}
long file_seek(FILEH handle, long pointer, int method) {
long ret;
FRESULT res;
ret = 0;
switch (method) {
case 1:
ret = f_tell(handle);
break;
case 2:
ret = f_size(handle);
break;
}
ret += pointer;
if (ret < 0) {
ret = 0;
} else if (ret > (long)f_size(handle)) {
ret = f_size(handle);
}
res = f_lseek (handle, ret);
if (res != FR_OK)
return -1;
return ret;
}
UINT file_read(FILEH handle, void *data, UINT length)
{
UINT readsize;
if(f_read (handle, data, length, &readsize) != FR_OK) {
#ifndef NOSERIAL
printf("%s failed 0x%x 0x%x\n", __func__, length, readsize);
#endif
return(0);
}
return(readsize);
}
UINT file_write(FILEH handle, const void *data, UINT length)
{
UINT writesize;
if (length) {
if (f_write (handle, data, length, &writesize) == FR_OK) {
return(writesize);
}
else {
f_lseek (handle, f_size(handle));
}
}
return(0);
}
short file_close(FILEH handle)
{
f_close (handle);
free(handle);
return 0;
}
UINT file_getsize(FILEH handle)
{
return f_size(handle);
}
static BOOL cnvdatetime(FILINFO *fno, DOSDATE *dosdate, DOSTIME *dostime)
{
if (dosdate) {
dosdate->year = (fno->fdate >> 9) + 1980;
dosdate->month = (fno->fdate >> 5) & 0x0f;
dosdate->day = (fno->fdate >> 0) & 0x0f;
}
if (dostime) {
dostime->hour = (fno->ftime >> 11);
dostime->minute = (fno->ftime >> 5) & 0x3f;
dostime->second = (fno->ftime >> 0) & 0x0f;
}
return SUCCESS;
}
short file_getdatetime(const char *path, DOSDATE *dosdate, DOSTIME *dostime)
{
FILINFO *fi = &_fi;
if ((f_stat(path, fi) == FR_OK)
&& (cnvdatetime(fi, dosdate, dostime)))
return 0;
return -1;
}
short file_delete(const OEMCHAR *path)
{
return(f_unlink(path)? FAILURE:SUCCESS);
}
short file_attr(const OEMCHAR *path)
{
FILINFO *fi = &_fi;
if (f_stat(path, fi) != FR_OK)
return 0;
return fi->fattrib;
}
short file_dircreate(const OEMCHAR *path)
{
return(f_mkdir(path) ?FAILURE:SUCCESS);
}
// Jgt@C
void file_setcd(const OEMCHAR *exepath)
{
file_cpyname(curpath, exepath, sizeof(curpath));
curfilep = file_getname(curpath);
*curfilep = '\0';
}
OEMCHAR *file_getcd(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return curpath;
}
FILEH file_open_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_open(curpath);
}
FILEH file_open_rb_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_open_rb(curpath);
}
FILEH file_create_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_create(curpath);
}
short file_delete_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_delete(curpath);
}
short file_attr_c(const OEMCHAR *path)
{
*curfilep = '\0';
file_catname(curpath, path, sizeof(curpath));
return file_attr(curpath);
}
static BRESULT setflist(FILINFO *fi, FLINFO *fli) {
char *fn;
fli->caps = FLICAPS_SIZE | FLICAPS_ATTR | FLICAPS_DATE | FLICAPS_TIME;
fli->size = fi->fsize;
fli->attr = fi->fattrib;
cnvdatetime(fi, &fli->date, &fli->time);
#ifdef _USE_LFN
fn = *fi->lfname ? fi->lfname : fi->fname;
#else
fn = fi->fname;
#endif
file_cpyname(fli->path, fn, NELEMENTS(fli->path));
return(SUCCESS);
}
FLISTH file_list1st(const OEMCHAR *dir, FLINFO *fli) {
FRESULT res;
FILINFO *fi = &_fi;
OEMCHAR path[MAX_PATH];
file_cpyname(path, dir, NELEMENTS(path));
// file_setseparator(path, NELEMENTS(path));
#ifndef NOSERIAL
printf("file_list1st %s\n", path);
#endif
FLISTH dj = (FLISTH)malloc(sizeof(DIR));
if (dj == NULL) goto err;
res = f_opendir(dj, path);
if (res == FR_OK) {
while ((f_readdir(dj, fi) == FR_OK) && fi->fname[0]) {
if (setflist(fi, fli) == SUCCESS) {
return(dj);
}
}
}
free(dj);
err:
return(FLISTH_INVALID);
}
BRESULT file_listnext(FLISTH hdl, FLINFO *fli) {
FILINFO *fi = &_fi;
if ((f_readdir(hdl, fi) != FR_OK) || fi->fname[0] == 0) {
return(FAILURE);
}
if (setflist(fi, fli) == SUCCESS) {
return(SUCCESS);
}
return(FAILURE);
}
void file_listclose(FLISTH hdl) {
free(hdl);
}
OEMCHAR *file_getname(const OEMCHAR *path) {
const OEMCHAR *ret;
int csize;
ret = path;
while((csize = milstr_charsize(path)) != 0) {
if ((csize == 1) &&
((*path == '\\') || (*path == '/') || (*path == ':'))) {
ret = path + 1;
}
path += csize;
}
return((OEMCHAR *)ret);
}
void file_cutname(OEMCHAR *path) {
OEMCHAR *p;
p = file_getname(path);
p[0] = '\0';
}
OEMCHAR *file_getext(const OEMCHAR *path) {
const OEMCHAR *p;
const OEMCHAR *q;
int csize;
p = file_getname(path);
q = NULL;
while((csize = milstr_charsize(p)) != 0) {
if ((csize == 1) && (*p == '.')) {
q = p + 1;
}
p += csize;
}
if (q == NULL) {
q = p;
}
return((OEMCHAR *)q);
}
void file_cutext(OEMCHAR *path) {
OEMCHAR *p;
OEMCHAR *q;
int csize;
p = file_getname(path);
q = NULL;
while((csize = milstr_charsize(p)) != 0) {
if ((csize == 1) && (*p == '.')) {
q = p;
}
p += csize;
}
if (q) {
*q = '\0';
}
}
void file_cutseparator(OEMCHAR *path) {
int pos;
pos = OEMSTRLEN(path) - 1;
if ((pos > 0) && // 2ȏŁ[
(path[pos] == '\\') && // Pc \ Ł[
(!milstr_kanji2nd(path, pos)) && // 2oCgڂȂā[
((pos != 1) || (path[0] != '\\')) && // '\\' ł͂Ȃā[
((pos != 2) || (path[1] != ':'))) { // '?:\' ł͂Ȃ
path[pos] = '\0';
}
}
void file_setseparator(OEMCHAR *path, int maxlen) {
int pos;
pos = OEMSTRLEN(path) - 1;
if ((pos < 0) ||
((pos == 1) && (path[1] == ':')) ||
((path[pos] == '\\') && (!milstr_kanji2nd(path, pos))) ||
((pos + 2) >= maxlen)) {
return;
}
path[++pos] = '\\';
path[++pos] = '\0';
}
<|endoftext|> |
<commit_before>{
gROOT->Reset();
TCanvas *nut = new TCanvas("nut", "FirstSession",100,10,700,900);
nut->Range(0,0,20,24);
nut->SetFillColor(10);
nut->SetBorderSize(2);
TPaveLabel *pl = new TPaveLabel(3,22,17,23.7,"My first ROOT interactive session","br");
pl->SetFillColor(18);
pl->SetTextSize(0.7);
pl->Draw();
TText t(0,0,"a");
t.SetTextFont(62);
t.SetTextSize(0.025);
t.SetTextAlign(12);
t.DrawText(2,20.3,"ROOT is based on CINT, a powerful C/C++ interpreter.");
t.DrawText(2,19.3,"Blocks of lines can be entered within {...}.");
t.DrawText(2,18.3,"Previous typed lines can be recalled.");
t.SetTextFont(72);
t.SetTextSize(0.026);
t.DrawText(3,17,"Root > float x=5; float y=7;");
t.DrawText(3,16,"Root > x*sqrt(y)");
t.DrawText(3,14,"Root > for (int i=2;i<7;i++) printf(\"sqrt(%d) = %f\",i,sqrt(i));");
t.DrawText(3,10,"Root > TF1 f1(\"f1\",\"sin(x)/x\",0,10)");
t.DrawText(3, 9,"Root > f1.Draw()");
t.SetTextFont(81);
t.SetTextSize(0.018);
t.DrawText(4,15,"(double)1.322875655532e+01");
t.DrawText(4,13.3,"sqrt(2) = 1.414214");
t.DrawText(4,12.7,"sqrt(3) = 1.732051");
t.DrawText(4,12.1,"sqrt(4) = 2.000000");
t.DrawText(4,11.5,"sqrt(5) = 2.236068");
t.DrawText(4,10.9,"sqrt(6) = 2.449490");
TPad *pad = new TPad("pad","pad",.2,.05,.8,.35);
pad->Draw();
pad->cd();
pad->SetGrid();
TF1 f1("f1","sin(x)/x",0,10);
f1.Draw();
nut.cd();
//--signature
TText sig(.2,.2,"/user/brun/root/aihep/first.C");
sig.SetTextFont(72);
sig.SetTextSize(0.020);
sig.Draw();
nut->Modified();
nut->Print("first.ps");
nut->cd();
nut->Update();
}
<commit_msg>Remove the line setting the TPaveLabel text size. This is now automatic.<commit_after>{
gROOT->Reset();
TCanvas *nut = new TCanvas("nut", "FirstSession",100,10,700,900);
nut->Range(0,0,20,24);
nut->SetFillColor(10);
nut->SetBorderSize(2);
TPaveLabel *pl = new TPaveLabel(3,22,17,23.7,"My first ROOT interactive session","br");
pl->SetFillColor(18);
pl->Draw();
TText t(0,0,"a");
t.SetTextFont(62);
t.SetTextSize(0.025);
t.SetTextAlign(12);
t.DrawText(2,20.3,"ROOT is based on CINT, a powerful C/C++ interpreter.");
t.DrawText(2,19.3,"Blocks of lines can be entered within {...}.");
t.DrawText(2,18.3,"Previous typed lines can be recalled.");
t.SetTextFont(72);
t.SetTextSize(0.026);
t.DrawText(3,17,"Root > float x=5; float y=7;");
t.DrawText(3,16,"Root > x*sqrt(y)");
t.DrawText(3,14,"Root > for (int i=2;i<7;i++) printf(\"sqrt(%d) = %f\",i,sqrt(i));");
t.DrawText(3,10,"Root > TF1 f1(\"f1\",\"sin(x)/x\",0,10)");
t.DrawText(3, 9,"Root > f1.Draw()");
t.SetTextFont(81);
t.SetTextSize(0.018);
t.DrawText(4,15,"(double)1.322875655532e+01");
t.DrawText(4,13.3,"sqrt(2) = 1.414214");
t.DrawText(4,12.7,"sqrt(3) = 1.732051");
t.DrawText(4,12.1,"sqrt(4) = 2.000000");
t.DrawText(4,11.5,"sqrt(5) = 2.236068");
t.DrawText(4,10.9,"sqrt(6) = 2.449490");
TPad *pad = new TPad("pad","pad",.2,.05,.8,.35);
pad->Draw();
pad->cd();
pad->SetGrid();
TF1 f1("f1","sin(x)/x",0,10);
f1.Draw();
nut.cd();
//--signature
TText sig(.2,.2,"/user/brun/root/aihep/first.C");
sig.SetTextFont(72);
sig.SetTextSize(0.020);
sig.Draw();
nut->Modified();
nut->Print("first.ps");
nut->cd();
nut->Update();
}
<|endoftext|> |
<commit_before>#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
# pragma once
#include <cassert>
#include <atomic>
#include <memory>
#include <type_traits>
#include <utility>
namespace generic
{
namespace detail
{
namespace light_ptr
{
using counter_type = unsigned;
using atomic_type = ::std::atomic<counter_type>;
template <typename T>
using deleter_type = void (*)(T*);
template <typename U>
struct ref_type
{
using type = U&;
};
template <>
struct ref_type<void>
{
using type = void;
};
}
}
template <typename T>
class light_ptr
{
template <typename U, typename V>
struct deletion_type
{
using type = V;
};
template <typename U, typename V>
struct deletion_type<U[], V>
{
using type = V[];
};
template <typename U, typename V, ::std::size_t N>
struct deletion_type<U[N], V>
{
using type = V[];
};
using element_type = typename ::std::remove_extent<T>::type;
using deleter_type = detail::light_ptr::deleter_type<element_type>;
class counter_base
{
friend class light_ptr;
using invoker_type = void (*)(counter_base*, element_type*);
detail::light_ptr::atomic_type counter_{};
invoker_type const invoker_;
protected:
explicit counter_base(detail::light_ptr::counter_type const c,
invoker_type const invoker) noexcept :
counter_(c),
invoker_(invoker)
{
}
public:
template <typename U>
typename ::std::enable_if<!::std::is_void<U>{}>::type
dec_ref(U* const ptr) noexcept
{
if (detail::light_ptr::counter_type(1) ==
counter_.fetch_sub(detail::light_ptr::counter_type(1),
::std::memory_order_relaxed))
{
using type_must_be_complete = char[sizeof(U) ? 1 : -1];
(void)sizeof(type_must_be_complete);
invoker_(this, ptr);
}
// else do nothing
}
template <typename U>
typename ::std::enable_if<::std::is_void<U>{}>::type
dec_ref(U* const ptr) noexcept
{
if (detail::light_ptr::counter_type(1) ==
counter_.fetch_sub(detail::light_ptr::counter_type(1),
::std::memory_order_relaxed))
{
invoker_(this, ptr);
}
// else do nothing
}
void inc_ref() noexcept
{
counter_.fetch_add(detail::light_ptr::counter_type(1),
::std::memory_order_relaxed);
}
};
template <typename D>
class counter : public counter_base
{
typename ::std::decay<D>::type const d_;
static void invoker(counter_base* const ptr,
element_type* const e) noexcept
{
auto const c(static_cast<counter<D>*>(ptr));
// invoke deleter on the element
c->d_(e);
// delete from a static member function
delete c;
}
public:
explicit counter(detail::light_ptr::counter_type const c,
D&& d) noexcept :
counter_base(c, invoker),
d_(::std::forward<D>(d))
{
}
};
private:
template <typename U> friend struct ::std::hash;
counter_base* counter_{};
element_type* ptr_;
public:
light_ptr() = default;
template <typename U>
explicit light_ptr(U* const p)
{
reset(p);
}
template <typename U, typename D>
explicit light_ptr(U* const p, D&& d)
{
reset(p, ::std::forward<D>(d));
}
light_ptr(light_ptr const& other) { *this = other; }
light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }
~light_ptr() noexcept
{
if (counter_)
{
counter_->dec_ref(ptr_);
}
// else do nothing
}
light_ptr& operator=(light_ptr const& rhs) noexcept
{
if (*this != rhs)
{
if (counter_)
{
counter_->dec_ref(ptr_);
}
// else do nothing
if ((counter_ = rhs.counter_))
{
counter_->inc_ref();
}
// else do nothing
ptr_ = rhs.ptr_;
}
// else do nothing
return *this;
}
light_ptr& operator=(light_ptr&& rhs) noexcept
{
counter_ = rhs.counter_;
rhs.counter_ = nullptr;
ptr_ = rhs.ptr_;
return *this;
}
light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }
bool operator<(light_ptr const& rhs) const noexcept
{
return counter_ < rhs.counter_;
}
bool operator==(light_ptr const& rhs) const noexcept
{
return counter_ == rhs.counter_;
}
bool operator!=(light_ptr const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator==(::std::nullptr_t const) const noexcept { return !counter_; }
bool operator!=(::std::nullptr_t const) const noexcept { return counter_; }
explicit operator bool() const noexcept { return counter_; }
typename detail::light_ptr::ref_type<T>::type
operator*() const noexcept
{
return *reinterpret_cast<T*>(ptr_);
}
T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }
template <typename U = T, typename =
typename ::std::enable_if<::std::is_array<U>{}>::type>
typename detail::light_ptr::ref_type<element_type>::type operator[](
::std::size_t const i) const noexcept
{
return ptr_[i];
}
element_type* get() const noexcept { return ptr_; }
void reset() noexcept { reset(nullptr); }
void reset(::std::nullptr_t const) noexcept
{
if (counter_)
{
counter_->dec_ref(ptr_);
counter_ = {};
}
// else do nothing
}
template <typename U>
void reset(U* const p) noexcept
{
reset(p,
[](element_type* const p) noexcept {
::std::default_delete<typename deletion_type<T, U>::type>()(
static_cast<U*>(p)
);
}
);
}
template <typename U, typename D>
void reset(U* const p, D&& d) noexcept
{
if (counter_)
{
counter_->dec_ref(ptr_);
}
// else do nothing
counter_ = new counter<D>(detail::light_ptr::counter_type(1),
::std::forward<D>(d)
);
ptr_ = p;
}
void swap(light_ptr& other) noexcept
{
::std::swap(counter_, other.counter_);
::std::swap(ptr_, other.ptr_);
}
bool unique() const noexcept
{
return detail::light_ptr::counter_type(1) == use_count();
}
detail::light_ptr::counter_type use_count() const noexcept
{
return counter_ ?
counter_->counter_.load(::std::memory_order_relaxed) :
detail::light_ptr::counter_type{};
}
};
template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
return light_ptr<T>(new T(::std::forward<Args>(args)...));
}
}
namespace std
{
template <typename T>
struct hash<::generic::light_ptr<T> >
{
size_t operator()(::generic::light_ptr<T> const& l) const noexcept
{
return hash<typename ::generic::light_ptr<T>::element_type*>()(l.ptr_);
}
};
}
#endif // LIGHTPTR_HPP
<commit_msg>some fixes<commit_after>#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
# pragma once
#include <cassert>
#include <atomic>
#include <memory>
#include <type_traits>
#include <utility>
namespace generic
{
namespace detail
{
namespace light_ptr
{
using counter_type = unsigned;
using atomic_type = ::std::atomic<counter_type>;
template <typename T>
using deleter_type = void (*)(T*);
template <typename U>
struct ref_type
{
using type = U&;
};
template <>
struct ref_type<void>
{
using type = void;
};
}
}
template <typename T>
class light_ptr
{
template <typename U, typename V>
struct deletion_type
{
using type = V;
};
template <typename U, typename V>
struct deletion_type<U[], V>
{
using type = V[];
};
template <typename U, typename V, ::std::size_t N>
struct deletion_type<U[N], V>
{
using type = V[];
};
using element_type = typename ::std::remove_extent<T>::type;
using deleter_type = detail::light_ptr::deleter_type<element_type>;
class counter_base
{
friend class light_ptr;
using invoker_type = void (*)(counter_base*, element_type*) noexcept;
detail::light_ptr::atomic_type counter_{};
invoker_type const invoker_;
protected:
explicit counter_base(detail::light_ptr::counter_type const c,
invoker_type const invoker) noexcept :
counter_(c),
invoker_(invoker)
{
}
public:
template <typename U>
typename ::std::enable_if<!::std::is_void<U>{}>::type
dec_ref(U* const ptr) noexcept
{
if (detail::light_ptr::counter_type(1) ==
counter_.fetch_sub(detail::light_ptr::counter_type(1),
::std::memory_order_relaxed))
{
using type_must_be_complete = char[sizeof(U) ? 1 : -1];
(void)sizeof(type_must_be_complete);
invoker_(this, ptr);
}
// else do nothing
}
template <typename U>
typename ::std::enable_if<::std::is_void<U>{}>::type
dec_ref(U* const ptr) noexcept
{
if (detail::light_ptr::counter_type(1) ==
counter_.fetch_sub(detail::light_ptr::counter_type(1),
::std::memory_order_relaxed))
{
invoker_(this, ptr);
}
// else do nothing
}
void inc_ref() noexcept
{
counter_.fetch_add(detail::light_ptr::counter_type(1),
::std::memory_order_relaxed);
}
};
template <typename D>
class counter : public counter_base
{
typename ::std::decay<D>::type const d_;
static void invoked(counter_base* const ptr,
element_type* const e) noexcept
{
auto const c(static_cast<counter<D>*>(ptr));
// invoke deleter on the element
c->d_(e);
// delete from a static member function
delete c;
}
public:
explicit counter(detail::light_ptr::counter_type const c,
D&& d) noexcept :
counter_base(c, invoked),
d_(::std::forward<D>(d))
{
}
};
private:
template <typename U> friend struct ::std::hash;
counter_base* counter_{};
element_type* ptr_;
public:
light_ptr() = default;
template <typename U>
explicit light_ptr(U* const p)
{
reset(p);
}
template <typename U, typename D>
explicit light_ptr(U* const p, D&& d)
{
reset(p, ::std::forward<D>(d));
}
light_ptr(light_ptr const& other) { *this = other; }
light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }
~light_ptr() noexcept
{
if (counter_)
{
counter_->dec_ref(ptr_);
}
// else do nothing
}
light_ptr& operator=(light_ptr const& rhs) noexcept
{
if (*this != rhs)
{
if (counter_)
{
counter_->dec_ref(ptr_);
}
// else do nothing
if ((counter_ = rhs.counter_))
{
counter_->inc_ref();
}
// else do nothing
ptr_ = rhs.ptr_;
}
// else do nothing
return *this;
}
light_ptr& operator=(light_ptr&& rhs) noexcept
{
counter_ = rhs.counter_;
rhs.counter_ = nullptr;
ptr_ = rhs.ptr_;
return *this;
}
light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }
bool operator<(light_ptr const& rhs) const noexcept
{
return counter_ < rhs.counter_;
}
bool operator==(light_ptr const& rhs) const noexcept
{
return counter_ == rhs.counter_;
}
bool operator!=(light_ptr const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator==(::std::nullptr_t const) const noexcept { return !counter_; }
bool operator!=(::std::nullptr_t const) const noexcept { return counter_; }
explicit operator bool() const noexcept { return counter_; }
typename detail::light_ptr::ref_type<T>::type
operator*() const noexcept
{
return *reinterpret_cast<T*>(ptr_);
}
T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }
template <typename U = T, typename =
typename ::std::enable_if<::std::is_array<U>{}>::type>
typename detail::light_ptr::ref_type<element_type>::type operator[](
::std::size_t const i) const noexcept
{
return ptr_[i];
}
element_type* get() const noexcept { return ptr_; }
void reset() noexcept { reset(nullptr); }
void reset(::std::nullptr_t const) noexcept
{
if (counter_)
{
counter_->dec_ref(ptr_);
counter_ = {};
}
// else do nothing
}
template <typename U>
void reset(U* const p) noexcept
{
reset(p,
[](element_type* const p) noexcept {
::std::default_delete<typename deletion_type<T, U>::type>()(
static_cast<U*>(p)
);
}
);
}
template <typename U, typename D>
void reset(U* const p, D&& d) noexcept
{
if (counter_)
{
counter_->dec_ref(ptr_);
}
// else do nothing
counter_ = new counter<D>(detail::light_ptr::counter_type(1),
::std::forward<D>(d)
);
ptr_ = p;
}
void swap(light_ptr& other) noexcept
{
::std::swap(counter_, other.counter_);
::std::swap(ptr_, other.ptr_);
}
bool unique() const noexcept
{
return detail::light_ptr::counter_type(1) == use_count();
}
detail::light_ptr::counter_type use_count() const noexcept
{
return counter_ ?
counter_->counter_.load(::std::memory_order_relaxed) :
detail::light_ptr::counter_type{};
}
};
template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
return light_ptr<T>(new T(::std::forward<Args>(args)...));
}
}
namespace std
{
template <typename T>
struct hash<::generic::light_ptr<T> >
{
size_t operator()(::generic::light_ptr<T> const& l) const noexcept
{
return hash<typename ::generic::light_ptr<T>::element_type*>()(l.ptr_);
}
};
}
#endif // LIGHTPTR_HPP
<|endoftext|> |
<commit_before>/*
* linker32.cpp
*
* Created on: Jul 23, 2014
* Author: Pimenta
*/
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <set>
#include <map>
#include <string>
using namespace std;
typedef uint32_t uword_t;
#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif
#ifndef WORD_WIDTH
#define WORD_WIDTH 32
#endif
struct ObjectFile32 {
uword_t offset;
uword_t text_offset;
map<string, uword_t> exported;
map<string, set<uword_t>> imported;
set<uword_t> absolute;
uword_t mem_size;
uword_t* mem;
~ObjectFile32() {
delete[] mem;
}
void initStart() {
offset = 0;
text_offset = 0;
imported["start"].emplace(2);
mem_size = 3;
mem = new uword_t[3];
mem[0] = 0;
mem[1] = 0;
mem[2] = 0;
}
void read(const char* fn, uword_t offs) {
offset = offs;
fstream f(fn, fstream::in | fstream::binary);
uword_t tmp;
// read text section offset
f.read((char*)&text_offset, sizeof(uword_t));
// read number of exported symbols
f.read((char*)&tmp, sizeof(uword_t));
// read exported symbols
for (uword_t i = 0; i < tmp; ++i) {
string sym;
uword_t addr;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
// address
f.read((char*)&addr, sizeof(uword_t));
exported[sym] = addr;
}
// read number of symbols of pending references
f.read((char*)&tmp, sizeof(uword_t));
// read symbols of pending references
for (uword_t i = 0; i < tmp; ++i) {
string sym;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
uword_t tmp2;
// read number of references to current symbol
f.read((char*)&tmp2, sizeof(uword_t));
// read references to current symbol
for (uword_t j = 0; j < tmp2; ++j) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
imported[sym].emplace(addr);
}
}
// read number of absolute addresses
f.read((char*)&tmp, sizeof(uword_t));
// read absolute addresses
for (uword_t i = 0; i < tmp; ++i) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
absolute.emplace(addr);
}
// read assembled code size
f.read((char*)&mem_size, sizeof(uword_t));
// read assembled code
mem = new uword_t[mem_size];
f.read((char*)mem, sizeof(uword_t)*mem_size);
f.close();
}
};
int linker32(int argc, char* argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage mode: subleq-ld <object_files...> <meminit_file>\n");
return 0;
}
// read object files
ObjectFile32 files[argc - 1];
files[0].initStart();
for (int i = 1; i < argc - 1; ++i)
files[i].read(argv[i], files[i - 1].offset + files[i - 1].mem_size);
// assemble global symbol table
map<string, uword_t> symbols;
for (auto& file : files) {
for (auto& sym : file.exported) {
symbols[sym.first] = sym.second + file.offset;
}
}
// link
uword_t mem_size = 0;
uword_t* mem = new uword_t[MEM_WORDS];
for (auto& file : files) {
// relocate addresses
for (uword_t i = file.text_offset; i < file.mem_size; ++i) {
auto it = file.absolute.find(i);
if (it == file.absolute.end()) {
file.mem[i] += file.offset;
}
}
// solve pendencies for this file
for (auto& sym : file.imported) {
uword_t sym_addr = symbols[sym.first];
for (auto ref : sym.second) {
file.mem[ref] = sym_addr;
}
}
// copy mem
memcpy(&mem[mem_size], file.mem, file.mem_size*sizeof(uword_t));
mem_size += file.mem_size;
}
// output mif
fstream f(argv[argc - 1], fstream::out);
char buf[20];
f << "DEPTH = " << MEM_WORDS << ";\n";
f << "WIDTH = " << WORD_WIDTH << ";\n";
f << "ADDRESS_RADIX = HEX;\n";
f << "DATA_RADIX = HEX;\n";
f << "CONTENT\n";
f << "BEGIN\n";
f << "\n";
for (uword_t i = 0; i < mem_size; ++i) {
sprintf(buf, "%08x", i);
f << buf;
sprintf(buf, "%08x", mem[i]);
f << " : " << buf << ";\n";
}
f << "\n";
f << "END;\n";
f.close();
delete[] mem;
return 0;
}
<commit_msg>Now the linker for subleq32 has global references and absoluted addresses tables<commit_after>/*
* linker32.cpp
*
* Created on: Jul 23, 2014
* Author: Pimenta
*/
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <set>
#include <map>
#include <string>
using namespace std;
typedef uint32_t uword_t;
#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif
#ifndef WORD_WIDTH
#define WORD_WIDTH 32
#endif
struct ObjectFile32 {
uword_t offset;
uword_t text_offset;
map<string, uword_t> exported;
map<string, set<uword_t>> imported;
set<uword_t> absolute;
uword_t mem_size;
uword_t* mem;
~ObjectFile32() {
delete[] mem;
}
void initStart() {
offset = 0;
text_offset = 0;
imported["start"].emplace(2);
mem_size = 3;
mem = new uword_t[3];
mem[0] = 0;
mem[1] = 0;
mem[2] = 0;
}
void read(const char* fn, uword_t offs) {
offset = offs;
fstream f(fn, fstream::in | fstream::binary);
uword_t tmp;
// read text section offset
f.read((char*)&text_offset, sizeof(uword_t));
// read number of exported symbols
f.read((char*)&tmp, sizeof(uword_t));
// read exported symbols
for (uword_t i = 0; i < tmp; ++i) {
string sym;
uword_t addr;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
// address
f.read((char*)&addr, sizeof(uword_t));
exported[sym] = addr;
}
// read number of symbols of pending references
f.read((char*)&tmp, sizeof(uword_t));
// read symbols of pending references
for (uword_t i = 0; i < tmp; ++i) {
string sym;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
uword_t tmp2;
// read number of references to current symbol
f.read((char*)&tmp2, sizeof(uword_t));
// read references to current symbol
for (uword_t j = 0; j < tmp2; ++j) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
imported[sym].emplace(addr);
}
}
// read number of absolute addresses
f.read((char*)&tmp, sizeof(uword_t));
// read absolute addresses
for (uword_t i = 0; i < tmp; ++i) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
absolute.emplace(addr);
}
// read assembled code size
f.read((char*)&mem_size, sizeof(uword_t));
// read assembled code
mem = new uword_t[mem_size];
f.read((char*)mem, sizeof(uword_t)*mem_size);
f.close();
}
};
int linker32(int argc, char* argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage mode: subleq-ld <object_files...> <meminit_file>\n");
return 0;
}
// read object files
ObjectFile32 files[argc - 1];
files[0].initStart();
for (int i = 1; i < argc - 1; ++i)
files[i].read(argv[i], files[i - 1].offset + files[i - 1].mem_size);
uword_t mem_size = 0;
uword_t* mem = new uword_t[MEM_WORDS];
map<string, uword_t> symbols;
map<string, set<uword_t>> references;
set<uword_t> absolutes;
for (auto& file : files) {
// assemble global symbol table
for (auto& sym : file.exported) {
symbols[sym.first] = sym.second + file.offset;
}
// assemble global reference table
for (auto& sym : file.imported) {
set<uword_t>& refs = references[sym.first];
for (auto addr : sym.second) {
refs.emplace(addr + file.offset);
}
}
// assemble global absolute address table
for (auto addr : file.absolute) {
absolutes.emplace(addr + file.offset);
}
// relocate addresses
for (uword_t i = file.text_offset; i < file.mem_size; ++i) {
auto it = file.absolute.find(i);
if (it == file.absolute.end()) {
file.mem[i] += file.offset;
}
}
// copy object code
memcpy(&mem[mem_size], file.mem, file.mem_size*sizeof(uword_t));
mem_size += file.mem_size;
}
// solve references
for (auto ref = references.begin(); ref != references.end();) {
auto sym = symbols.find(ref->first);
if (sym == symbols.end()) {
ref++;
}
else {
for (auto addr : ref->second) {
mem[addr] = sym->second;
}
references.erase(ref++);
}
}
// output mif
fstream f(argv[argc - 1], fstream::out);
char buf[20];
f << "DEPTH = " << MEM_WORDS << ";\n";
f << "WIDTH = " << WORD_WIDTH << ";\n";
f << "ADDRESS_RADIX = HEX;\n";
f << "DATA_RADIX = HEX;\n";
f << "CONTENT\n";
f << "BEGIN\n";
f << "\n";
for (uword_t i = 0; i < mem_size; ++i) {
sprintf(buf, "%08x", i);
f << buf;
sprintf(buf, "%08x", mem[i]);
f << " : " << buf << ";\n";
}
f << "\n";
f << "END;\n";
f.close();
delete[] mem;
return 0;
}
<|endoftext|> |
<commit_before>#include "Constraints.h"
namespace Analytics {
Constraints::Constraints() {
}
/**
* Add an item constraint of a given constraint type. When
* frequent itemsets are being generated, only those will be considered
* that match the constraints defined here.
*
* @param item
* An item name.
* @param type
* The constraint type.
*/
void Constraints::addItemConstraint(ItemName item, ItemConstraintType type) {
if (!this->itemConstraints.contains(type))
this->itemConstraints.insert(type, QSet<ItemName>());
this->itemConstraints[type].insert(item);
}
/**
* Set the requirements for frequent itemset. Wildcards are allowed, e.g.
* "episode:*" will match "episode:foo", "episode:bar", etc.
*
* Note: wilcard items will be expanded to their corresponding item ids in
* FPGrowth::scanTransactions().
*
* @param contraints
* A list of constraints.
* @param type
* The item constraint type.
*/
void Constraints::setItemConstraints(const QSet<ItemName> & constraints, ItemConstraintType type) {
this->itemConstraints.insert(type, constraints);
}
/**
* Consider the given item for use with constraints: store its item id in
* an optimized data structure to allow for fast constraint checking
* during frequent itemset generation.
*
* @param name
* An item name.
* @param id
* The corresponding item ID.
*/
void Constraints::preprocessItem(const ItemName & name, ItemID id) {
QRegExp rx;
rx.setPatternSyntax(QRegExp::Wildcard);
// Store the item IDs that correspond to the wildcard item
// constraints.
ItemConstraintType constraintType;
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
constraintType = (ItemConstraintType) i;
if (!this->itemConstraints.contains(constraintType))
continue;
foreach (ItemName constraint, this->itemConstraints[constraintType]) {
// Map ItemNames to ItemIDs.
if (constraint.compare(name) == 0) {
this->addPreprocessedItemConstraint(constraintType, "non-wildcards", id);
}
// Map ItemNames with wildcards in them to *all* corresponding
// ItemIDs.
else if (constraint.contains('*')) {
rx.setPattern(constraint);
if (rx.exactMatch(name))
this->addPreprocessedItemConstraint(constraintType, constraint, id);
}
}
}
}
/**
* Remove the given item id from the optimized constraint storage data
* structure, because it is infrequent.
*
* @param id
* The item id to remove.
*/
void Constraints::removeItem(ItemID id) {
ItemConstraintType type;
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
type = (ItemConstraintType) i;
if (!this->preprocessedItemConstraints.contains(type))
continue;
foreach (ItemName constraint, this->preprocessedItemConstraints[type].keys())
this->preprocessedItemConstraints[type][constraint].remove(id);
}
}
/**
* Check if the given itemset matches the defined constraints.
*
* @param itemset
* An itemset to check the constraints for.
* @return
* True if the itemset matches the constraints, false otherwise.
*/
bool Constraints::matchItemset(const ItemIDList & itemset) const {
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
ItemConstraintType type = (ItemConstraintType) i;
foreach (ItemName category, this->preprocessedItemConstraints[type].keys()) {
if (!Constraints::matchItemsetHelper(itemset, type, this->preprocessedItemConstraints[type][category]))
return false;
}
}
return true;
}
/**
* Check if a particular frequent itemset search space will be able to
* match the defined constraints. We can do this by matching all
* constraints over the itemset *and* prefix paths support count
* simultaneously (since this itemset will be extended with portions of
* the prefix paths).
*
* @param itemset
* An itemset to check the constraints for.
* @param prefixPathsSupportCounts
* A list of support counts for the prefix paths in this search space.
* @return
* True if the itemset matches the constraints, false otherwise.
*/
bool Constraints::matchSearchSpace(const ItemIDList & frequentItemset, const QHash<ItemID, SupportCount> & prefixPathsSupportCounts) const {
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
ItemConstraintType type = (ItemConstraintType) i;
foreach (ItemName category, this->preprocessedItemConstraints[type].keys()) {
if (!Constraints::matchSearchSpaceHelper(frequentItemset, prefixPathsSupportCounts, type, this->preprocessedItemConstraints[type][category]))
return false;
}
}
return true;
}
//------------------------------------------------------------------------
// Protected methods.
/**
* Helper function for Constraints::matchItemSet().
*/
bool Constraints::matchItemsetHelper(const ItemIDList & itemset, ItemConstraintType type, const QSet<ItemID> & constraintItems) {
foreach (ItemID id, constraintItems) {
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
if (!itemset.contains(id))
return false;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
if (itemset.contains(id))
return true;
break;
case CONSTRAINT_NEGATIVE_MATCH_ALL:
if (itemset.contains(id))
return false;
break;
case CONSTRAINT_NEGATIVE_MATCH_ANY:
if (!itemset.contains(id))
return true;
break;
}
}
// In case we haven't returned yet: in the case of the "all matches",
// this is a good thing, since we haven't had any bad encounters.
// Hence we return true for those. For the "any matches", it's the
// other way around.
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
case CONSTRAINT_NEGATIVE_MATCH_ALL:
return true;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
case CONSTRAINT_NEGATIVE_MATCH_ANY:
return false;
break;
}
// Satisfy the compiler.
return false;
}
/**
* Helper function for Constraints::matchSearchSpace().
*/
bool Constraints::matchSearchSpaceHelper(const ItemIDList & frequentItemset, const QHash<ItemID, SupportCount> & prefixPathsSupportCounts, ItemConstraintType type, const QSet<ItemID> & constraintItems) {
foreach (ItemID id, constraintItems) {
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
if (!frequentItemset.contains(id) && prefixPathsSupportCounts[id] == 0)
return false;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
if (frequentItemset.contains(id) || prefixPathsSupportCounts[id] > 0)
return true;
break;
case CONSTRAINT_NEGATIVE_MATCH_ALL:
if (prefixPathsSupportCounts[id] > 0)
return false;
break;
case CONSTRAINT_NEGATIVE_MATCH_ANY:
if (prefixPathsSupportCounts[id] == 0)
return true;
break;
}
}
// In case we haven't returned yet: in the case of the "all matches",
// this is a good thing, since we haven't had any bad encounters.
// Hence we return true or those. For the "any matches", it's the
// other way around.
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
case CONSTRAINT_NEGATIVE_MATCH_ALL:
return true;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
case CONSTRAINT_NEGATIVE_MATCH_ANY:
return false;
break;
}
// Satisfy the compiler.
return false;
}
/**
* Store a preprocessed item constraint in the optimized constraint data
* structure.
*
* @param type
* The item constraint type.
* @param category
* The category, either "non-wildcards" or a constraint that contains a
* wildcard ('*').
* @param id
* The item id.
*/
void Constraints::addPreprocessedItemConstraint(ItemConstraintType type, const ItemName & category, ItemID id) {
if (!this->preprocessedItemConstraints.contains(type))
this->preprocessedItemConstraints.insert(type, QHash<ItemName, QSet<ItemID> >());
if (!this->preprocessedItemConstraints[type].contains(category))
this->preprocessedItemConstraints[type].insert(category, QSet<ItemID>());
this->preprocessedItemConstraints[type][category].insert(id);
}
}
<commit_msg>Fix minor typo<commit_after>#include "Constraints.h"
namespace Analytics {
Constraints::Constraints() {
}
/**
* Add an item constraint of a given constraint type. When
* frequent itemsets are being generated, only those will be considered
* that match the constraints defined here.
*
* @param item
* An item name.
* @param type
* The constraint type.
*/
void Constraints::addItemConstraint(ItemName item, ItemConstraintType type) {
if (!this->itemConstraints.contains(type))
this->itemConstraints.insert(type, QSet<ItemName>());
this->itemConstraints[type].insert(item);
}
/**
* Set the requirements for frequent itemset. Wildcards are allowed, e.g.
* "episode:*" will match "episode:foo", "episode:bar", etc.
*
* Note: wilcard items will be expanded to their corresponding item ids in
* FPGrowth::scanTransactions().
*
* @param contraints
* A list of constraints.
* @param type
* The item constraint type.
*/
void Constraints::setItemConstraints(const QSet<ItemName> & constraints, ItemConstraintType type) {
this->itemConstraints.insert(type, constraints);
}
/**
* Consider the given item for use with constraints: store its item id in
* an optimized data structure to allow for fast constraint checking
* during frequent itemset generation.
*
* @param name
* An item name.
* @param id
* The corresponding item ID.
*/
void Constraints::preprocessItem(const ItemName & name, ItemID id) {
QRegExp rx;
rx.setPatternSyntax(QRegExp::Wildcard);
// Store the item IDs that correspond to the wildcard item
// constraints.
ItemConstraintType constraintType;
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
constraintType = (ItemConstraintType) i;
if (!this->itemConstraints.contains(constraintType))
continue;
foreach (ItemName constraint, this->itemConstraints[constraintType]) {
// Map ItemNames to ItemIDs.
if (constraint.compare(name) == 0) {
this->addPreprocessedItemConstraint(constraintType, "non-wildcards", id);
}
// Map ItemNames with wildcards in them to *all* corresponding
// ItemIDs.
else if (constraint.contains('*')) {
rx.setPattern(constraint);
if (rx.exactMatch(name))
this->addPreprocessedItemConstraint(constraintType, constraint, id);
}
}
}
}
/**
* Remove the given item id from the optimized constraint storage data
* structure, because it is infrequent.
*
* @param id
* The item id to remove.
*/
void Constraints::removeItem(ItemID id) {
ItemConstraintType type;
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
type = (ItemConstraintType) i;
if (!this->preprocessedItemConstraints.contains(type))
continue;
foreach (ItemName constraint, this->preprocessedItemConstraints[type].keys())
this->preprocessedItemConstraints[type][constraint].remove(id);
}
}
/**
* Check if the given itemset matches the defined constraints.
*
* @param itemset
* An itemset to check the constraints for.
* @return
* True if the itemset matches the constraints, false otherwise.
*/
bool Constraints::matchItemset(const ItemIDList & itemset) const {
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
ItemConstraintType type = (ItemConstraintType) i;
foreach (ItemName category, this->preprocessedItemConstraints[type].keys()) {
if (!Constraints::matchItemsetHelper(itemset, type, this->preprocessedItemConstraints[type][category]))
return false;
}
}
return true;
}
/**
* Check if a particular frequent itemset search space will be able to
* match the defined constraints. We can do this by matching all
* constraints over the itemset *and* prefix paths support counts
* simultaneously (since this itemset will be extended with portions of
* the prefix paths).
*
* @param itemset
* An itemset to check the constraints for.
* @param prefixPathsSupportCounts
* A list of support counts for the prefix paths in this search space.
* @return
* True if the itemset matches the constraints, false otherwise.
*/
bool Constraints::matchSearchSpace(const ItemIDList & frequentItemset, const QHash<ItemID, SupportCount> & prefixPathsSupportCounts) const {
for (int i = CONSTRAINT_POSITIVE_MATCH_ALL; i <= CONSTRAINT_NEGATIVE_MATCH_ANY; i++) {
ItemConstraintType type = (ItemConstraintType) i;
foreach (ItemName category, this->preprocessedItemConstraints[type].keys()) {
if (!Constraints::matchSearchSpaceHelper(frequentItemset, prefixPathsSupportCounts, type, this->preprocessedItemConstraints[type][category]))
return false;
}
}
return true;
}
//------------------------------------------------------------------------
// Protected methods.
/**
* Helper function for Constraints::matchItemSet().
*/
bool Constraints::matchItemsetHelper(const ItemIDList & itemset, ItemConstraintType type, const QSet<ItemID> & constraintItems) {
foreach (ItemID id, constraintItems) {
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
if (!itemset.contains(id))
return false;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
if (itemset.contains(id))
return true;
break;
case CONSTRAINT_NEGATIVE_MATCH_ALL:
if (itemset.contains(id))
return false;
break;
case CONSTRAINT_NEGATIVE_MATCH_ANY:
if (!itemset.contains(id))
return true;
break;
}
}
// In case we haven't returned yet: in the case of the "all matches",
// this is a good thing, since we haven't had any bad encounters.
// Hence we return true for those. For the "any matches", it's the
// other way around.
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
case CONSTRAINT_NEGATIVE_MATCH_ALL:
return true;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
case CONSTRAINT_NEGATIVE_MATCH_ANY:
return false;
break;
}
// Satisfy the compiler.
return false;
}
/**
* Helper function for Constraints::matchSearchSpace().
*/
bool Constraints::matchSearchSpaceHelper(const ItemIDList & frequentItemset, const QHash<ItemID, SupportCount> & prefixPathsSupportCounts, ItemConstraintType type, const QSet<ItemID> & constraintItems) {
foreach (ItemID id, constraintItems) {
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
if (!frequentItemset.contains(id) && prefixPathsSupportCounts[id] == 0)
return false;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
if (frequentItemset.contains(id) || prefixPathsSupportCounts[id] > 0)
return true;
break;
case CONSTRAINT_NEGATIVE_MATCH_ALL:
if (prefixPathsSupportCounts[id] > 0)
return false;
break;
case CONSTRAINT_NEGATIVE_MATCH_ANY:
if (prefixPathsSupportCounts[id] == 0)
return true;
break;
}
}
// In case we haven't returned yet: in the case of the "all matches",
// this is a good thing, since we haven't had any bad encounters.
// Hence we return true or those. For the "any matches", it's the
// other way around.
switch (type) {
case CONSTRAINT_POSITIVE_MATCH_ALL:
case CONSTRAINT_NEGATIVE_MATCH_ALL:
return true;
break;
case CONSTRAINT_POSITIVE_MATCH_ANY:
case CONSTRAINT_NEGATIVE_MATCH_ANY:
return false;
break;
}
// Satisfy the compiler.
return false;
}
/**
* Store a preprocessed item constraint in the optimized constraint data
* structure.
*
* @param type
* The item constraint type.
* @param category
* The category, either "non-wildcards" or a constraint that contains a
* wildcard ('*').
* @param id
* The item id.
*/
void Constraints::addPreprocessedItemConstraint(ItemConstraintType type, const ItemName & category, ItemID id) {
if (!this->preprocessedItemConstraints.contains(type))
this->preprocessedItemConstraints.insert(type, QHash<ItemName, QSet<ItemID> >());
if (!this->preprocessedItemConstraints[type].contains(category))
this->preprocessedItemConstraints[type].insert(category, QSet<ItemID>());
this->preprocessedItemConstraints[type][category].insert(id);
}
}
<|endoftext|> |
<commit_before>#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/rnea.hpp"
#include <iostream>
#include "pinocchio/tools/timer.hpp"
//#define __SSE3__
#include <fenv.h>
#ifdef __SSE3__
#include <pmmintrin.h>
#endif
int main()
{
#ifdef __SSE3__
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
#endif
using namespace Eigen;
using namespace se3;
se3::Model model;
model.addBody(model.getBodyId("universe"),JointModelFreeFlyer(),SE3::Random(),Inertia::Random(),"root");
model.addBody(model.getBodyId("root"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg1");
model.addBody(model.getBodyId("rleg1"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg2");
model.addBody(model.getBodyId("rleg2"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg3");
model.addBody(model.getBodyId("rleg3"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg4");
model.addBody(model.getBodyId("rleg4"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg5");
model.addBody(model.getBodyId("rleg5"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg6");
model.addBody(model.getBodyId("root"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg1");
model.addBody(model.getBodyId("lleg1"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg2");
model.addBody(model.getBodyId("lleg2"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg3");
model.addBody(model.getBodyId("lleg3"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg4");
model.addBody(model.getBodyId("lleg4"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg5");
model.addBody(model.getBodyId("lleg5"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg6");
model.addBody(model.getBodyId("root"),JointModelRX(),SE3::Random(),Inertia::Random(),"torso1");
model.addBody(model.getBodyId("torso1"),JointModelRX(),SE3::Random(),Inertia::Random(),"torso2");
//model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"torso3");
model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"neck1");
model.addBody(model.getBodyId("neck1"),JointModelRX(),SE3::Random(),Inertia::Random(),"neck2");
//model.addBody(model.getBodyId("neck2"),JointModelRX(),SE3::Random(),Inertia::Random(),"neck3");
model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm1");
model.addBody(model.getBodyId("rarm1"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm2");
model.addBody(model.getBodyId("rarm2"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm3");
model.addBody(model.getBodyId("rarm3"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm4");
model.addBody(model.getBodyId("rarm4"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm5");
model.addBody(model.getBodyId("rarm5"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm6");
model.addBody(model.getBodyId("rarm6"),JointModelRX(),SE3::Random(),Inertia::Random(),"rgrip");
model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm1");
model.addBody(model.getBodyId("larm1"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm2");
model.addBody(model.getBodyId("larm2"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm3");
model.addBody(model.getBodyId("larm3"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm4");
model.addBody(model.getBodyId("larm4"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm5");
model.addBody(model.getBodyId("larm5"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm6");
model.addBody(model.getBodyId("larm6"),JointModelRX(),SE3::Random(),Inertia::Random(),"lgrip");
se3::Data data(model);
data.v[0] = Motion::Zero();
data.a[0] = -model.gravity;
VectorXd q = VectorXd::Random(model.nq);
VectorXd v = VectorXd::Random(model.nv);
VectorXd a = VectorXd::Random(model.nv);
StackTicToc timer(StackTicToc::US); timer.tic();
SMOOTH(1000)
{
rnea(model,data,q,v,a);
}
timer.toc(std::cout,1000);
return 0;
}
<commit_msg>Increase the timing sample in RNEA: 4.8us on a 64x.<commit_after>#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/rnea.hpp"
#include <iostream>
#include "pinocchio/tools/timer.hpp"
//#define __SSE3__
#include <fenv.h>
#ifdef __SSE3__
#include <pmmintrin.h>
#endif
int main()
{
#ifdef __SSE3__
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
#endif
using namespace Eigen;
using namespace se3;
se3::Model model;
model.addBody(model.getBodyId("universe"),JointModelFreeFlyer(),SE3::Random(),Inertia::Random(),"root");
model.addBody(model.getBodyId("root"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg1");
model.addBody(model.getBodyId("rleg1"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg2");
model.addBody(model.getBodyId("rleg2"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg3");
model.addBody(model.getBodyId("rleg3"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg4");
model.addBody(model.getBodyId("rleg4"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg5");
model.addBody(model.getBodyId("rleg5"),JointModelRX(),SE3::Random(),Inertia::Random(),"rleg6");
model.addBody(model.getBodyId("root"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg1");
model.addBody(model.getBodyId("lleg1"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg2");
model.addBody(model.getBodyId("lleg2"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg3");
model.addBody(model.getBodyId("lleg3"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg4");
model.addBody(model.getBodyId("lleg4"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg5");
model.addBody(model.getBodyId("lleg5"),JointModelRX(),SE3::Random(),Inertia::Random(),"lleg6");
model.addBody(model.getBodyId("root"),JointModelRX(),SE3::Random(),Inertia::Random(),"torso1");
model.addBody(model.getBodyId("torso1"),JointModelRX(),SE3::Random(),Inertia::Random(),"torso2");
//model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"torso3");
model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"neck1");
model.addBody(model.getBodyId("neck1"),JointModelRX(),SE3::Random(),Inertia::Random(),"neck2");
//model.addBody(model.getBodyId("neck2"),JointModelRX(),SE3::Random(),Inertia::Random(),"neck3");
model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm1");
model.addBody(model.getBodyId("rarm1"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm2");
model.addBody(model.getBodyId("rarm2"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm3");
model.addBody(model.getBodyId("rarm3"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm4");
model.addBody(model.getBodyId("rarm4"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm5");
model.addBody(model.getBodyId("rarm5"),JointModelRX(),SE3::Random(),Inertia::Random(),"rarm6");
model.addBody(model.getBodyId("rarm6"),JointModelRX(),SE3::Random(),Inertia::Random(),"rgrip");
model.addBody(model.getBodyId("torso2"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm1");
model.addBody(model.getBodyId("larm1"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm2");
model.addBody(model.getBodyId("larm2"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm3");
model.addBody(model.getBodyId("larm3"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm4");
model.addBody(model.getBodyId("larm4"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm5");
model.addBody(model.getBodyId("larm5"),JointModelRX(),SE3::Random(),Inertia::Random(),"larm6");
model.addBody(model.getBodyId("larm6"),JointModelRX(),SE3::Random(),Inertia::Random(),"lgrip");
se3::Data data(model);
data.v[0] = Motion::Zero();
data.a[0] = -model.gravity;
VectorXd q = VectorXd::Random(model.nq);
VectorXd v = VectorXd::Random(model.nv);
VectorXd a = VectorXd::Random(model.nv);
StackTicToc timer(StackTicToc::US); timer.tic();
SMOOTH(100000)
{
rnea(model,data,q,v,a);
}
timer.toc(std::cout,100000);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STRING_HPP
# define STRING_HPP
#include <cstring>
#include <algorithm>
#include <string>
namespace generic
{
// join
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type const sep)
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.cend());
for (typename C::const_iterator i(container.cbegin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type::value_type const sep)
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.cend());
for (typename C::const_iterator i(container.cbegin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
// trim
//////////////////////////////////////////////////////////////////////////////
inline ::std::string& ltrim(::std::string& s)
{
s.erase(s.begin(), ::std::find_if(s.begin(), s.end(),
[](char const c){ return !::std::isspace(c); }));
return s;
}
inline ::std::string& rtrim(::std::string& s)
{
s.erase(s.begin(), ::std::find_if(s.begin(), s.end(),
[](char const c){ return !::std::isspace(c); }));
return s;
}
inline ::std::string& trim(::std::string& s)
{
return ltrim(rtrim(s));
}
}
#endif // STRING_HPP
<commit_msg>some fixes<commit_after>#ifndef STRING_HPP
# define STRING_HPP
#include <cstring>
#include <algorithm>
#include <string>
namespace generic
{
// join
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type const sep)
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.cend());
for (typename C::const_iterator i(container.cbegin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type::value_type const sep)
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.cend());
for (typename C::const_iterator i(container.cbegin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
// trim
//////////////////////////////////////////////////////////////////////////////
inline ::std::string& ltrim(::std::string& s)
{
s.erase(s.begin(), ::std::find_if(s.begin(), s.end(),
[](char const c){ return !::std::isspace(c); }));
return s;
}
inline ::std::string& rtrim(::std::string& s)
{
s.erase(::std::find_if(s.rbegin(), s.rend(),
[](char const c){ return !::std::isspace(c); }).base(), s.end());
return s;
}
inline ::std::string& trim(::std::string& s)
{
return ltrim(rtrim(s));
}
}
#endif // STRING_HPP
<|endoftext|> |
<commit_before>// Copyright 2009 The RE2 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 "util/util.h"
#include "util/flags.h"
#include "util/benchmark.h"
#include "re2/re2.h"
DEFINE_string(test_tmpdir, "/var/tmp", "temp directory");
using testing::Benchmark;
using namespace re2;
static Benchmark* benchmarks[10000];
static int nbenchmarks;
void Benchmark::Register() {
benchmarks[nbenchmarks] = this;
if(lo < 1)
lo = 1;
if(hi < lo)
hi = lo;
nbenchmarks++;
}
static int64 nsec() {
#if defined(__APPLE__)
struct timeval tv;
if(gettimeofday(&tv, 0) < 0)
return -1;
return (int64)tv.tv_sec*1000*1000*1000 + tv.tv_usec*1000;
#elif defined(_WIN32)
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408.aspx
// describes how to query ticks and convert to microseconds. Of course,
// what we want in this case are nanoseconds. Also, note that .QuadPart
// is a signed 64-bit integer, so casting to int64 shouldn't be needed.
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
LARGE_INTEGER ticks;
QueryPerformanceCounter(&ticks);
ticks.QuadPart *= 1000*1000*1000;
ticks.QuadPart /= freq.QuadPart;
return ticks.QuadPart;
#else
struct timespec tp;
if(clock_gettime(CLOCK_REALTIME, &tp) < 0)
return -1;
return (int64)tp.tv_sec*1000*1000*1000 + tp.tv_nsec;
#endif
}
static int64 bytes;
static int64 ns;
static int64 t0;
static int64 items;
void SetBenchmarkBytesProcessed(long long x) {
bytes = x;
}
void StopBenchmarkTiming() {
if(t0 != 0)
ns += nsec() - t0;
t0 = 0;
}
void StartBenchmarkTiming() {
if(t0 == 0)
t0 = nsec();
}
void SetBenchmarkItemsProcessed(int n) {
items = n;
}
void BenchmarkMemoryUsage() {
// TODO(rsc): Implement.
}
int NumCPUs() {
return 1;
}
static void runN(Benchmark *b, int n, int siz) {
bytes = 0;
items = 0;
ns = 0;
t0 = nsec();
if(b->fn)
b->fn(n);
else if(b->fnr)
b->fnr(n, siz);
else {
fprintf(stderr, "%s: missing function\n", b->name);
exit(2);
}
if(t0 != 0)
ns += nsec() - t0;
}
static int round(int n) {
int base = 1;
while(base*10 < n)
base *= 10;
if(n < 2*base)
return 2*base;
if(n < 5*base)
return 5*base;
return 10*base;
}
void RunBench(Benchmark* b, int nthread, int siz) {
int n, last;
// TODO(rsc): Threaded benchmarks.
if(nthread != 1)
return;
// run once in case it's expensive
n = 1;
runN(b, n, siz);
while(ns < (int)1e9 && n < (int)1e9) {
last = n;
if(ns/n == 0)
n = (int)1e9;
else
n = (int)1e9 / static_cast<int>(ns/n);
n = max(last+1, min(n+n/2, 100*last));
n = round(n);
runN(b, n, siz);
}
char mb[100];
char suf[100];
mb[0] = '\0';
suf[0] = '\0';
if(ns > 0 && bytes > 0)
snprintf(mb, sizeof mb, "\t%7.2f MB/s", ((double)bytes/1e6)/((double)ns/1e9));
if(b->fnr || b->lo != b->hi) {
if(siz >= (1<<20))
snprintf(suf, sizeof suf, "/%dM", siz/(1<<20));
else if(siz >= (1<<10))
snprintf(suf, sizeof suf, "/%dK", siz/(1<<10));
else
snprintf(suf, sizeof suf, "/%d", siz);
}
printf("%s%s\t%8lld\t%10lld ns/op%s\n", b->name, suf, (long long)n, (long long)ns/n, mb);
fflush(stdout);
}
static int match(const char* name, int argc, const char** argv) {
if(argc == 1)
return 1;
for(int i = 1; i < argc; i++)
if(RE2::PartialMatch(name, argv[i]))
return 1;
return 0;
}
int main(int argc, const char** argv) {
for(int i = 0; i < nbenchmarks; i++) {
Benchmark* b = benchmarks[i];
if(match(b->name, argc, argv))
for(int j = b->threadlo; j <= b->threadhi; j++)
for(int k = max(b->lo, 1); k <= max(b->hi, 1); k<<=1)
RunBench(b, j, k);
}
}
<commit_msg>Prefer CPU time (when available) for benchmarks.<commit_after>// Copyright 2009 The RE2 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 "util/util.h"
#include "util/flags.h"
#include "util/benchmark.h"
#include "re2/re2.h"
DEFINE_string(test_tmpdir, "/var/tmp", "temp directory");
using testing::Benchmark;
using namespace re2;
static Benchmark* benchmarks[10000];
static int nbenchmarks;
void Benchmark::Register() {
benchmarks[nbenchmarks] = this;
if(lo < 1)
lo = 1;
if(hi < lo)
hi = lo;
nbenchmarks++;
}
static int64 nsec() {
#if defined(__APPLE__)
struct timeval tv;
if(gettimeofday(&tv, 0) < 0)
return -1;
return (int64)tv.tv_sec*1000*1000*1000 + tv.tv_usec*1000;
#elif defined(_WIN32)
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408.aspx
// describes how to query ticks and convert to microseconds. Of course,
// what we want in this case are nanoseconds. Also, note that .QuadPart
// is a signed 64-bit integer, so casting to int64 shouldn't be needed.
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
LARGE_INTEGER ticks;
QueryPerformanceCounter(&ticks);
ticks.QuadPart *= 1000*1000*1000;
ticks.QuadPart /= freq.QuadPart;
return ticks.QuadPart;
#else
struct timespec tp;
#ifdef CLOCK_PROCESS_CPUTIME_ID
if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp) < 0)
#else
if(clock_gettime(CLOCK_REALTIME, &tp) < 0)
#endif
return -1;
return (int64)tp.tv_sec*1000*1000*1000 + tp.tv_nsec;
#endif
}
static int64 bytes;
static int64 ns;
static int64 t0;
static int64 items;
void SetBenchmarkBytesProcessed(long long x) {
bytes = x;
}
void StopBenchmarkTiming() {
if(t0 != 0)
ns += nsec() - t0;
t0 = 0;
}
void StartBenchmarkTiming() {
if(t0 == 0)
t0 = nsec();
}
void SetBenchmarkItemsProcessed(int n) {
items = n;
}
void BenchmarkMemoryUsage() {
// TODO(rsc): Implement.
}
int NumCPUs() {
return 1;
}
static void runN(Benchmark *b, int n, int siz) {
bytes = 0;
items = 0;
ns = 0;
t0 = nsec();
if(b->fn)
b->fn(n);
else if(b->fnr)
b->fnr(n, siz);
else {
fprintf(stderr, "%s: missing function\n", b->name);
exit(2);
}
if(t0 != 0)
ns += nsec() - t0;
}
static int round(int n) {
int base = 1;
while(base*10 < n)
base *= 10;
if(n < 2*base)
return 2*base;
if(n < 5*base)
return 5*base;
return 10*base;
}
void RunBench(Benchmark* b, int nthread, int siz) {
int n, last;
// TODO(rsc): Threaded benchmarks.
if(nthread != 1)
return;
// run once in case it's expensive
n = 1;
runN(b, n, siz);
while(ns < (int)1e9 && n < (int)1e9) {
last = n;
if(ns/n == 0)
n = (int)1e9;
else
n = (int)1e9 / static_cast<int>(ns/n);
n = max(last+1, min(n+n/2, 100*last));
n = round(n);
runN(b, n, siz);
}
char mb[100];
char suf[100];
mb[0] = '\0';
suf[0] = '\0';
if(ns > 0 && bytes > 0)
snprintf(mb, sizeof mb, "\t%7.2f MB/s", ((double)bytes/1e6)/((double)ns/1e9));
if(b->fnr || b->lo != b->hi) {
if(siz >= (1<<20))
snprintf(suf, sizeof suf, "/%dM", siz/(1<<20));
else if(siz >= (1<<10))
snprintf(suf, sizeof suf, "/%dK", siz/(1<<10));
else
snprintf(suf, sizeof suf, "/%d", siz);
}
printf("%s%s\t%8lld\t%10lld ns/op%s\n", b->name, suf, (long long)n, (long long)ns/n, mb);
fflush(stdout);
}
static int match(const char* name, int argc, const char** argv) {
if(argc == 1)
return 1;
for(int i = 1; i < argc; i++)
if(RE2::PartialMatch(name, argv[i]))
return 1;
return 0;
}
int main(int argc, const char** argv) {
for(int i = 0; i < nbenchmarks; i++) {
Benchmark* b = benchmarks[i];
if(match(b->name, argc, argv))
for(int j = b->threadlo; j <= b->threadhi; j++)
for(int k = max(b->lo, 1); k <= max(b->hi, 1); k<<=1)
RunBench(b, j, k);
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "GemmConvOp.h"
#include "GemmFunctor.h"
#include "paddle/math/MemoryHandle.h"
namespace paddle {
/*
* imData = [input_channels, input_height, input_width]
* colData = [input_channels, filter_height, filter_width,
* output_height, output_width]
*/
template <class T>
class Im2ColFunctor<DEVICE_TYPE_CPU, T> {
public:
void operator()(const T* imData,
int inputChannels,
int inputHeight,
int inputWidth,
int filterHeight,
int filterWidth,
int strideHeight,
int strideWidth,
int paddingHeight,
int paddingWidth,
int outputHeight,
int outputWidth,
T* colData) {
int channelsCol = inputChannels * filterHeight * filterWidth;
for (int c = 0; c < channelsCol; ++c) {
int wOffset = c % filterWidth;
int hOffset = (c / filterWidth) % filterHeight;
int c_im = c / filterWidth / filterHeight;
for (int h = 0; h < outputHeight; ++h) {
for (int w = 0; w < outputWidth; ++w) {
int imRowIdx = h * strideHeight + hOffset;
int imColIdx = w * strideWidth + wOffset;
if ((imRowIdx - paddingHeight) < 0 ||
(imRowIdx - paddingHeight) >= inputHeight ||
(imColIdx - paddingWidth) < 0 ||
(imColIdx - paddingWidth) >= inputWidth) {
colData[(c * outputHeight + h) * outputWidth + w] = T(0);
} else {
imRowIdx += c_im * inputHeight - paddingHeight;
imColIdx -= paddingWidth;
colData[(c * outputHeight + h) * outputWidth + w] =
imData[imRowIdx * inputWidth + imColIdx];
}
}
}
}
}
};
template <class T>
class Col2ImFunctor<DEVICE_TYPE_CPU, T> {
public:
void operator()(const T* colData,
int inputChannels,
int inputHeight,
int inputWidth,
int filterHeight,
int filterWidth,
int strideHeight,
int strideWidth,
int paddingHeight,
int paddingWidth,
int outputHeight,
int outputWidth,
T* imData) {
int channelsCol = inputChannels * filterHeight * filterWidth;
for (int c = 0; c < channelsCol; ++c) {
int wOffset = c % filterWidth;
int hOffset = (c / filterWidth) % filterHeight;
int c_im = c / filterWidth / filterHeight;
for (int h = 0; h < outputHeight; ++h) {
for (int w = 0; w < outputWidth; ++w) {
int imRowIdx = h * strideHeight + hOffset;
int imColIdx = w * strideWidth + wOffset;
if ((imRowIdx - paddingHeight) >= 0 &&
(imRowIdx - paddingHeight) < inputHeight &&
(imColIdx - paddingWidth) >= 0 &&
(imColIdx - paddingWidth) < inputWidth) {
imRowIdx += c_im * inputHeight - paddingHeight;
imColIdx -= paddingWidth;
imData[imRowIdx * inputWidth + imColIdx] +=
colData[(c * outputHeight + h) * outputWidth + w];
}
}
}
}
}
};
/*
* \brief Forward calculation of convolution.
*/
template <DeviceType Device>
class GemmConvFunction : public ConvFunctionBase {
public:
void init(const FuncConfig& config) override {
ConvFunctionBase::init(config);
}
void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
CHECK_EQ(numInputs_, inputs.size());
CHECK_EQ(numOutputs_, outputs.size());
// TODO(hedaoyuan): Need to define some index macros,
// to avoid useing 0 and 1.
const TensorShape& input = inputs[0].shape();
const TensorShape& filter = inputs[1].shape();
const TensorShape& output = outputs[0].shape();
check(input, filter, output);
real beta;
if (outputs[0].getArgType() == ADD_TO) {
beta = 1.0;
} else {
beta = 0.0;
}
size_t batchSize = inputs[0].shape()[0];
size_t inputChannels = inputs[0].shape()[1];
size_t inputHeight = inputs[0].shape()[2];
size_t inputWidth = inputs[0].shape()[3];
size_t filterHeight = inputs[1].shape()[2];
size_t filterWidth = inputs[1].shape()[3];
size_t outputChannels = outputs[0].shape()[1];
size_t outputHeight = outputs[0].shape()[2];
size_t outputWidth = outputs[0].shape()[3];
real* inputData = inputs[0].data<real>();
real* filterData = inputs[1].data<real>();
real* outputData = outputs[0].data<real>();
size_t size = inputChannels / groups_ * filterHeight * filterWidth *
outputHeight * outputWidth;
resizeBuffer<Device>(size);
real* colData = reinterpret_cast<real*>(memory_->getBuf());
Im2ColFunctor<Device, real> im2col;
GemmFunctor<Device, real> gemm;
size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
size_t outputOffset =
(outputChannels / groups_) * outputHeight * outputWidth;
size_t filterOffset = inputs[1].shape().getElements() / groups_;
for (size_t i = 0; i < batchSize; i++) {
for (size_t g = 0; g < groups_; g++) {
im2col(inputData + g * inputOffset,
inputChannels / groups_,
inputHeight,
inputWidth,
filterHeight,
filterWidth,
strideH(),
strideW(),
paddingH(),
paddingW(),
outputHeight,
outputWidth,
colData);
int M = outputChannels / groups_;
int N = outputHeight * outputWidth;
int K = inputChannels / groups_ * filterHeight * filterWidth;
gemm(CblasNoTrans,
CblasNoTrans,
M,
N,
K,
1.0f,
filterData + g * filterOffset,
K,
colData,
N,
beta,
outputData + g * outputOffset,
N);
}
inputData += inputChannels * inputHeight * inputWidth;
outputData += outputChannels * outputHeight * outputWidth;
}
}
};
/*
* \brief Backward input calculation of convolution.
*/
template <DeviceType Device>
class GemmConvGradInputFunction : public ConvFunctionBase {
public:
void init(const FuncConfig& config) override {
ConvFunctionBase::init(config);
}
void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
CHECK_EQ(numInputs_, inputs.size());
CHECK_EQ(numOutputs_, outputs.size());
// CHECK_EQ(outputs[0].getArgType(), ADD_TO);
const TensorShape& output = inputs[0].shape();
const TensorShape& filter = inputs[1].shape();
const TensorShape& input = outputs[0].shape();
check(input, filter, output);
size_t batchSize = input[0];
size_t inputChannels = input[1];
size_t inputHeight = input[2];
size_t inputWidth = input[3];
size_t filterHeight = filter[2];
size_t filterWidth = filter[3];
size_t outputChannels = output[1];
size_t outputHeight = output[2];
size_t outputWidth = output[3];
real* outputGrad = inputs[0].data<real>();
real* filterData = inputs[1].data<real>();
real* inputGrad = outputs[0].data<real>();
size_t size = inputChannels / groups_ * filterHeight * filterWidth *
outputHeight * outputWidth;
resizeBuffer<Device>(size);
real* colData = reinterpret_cast<real*>(memory_->getBuf());
Col2ImFunctor<Device, real> col2im;
GemmFunctor<Device, real> gemm;
size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
size_t outputOffset =
(outputChannels / groups_) * outputHeight * outputWidth;
size_t filterOffset = filter.getElements() / groups_;
for (size_t i = 0; i < batchSize; i++) {
for (size_t g = 0; g < groups_; g++) {
int K = outputChannels / groups_;
int N = outputHeight * outputWidth;
int M = inputChannels / groups_ * filterHeight * filterWidth;
gemm(CblasTrans,
CblasNoTrans,
M,
N,
K,
1.0f,
filterData + g * filterOffset,
M,
outputGrad + g * outputOffset,
N,
0.0f,
colData,
N);
col2im(colData,
inputChannels / groups_,
inputHeight,
inputWidth,
filterHeight,
filterWidth,
strideH(),
strideW(),
paddingH(),
paddingW(),
outputHeight,
outputWidth,
inputGrad + g * inputOffset);
}
inputGrad += inputChannels * inputHeight * inputWidth;
outputGrad += outputChannels * outputHeight * outputWidth;
}
}
};
/*
* \brief Backward filter calculation of convolution.
*/
template <DeviceType Device>
class GemmConvGradFilterFunction : public ConvFunctionBase {
public:
void init(const FuncConfig& config) override {
ConvFunctionBase::init(config);
}
void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
CHECK_EQ(numInputs_, inputs.size());
CHECK_EQ(numOutputs_, outputs.size());
const TensorShape& output = inputs[0].shape();
const TensorShape& input = inputs[1].shape();
const TensorShape& filter = outputs[0].shape();
check(input, filter, output);
real beta;
if (outputs[0].getArgType() == ADD_TO) {
beta = 1.0;
} else {
beta = 0.0;
}
size_t batchSize = input[0];
size_t inputChannels = input[1];
size_t inputHeight = input[2];
size_t inputWidth = input[3];
size_t filterHeight = filter[2];
size_t filterWidth = filter[3];
size_t outputChannels = output[1];
size_t outputHeight = output[2];
size_t outputWidth = output[3];
real* outputGrad = inputs[0].data<real>();
real* inputData = inputs[1].data<real>();
real* filterGrad = outputs[0].data<real>();
size_t size = inputChannels / groups_ * filterHeight * filterWidth *
outputHeight * outputWidth;
resizeBuffer<Device>(size);
real* colData = reinterpret_cast<real*>(memory_->getBuf());
Im2ColFunctor<Device, real> im2col;
GemmFunctor<Device, real> gemm;
size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
size_t outputOffset =
(outputChannels / groups_) * outputHeight * outputWidth;
size_t filterOffset = filter.getElements() / groups_;
for (size_t i = 0; i < batchSize; i++) {
for (size_t g = 0; g < groups_; g++) {
im2col(inputData + g * inputOffset,
inputChannels / groups_,
inputHeight,
inputWidth,
filterHeight,
filterWidth,
strideH(),
strideW(),
paddingH(),
paddingW(),
outputHeight,
outputWidth,
colData);
int M = outputChannels / groups_;
int K = outputHeight * outputWidth;
int N = inputChannels / groups_ * filterHeight * filterWidth;
gemm(CblasNoTrans,
CblasTrans,
M,
N,
K,
1.0f,
outputGrad + g * outputOffset,
K,
colData,
K,
i == 0 ? beta : 1.0f,
filterGrad + g * filterOffset,
N);
}
inputData += inputChannels * inputHeight * inputWidth;
outputGrad += outputChannels * outputHeight * outputWidth;
}
}
};
REGISTER_TYPED_FUNC(GemmConv, CPU, GemmConvFunction);
REGISTER_TYPED_FUNC(GemmConvGradInput, CPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, CPU, GemmConvGradFilterFunction);
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(GemmConv, GPU, GemmConvFunction);
REGISTER_TYPED_FUNC(GemmConvGradInput, GPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, GPU, GemmConvGradFilterFunction);
#endif
} // namespace paddle
<commit_msg>format<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "GemmConvOp.h"
#include "GemmFunctor.h"
#include "paddle/math/MemoryHandle.h"
namespace paddle {
/*
* imData = [input_channels, input_height, input_width]
* colData = [input_channels, filter_height, filter_width,
* output_height, output_width]
*/
template <class T>
class Im2ColFunctor<DEVICE_TYPE_CPU, T> {
public:
void operator()(const T* imData,
int inputChannels,
int inputHeight,
int inputWidth,
int filterHeight,
int filterWidth,
int strideHeight,
int strideWidth,
int paddingHeight,
int paddingWidth,
int outputHeight,
int outputWidth,
T* colData) {
int channelsCol = inputChannels * filterHeight * filterWidth;
for (int c = 0; c < channelsCol; ++c) {
int wOffset = c % filterWidth;
int hOffset = (c / filterWidth) % filterHeight;
int c_im = c / filterWidth / filterHeight;
for (int h = 0; h < outputHeight; ++h) {
for (int w = 0; w < outputWidth; ++w) {
int imRowIdx = h * strideHeight + hOffset;
int imColIdx = w * strideWidth + wOffset;
if ((imRowIdx - paddingHeight) < 0 ||
(imRowIdx - paddingHeight) >= inputHeight ||
(imColIdx - paddingWidth) < 0 ||
(imColIdx - paddingWidth) >= inputWidth) {
colData[(c * outputHeight + h) * outputWidth + w] = T(0);
} else {
imRowIdx += c_im * inputHeight - paddingHeight;
imColIdx -= paddingWidth;
colData[(c * outputHeight + h) * outputWidth + w] =
imData[imRowIdx * inputWidth + imColIdx];
}
}
}
}
}
};
template <class T>
class Col2ImFunctor<DEVICE_TYPE_CPU, T> {
public:
void operator()(const T* colData,
int inputChannels,
int inputHeight,
int inputWidth,
int filterHeight,
int filterWidth,
int strideHeight,
int strideWidth,
int paddingHeight,
int paddingWidth,
int outputHeight,
int outputWidth,
T* imData) {
int channelsCol = inputChannels * filterHeight * filterWidth;
for (int c = 0; c < channelsCol; ++c) {
int wOffset = c % filterWidth;
int hOffset = (c / filterWidth) % filterHeight;
int c_im = c / filterWidth / filterHeight;
for (int h = 0; h < outputHeight; ++h) {
for (int w = 0; w < outputWidth; ++w) {
int imRowIdx = h * strideHeight + hOffset;
int imColIdx = w * strideWidth + wOffset;
if ((imRowIdx - paddingHeight) >= 0 &&
(imRowIdx - paddingHeight) < inputHeight &&
(imColIdx - paddingWidth) >= 0 &&
(imColIdx - paddingWidth) < inputWidth) {
imRowIdx += c_im * inputHeight - paddingHeight;
imColIdx -= paddingWidth;
imData[imRowIdx * inputWidth + imColIdx] +=
colData[(c * outputHeight + h) * outputWidth + w];
}
}
}
}
}
};
/*
* \brief Forward calculation of convolution.
*/
template <DeviceType Device>
class GemmConvFunction : public ConvFunctionBase {
public:
void init(const FuncConfig& config) override {
ConvFunctionBase::init(config);
}
void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
CHECK_EQ(numInputs_, inputs.size());
CHECK_EQ(numOutputs_, outputs.size());
// TODO(hedaoyuan): Need to define some index macros,
// to avoid useing 0 and 1.
const TensorShape& input = inputs[0].shape();
const TensorShape& filter = inputs[1].shape();
const TensorShape& output = outputs[0].shape();
check(input, filter, output);
real beta;
if (outputs[0].getArgType() == ADD_TO) {
beta = 1.0;
} else {
beta = 0.0;
}
size_t batchSize = inputs[0].shape()[0];
size_t inputChannels = inputs[0].shape()[1];
size_t inputHeight = inputs[0].shape()[2];
size_t inputWidth = inputs[0].shape()[3];
size_t filterHeight = inputs[1].shape()[2];
size_t filterWidth = inputs[1].shape()[3];
size_t outputChannels = outputs[0].shape()[1];
size_t outputHeight = outputs[0].shape()[2];
size_t outputWidth = outputs[0].shape()[3];
real* inputData = inputs[0].data<real>();
real* filterData = inputs[1].data<real>();
real* outputData = outputs[0].data<real>();
size_t size = inputChannels / groups_ * filterHeight * filterWidth *
outputHeight * outputWidth;
resizeBuffer<Device>(size);
real* colData = reinterpret_cast<real*>(memory_->getBuf());
Im2ColFunctor<Device, real> im2col;
GemmFunctor<Device, real> gemm;
size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
size_t outputOffset =
(outputChannels / groups_) * outputHeight * outputWidth;
size_t filterOffset = inputs[1].shape().getElements() / groups_;
for (size_t i = 0; i < batchSize; i++) {
for (size_t g = 0; g < groups_; g++) {
im2col(inputData + g * inputOffset,
inputChannels / groups_,
inputHeight,
inputWidth,
filterHeight,
filterWidth,
strideH(),
strideW(),
paddingH(),
paddingW(),
outputHeight,
outputWidth,
colData);
int M = outputChannels / groups_;
int N = outputHeight * outputWidth;
int K = inputChannels / groups_ * filterHeight * filterWidth;
gemm(CblasNoTrans,
CblasNoTrans,
M,
N,
K,
1.0f,
filterData + g * filterOffset,
K,
colData,
N,
beta,
outputData + g * outputOffset,
N);
}
inputData += inputChannels * inputHeight * inputWidth;
outputData += outputChannels * outputHeight * outputWidth;
}
}
};
/*
* \brief Backward input calculation of convolution.
*/
template <DeviceType Device>
class GemmConvGradInputFunction : public ConvFunctionBase {
public:
void init(const FuncConfig& config) override {
ConvFunctionBase::init(config);
}
void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
CHECK_EQ(numInputs_, inputs.size());
CHECK_EQ(numOutputs_, outputs.size());
// CHECK_EQ(outputs[0].getArgType(), ADD_TO);
const TensorShape& output = inputs[0].shape();
const TensorShape& filter = inputs[1].shape();
const TensorShape& input = outputs[0].shape();
check(input, filter, output);
size_t batchSize = input[0];
size_t inputChannels = input[1];
size_t inputHeight = input[2];
size_t inputWidth = input[3];
size_t filterHeight = filter[2];
size_t filterWidth = filter[3];
size_t outputChannels = output[1];
size_t outputHeight = output[2];
size_t outputWidth = output[3];
real* outputGrad = inputs[0].data<real>();
real* filterData = inputs[1].data<real>();
real* inputGrad = outputs[0].data<real>();
size_t size = inputChannels / groups_ * filterHeight * filterWidth *
outputHeight * outputWidth;
resizeBuffer<Device>(size);
real* colData = reinterpret_cast<real*>(memory_->getBuf());
Col2ImFunctor<Device, real> col2im;
GemmFunctor<Device, real> gemm;
size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
size_t outputOffset =
(outputChannels / groups_) * outputHeight * outputWidth;
size_t filterOffset = filter.getElements() / groups_;
for (size_t i = 0; i < batchSize; i++) {
for (size_t g = 0; g < groups_; g++) {
int K = outputChannels / groups_;
int N = outputHeight * outputWidth;
int M = inputChannels / groups_ * filterHeight * filterWidth;
gemm(CblasTrans,
CblasNoTrans,
M,
N,
K,
1.0f,
filterData + g * filterOffset,
M,
outputGrad + g * outputOffset,
N,
0.0f,
colData,
N);
col2im(colData,
inputChannels / groups_,
inputHeight,
inputWidth,
filterHeight,
filterWidth,
strideH(),
strideW(),
paddingH(),
paddingW(),
outputHeight,
outputWidth,
inputGrad + g * inputOffset);
}
inputGrad += inputChannels * inputHeight * inputWidth;
outputGrad += outputChannels * outputHeight * outputWidth;
}
}
};
/*
* \brief Backward filter calculation of convolution.
*/
template <DeviceType Device>
class GemmConvGradFilterFunction : public ConvFunctionBase {
public:
void init(const FuncConfig& config) override {
ConvFunctionBase::init(config);
}
void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
CHECK_EQ(numInputs_, inputs.size());
CHECK_EQ(numOutputs_, outputs.size());
const TensorShape& output = inputs[0].shape();
const TensorShape& input = inputs[1].shape();
const TensorShape& filter = outputs[0].shape();
check(input, filter, output);
real beta;
if (outputs[0].getArgType() == ADD_TO) {
beta = 1.0;
} else {
beta = 0.0;
}
size_t batchSize = input[0];
size_t inputChannels = input[1];
size_t inputHeight = input[2];
size_t inputWidth = input[3];
size_t filterHeight = filter[2];
size_t filterWidth = filter[3];
size_t outputChannels = output[1];
size_t outputHeight = output[2];
size_t outputWidth = output[3];
real* outputGrad = inputs[0].data<real>();
real* inputData = inputs[1].data<real>();
real* filterGrad = outputs[0].data<real>();
size_t size = inputChannels / groups_ * filterHeight * filterWidth *
outputHeight * outputWidth;
resizeBuffer<Device>(size);
real* colData = reinterpret_cast<real*>(memory_->getBuf());
Im2ColFunctor<Device, real> im2col;
GemmFunctor<Device, real> gemm;
size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
size_t outputOffset =
(outputChannels / groups_) * outputHeight * outputWidth;
size_t filterOffset = filter.getElements() / groups_;
for (size_t i = 0; i < batchSize; i++) {
for (size_t g = 0; g < groups_; g++) {
im2col(inputData + g * inputOffset,
inputChannels / groups_,
inputHeight,
inputWidth,
filterHeight,
filterWidth,
strideH(),
strideW(),
paddingH(),
paddingW(),
outputHeight,
outputWidth,
colData);
int M = outputChannels / groups_;
int K = outputHeight * outputWidth;
int N = inputChannels / groups_ * filterHeight * filterWidth;
gemm(CblasNoTrans,
CblasTrans,
M,
N,
K,
1.0f,
outputGrad + g * outputOffset,
K,
colData,
K,
i == 0 ? beta : 1.0f,
filterGrad + g * filterOffset,
N);
}
inputData += inputChannels * inputHeight * inputWidth;
outputGrad += outputChannels * outputHeight * outputWidth;
}
}
};
REGISTER_TYPED_FUNC(GemmConv, CPU, GemmConvFunction);
REGISTER_TYPED_FUNC(GemmConvGradInput, CPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, CPU, GemmConvGradFilterFunction);
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(GemmConv, GPU, GemmConvFunction);
REGISTER_TYPED_FUNC(GemmConvGradInput, GPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, GPU, GemmConvGradFilterFunction);
#endif
} // namespace paddle
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/operators/reshape_op.h"
namespace paddle {
namespace operators {
class ReshapeOp : public framework::OperatorWithKernel {
public:
ReshapeOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
// input check
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of ReshapeOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of ReshapeOp should not be null.");
auto shape = ctx->Attrs().Get<std::vector<int>>("shape");
PADDLE_ENFORCE(shape.size() > 0, "Attr(shape) shouldn't be empty.");
auto x_dims = ctx->GetInputDim("X");
std::vector<size_t> neg_dims_idx;
for (size_t i = 0; i < shape.size(); ++i) {
PADDLE_ENFORCE(shape[i] > 0 || shape[i] == -1,
"Each dimension of Attr(shape) must be positive or -1.");
if (shape[i] == -1) {
neg_dims_idx.push_back(i);
PADDLE_ENFORCE(neg_dims_idx.size() <= 1,
"Only one dimension of Attr(shape) can be unknown.");
}
}
int64_t capacity =
std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>());
int64_t in_size = framework::product(x_dims);
if (neg_dims_idx.size() == 1) {
// dim infer
shape[neg_dims_idx[0]] = in_size / (-capacity);
// recalculate capacity
capacity = std::accumulate(shape.begin(), shape.end(), 1,
std::multiplies<int>());
}
// capacity check
PADDLE_ENFORCE(capacity == in_size,
"The size of Input(X) mismatches with Attr(shape).");
// resize output
std::vector<int64_t> shape_int64(shape.size(), 0);
std::transform(shape.begin(), shape.end(), shape_int64.begin(),
[](int a) { return static_cast<int64_t>(a); });
auto out_dims = framework::make_ddim(shape_int64);
ctx->SetOutputDim("Out", out_dims);
if (shape[0] == x_dims[0]) {
// Only pass LoD when the first dimension is equal between
// output and input.
ctx->ShareLoD("X", /*->*/ "Out");
}
}
};
class ReshapeOpMaker : public framework::OpProtoAndCheckerMaker {
public:
ReshapeOpMaker(framework::OpProto *proto,
framework::OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X", "The input tensor of reshape operator.");
AddOutput("Out", "The output tensor of reshape operator.");
AddAttr<std::vector<int>>("shape",
"(vector<int>) "
"Target shape of reshape operator.");
AddComment(R"DOC(
Reshape Operator.
Reshape Input(X) into the shape specified by Attr(shape).
An example:
Given a 2-D tensor X with 2 rows and 2 columns
[[1, 2], [3, 4]]
and target shape = [1, 4], the reshape operator will transform
the tensor X into a 2-D tensor:
[[1, 2, 3, 4]]
One dimension in the target shape can be set -1, and the real dimension
will be infered from the original shape of Input(X) and other
dimensions in the target shape.
)DOC");
}
};
class ReshapeGradOp : public framework::OperatorWithKernel {
public:
ReshapeGradOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) shouldn't be null.");
ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP(reshape, ops::ReshapeOp, ops::ReshapeOpMaker, reshape_grad,
ops::ReshapeGradOp);
REGISTER_OP_CPU_KERNEL(reshape,
ops::ReshapeKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(
reshape_grad, ops::ReshapeGradKernel<paddle::platform::CPUPlace, float>);
<commit_msg>polish code in reshape_op<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/operators/reshape_op.h"
namespace paddle {
namespace operators {
class ReshapeOp : public framework::OperatorWithKernel {
public:
ReshapeOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
// input check
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of ReshapeOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of ReshapeOp should not be null.");
auto shape = ctx->Attrs().Get<std::vector<int>>("shape");
PADDLE_ENFORCE(shape.size() > 0, "Attr(shape) shouldn't be empty.");
auto x_dims = ctx->GetInputDim("X");
std::vector<size_t> neg_dims_idx;
// set some dimension to -1 if it is unknown
const int unknown_size = -1;
for (size_t i = 0; i < shape.size(); ++i) {
PADDLE_ENFORCE(shape[i] > 0 || shape[i] == unknown_size,
"Each dimension of Attr(shape) must be positive or %d.",
unknown_size);
if (shape[i] == unknown_size) {
neg_dims_idx.push_back(i);
PADDLE_ENFORCE(neg_dims_idx.size() <= 1,
"Only one dimension of Attr(shape) can be unknown.");
}
}
int64_t capacity =
std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>());
int64_t in_size = framework::product(x_dims);
if (neg_dims_idx.size() == 1) {
// dim infer
shape[neg_dims_idx[0]] = in_size / (-capacity);
// recalculate capacity
capacity = shape[neg_dims_idx[0]] * (-capacity);
}
// capacity check
PADDLE_ENFORCE(capacity == in_size,
"The size of Input(X) mismatches with Attr(shape).");
// resize output
std::vector<int64_t> shape_int64(shape.size(), 0);
std::transform(shape.begin(), shape.end(), shape_int64.begin(),
[](int a) { return static_cast<int64_t>(a); });
auto out_dims = framework::make_ddim(shape_int64);
ctx->SetOutputDim("Out", out_dims);
if (shape[0] == x_dims[0]) {
// Only pass LoD when the first dimension is equal between
// output and input.
ctx->ShareLoD("X", /*->*/ "Out");
}
}
};
class ReshapeOpMaker : public framework::OpProtoAndCheckerMaker {
public:
ReshapeOpMaker(framework::OpProto *proto,
framework::OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X", "The input tensor of reshape operator.");
AddOutput("Out", "The output tensor of reshape operator.");
AddAttr<std::vector<int>>("shape",
"(vector<int>) "
"Target shape of reshape operator.");
AddComment(R"DOC(
Reshape Operator.
Reshape Input(X) into the shape specified by Attr(shape).
An example:
Given a 2-D tensor X with 2 rows and 2 columns
[[1, 2], [3, 4]]
and target shape = [1, 4], the reshape operator will transform
the tensor X into a 2-D tensor:
[[1, 2, 3, 4]]
One dimension in the target shape can be set -1, representing that its
size is unknown. In this case, the real dimension will be infered from
the original shape of Input(X) and other dimensions in the target shape.
)DOC");
}
};
class ReshapeGradOp : public framework::OperatorWithKernel {
public:
ReshapeGradOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) shouldn't be null.");
ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP(reshape, ops::ReshapeOp, ops::ReshapeOpMaker, reshape_grad,
ops::ReshapeGradOp);
REGISTER_OP_CPU_KERNEL(reshape,
ops::ReshapeKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(
reshape_grad, ops::ReshapeGradKernel<paddle::platform::CPUPlace, float>);
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.